dom4j-1.6.1/0000755000175000017500000000000010242120021012044 5ustar ebourgebourgdom4j-1.6.1/build.xml0000644000175000017500000006557510242120011013706 0ustar ebourgebourg dom4j-1.6.1/project.properties0000644000175000017500000000463410242120004015640 0ustar ebourgebourg# ------------------------------------------------------------------- # P R O J E C T P R O P E R T I E S # ------------------------------------------------------------------- maven.repo.remote=http://www.ibiblio.org/maven maven.junit.fork=true maven.compile.debug = on maven.compile.optimize = off maven.compile.deprecation = on maven.compile.target = 1.3 maven.compile.source = 1.3 maven.jarResources.basedir = ${basedir}/src/java # ------------------------------------------------------------------------ # M A V E N J A R O V E R R I D E # ------------------------------------------------------------------------ maven.jar.override = on # ------------------------------------------------------------------------ # J A L O P Y S E T T I N G S # ------------------------------------------------------------------------ maven.jalopy.style = jalopy.xml maven.jalopy.filesetExclude = org/dom4j/tree/ConcurrentReaderHashMap.java maven.checkstyle.properties = ${basedir}/checkstyle.xml maven.checkstyle.excludes = org/dom4j/tree/ConcurrentReaderHashMap.java # ------------------------------------------------------------------------ # Jars set explicity by path. # ------------------------------------------------------------------------ maven.jar.stax = ${basedir}/lib/jsr173_1.0_api.jar maven.jar.stax-ri = ${basedir}/lib/test/jsr173_1.0_ri.jar maven.jar.pull-parser = ${basedir}/lib/pull-parser-2.1.10.jar # ------------------------------------------------------------------- # J A V A D O C P R O P E R T I E S # ------------------------------------------------------------------- # Display the date on the Maven web site maven.xdoc.date = left # Display the maven version the web site is documenting maven.xdoc.version = ${pom.currentVersion} maven.javadoc.links = http://java.sun.com/j2se/1.3/docs/api/, http://java.sun.com/xml/jaxp/dist/1.1/docs/api/ # ------------------------------------------------------------------- # D O C P R O P E R T I E S # ------------------------------------------------------------------- maven.ui.banner.background = #fff maven.ui.banner.foreground = #000 # ------------------------------------------------------------------- # C L O V E R P R O P E R T I E S # ------------------------------------------------------------------- maven.clover.license.path = ${basedir}/lib/tools/clover.license maven.clover.excludes = org/dom4j/persistence/**dom4j-1.6.1/maven.xml0000644000175000017500000000352710242120004013704 0ustar ebourgebourg dom4j-1.6.1/xdocs/0000755000175000017500000000000012133227266013210 5ustar ebourgebourgdom4j-1.6.1/xdocs/navigation.xml0000644000175000017500000000362210242120010016046 0ustar ebourgebourg dom4j dom4j --> dom4j-1.6.1/xdocs/status.xml0000644000175000017500000016234010242120013015240 0ustar ebourgebourg Change History James Strachan

Fixed bug in BeanElement which prevented proper execution of the bean samples (contributed by Wonne Keysers).

STAXEventWriter now uses XMLEventConsumer instead of XMLEventWriter (contributed by Christian Niles).

Fixed bug in SAXReader that caused problems parsing files in OSX (reported by Paul Libbrecht).

Fixed bug in XMLWriter that caused whitespace to be added between successive calls of the characters(...) method (reported by Paul Libbrecht).

Improved performance of NamespaceCache in multithreaded environments (contributed by Brett Finnell).

Added flag to OutputFormat that supresses newline after XML declaration.

Upgraded dependencies to their latest version on ibiblio.

Added method to DocumentHelper that allows user to specify encoding when parsing an xml String (contributed by Todd Wolff).

Fixed a ClassCastException bug in BeanElement.

Fixed a bug in SAXContentHandler which caused a NullPointerException in some situations.

Fixed bug which prevented an element's namespace prefix from being registered for use in xpath expressions (contributed by Todd Wolff).

Fixed bug in XMLWriter that caused duplication of the default namespace declaration (reported by Todd Wolff).

Added a bunch of patches to make the dom4j DOM classes more DOM compliant (contributed by Curt Arnold).

Fixed bug in DispatchHandler which made the handler not reusable (reported by Ricardo Leon).

Fixed bug in SAXContentHandler that caused incorrect CDATA section parsing (contributed by Todd Wolff).

Fixed bug in SAXContentHandler that caused incorrect entity handling.

Fixed bug in XMLWriter causing padding to be disabled, even if enabled in the specified outputformat (reported by Bo Gundersen).

Added initial support for STaX streams (contributed by Christian Niles).

Fixed encoding bug in Document.asXML() and DocumentHelper.parseText().

Fixed bug in SAXReader that caused problems resolving relative URIs when parsing java.io.File Objects (reported by Kohsuke Kawaguchi).

The iterators returned by the Element.elementIterator(...) methods now support remove().

DOMWriter writes now DOM Level 2 attributes and elements (reported by Geert Dendoncker and Joury Gokel).

Use latest implementation of the Aelfred parser.

Fixed some problems with internal/external DTD declarations (reported by Bryan Thompson).

Upgraded to Jaxen 1.1 beta 2.

Ignore attribute order when comparing Elements in NodeComparator.

Fixed bug in XMLWriter where namespace declarations were duplicated.

Fixed bug in parsing a Processing Instruction (reported by Vladimir Kralik).

Added support for Stylesheet modes (reported by Mark Diggory).

Don't escape " and ' characters in attribute values if it's not necessary (contributed by Christian Niles).

Fixed some DOMNodeHelper issues (reported by Henner Kollmann).

Fixed some datatype issues (reported by Thomas Draier).

Fixed an bug where the EntityResolver was not set on the XMLReader.

Fixed multithreaded access on DefaultElement.

Fixed problem parsing XML Files (reported by Geoffrey Vlassaks).

Added xml:space attribute support based on XML Specification 1.0.

Maven build of dom4j is now nearly complete. Maven is now used for the website generation.

Fixed some bugs in BackedList (contributed by Alessandro Vernet).

Added patch supplied by Dan Jacobs that fixes some entity encoding problems in XMLWriter - cheers Dan!

Patched the DOMElement replaceChild method to return the correct Node and to throw a DOMException when trying to replace a non-existing child.

Added patch to BackedList that could cause IndexOutOfBoundsExceptions to be thrown that was kindly supplied by Andy Yang - thanks Andy!

Update of Cookbook containing a chapter about rule API.

Patched SAXWriter to not pass in null System or Public IDs which can cause problems in Saxon.

Patched dom4j to work against Jaxen 1.0 RC1 or later build.

Applied patch to bug found by Tom Oehser that XPath expressions using elements or attributes whose name starts with '_' were not being handled correctly. It turns out this was a SAXPath issue.

Applied patch to bug found by Soumanjoy Das that creating a new DOMDocument then calling createElement() would generate a ClassCastException.

Applied patch supplied by James Dodd that fixes a MIME encoding issue in the embedded Aelfred parser

Applied patch to fix bug found by David Frankson. Adding attributes with null values causes problems in XSLT engines so now adding a null valued attribute is equivalent to removing the attribute. So null attribute values are silently ignored. e.g.

Element element = ...;
element.addAttribute( "foo", "123" );
...
Attribute attribute = element.attribute( "foo" );
assertTrue( attribute != null );
...
element.addAttribute( "foo", null );
attribute = element.attribute( "foo" );
assertTrue( attribute == null );

Applied patch to bug found by Mike Skells that was causing XPath.matches() to return true for absolute XPaths which returned different nodes to the node provided to the XPath.

Applied patch provided by Stefan that was causing IndexOutOfBoundsException when using the evaluate() method in DefaultXPath on an empty result set. Also added a test case to org.dom4j.TestXPathBug called testStefan().

Applied patch suggested by Frank Walinsky, that XPath objects are now Serializable.

Applied patch provided by Bill Burton that fixes union pattern matching.

Added a new Swing TableModel for displaying XML data in a Swing user interface. It uses an XPath based model to define the rows and column values. A table definition can be specified using a simple XML format and then loaded in a small amount of code. e.g. here's an example of a table that will list the servlets used in a web.xml document

<table select="/web-app/servlet">
  <column select="servlet-name">Name</column>
  <column select="servlet-class">Class</column>
  <column select="../servlet-mapping[servlet-name=$Name]/url-pattern">Mapping</column>
</table>

Notice the use of the $Name XPath variable to access other cells on the row. Here's the pseudo code to display a table for an XML document.

Document tableDefinition = ...;
Document source = ...;
TableModel tableModel = new XMLTableModel( tableDefinition, source );
JTable table = new JTable( tableModel );

There is a sample program in samples/swing/JTableTool which will display any table definition for a given source XML document. There is an example table definition for the periodic table in xml/swing/tableForAtoms.xml.

Added a new helper method to make it easier to create namespace contexts for doing namespace aware XPath expressions. The new setNamespaceURIs(Map) method on XPath makes it easier to pass in the prefixes and URIs you wish to use in an XPath expression. Here's an example of it in action

Map uris = new HashMap();
uris.put( "SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/" );
uris.put( "m", "urn:xmethodsBabelFish" );        
XPath xpath = document.createXPath( "/SOAP-ENV:Envelope/SOAP-ENV:Body/m:BabelFish" );
xpath.setNamespaceURIs( uris );        
Node element = xpath.selectSingleNode( document );

In addition DocumentFactory has a setXPathNamespaceURIs(Map) method so that common namespace URIs can be associated with a DocumentFactory so namespace prefixes can be used across many XPath expressions in an easy way. e.g.

// register prefixes with my factory
Map uris = new HashMap();
uris.put( "SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/" );
uris.put( "m", "urn:xmethodsBabelFish" );        

DocumentFactory factory = new DocumentFactory();
factory.setXPathNamespaceURIs( uris );

// now parse a document using my factory
SAXReader reader = new SAXReader();
reader.setDocumentFactory( factory );
Document doc = reader.read( "soap.xml" );

// now lets use the prefixes
Node element = doc.selectSingleNode( "/SOAP-ENV:Envelope/SOAP-ENV:Body/m:BabelFish" );

There is a new mergeAdjacentText option available on SAXReader to concatenate adjacent text nodes into a single Text node.

In addition there is a new stripWhitespaceText option to strip text which occurs between start/end tags which only consists of whitespace.

For example, parsing the following XML with the stripWhitespaceText option enabled and the mergeAdjacentText option enabled will result in a single child node of the parent element, rather than 3 (2 text nodes containing whitespace and one element).

<parent>
  <child>foo</child>
</parent>

Note that this option will not break most mixed content markup such as the following, since its only whitespace between tag start/ends that gets removed; non-whitespace strings are not trimmed.

<p>hello <b>James</b> how are you?</p>

Both these options together can improve the parsing performance by around 10-12% depending on the structure of the document. Though the whitespace layout of the XML document will be lost, so only use these modes in data-centric applications like XML messaging and SOAP.

So a typical SOAP or XML messaging developer, who may care more about performance than preserving exact whitespace layout, may use the following code to make the SAX parsing more optimal.

SAXReader reader = new SAXReader();
reader.setMergeAdjacentText( true );
reader.setStripWhitespaceText( true );
Document doc = reader.read( "soap.xml" );

Applied patch to HTMLWriter to fix bug found by Dominik Deimling that was not correctly outputting CDATA sections correctly.

Patched the setName() method on Element so that elements can be renamed. Also added a new setQName() to the Element interface so that elements can be renamed in a namespace aware manner. Thanks to Robert Lebowitz for this.

Applied fix to bug found by Manfred Lotz that XMLWriter in whitespace trimming mode would sometimes not correctly insert a space when text is seperated by newlines. The Test case testWhitespaceBug() in org.dom4j.TestXMLWriter reproduces the bug that has now been fixed.

Applied patches supplied by Stefan Graeber that enhance the datatype support to support included schemata and derived element types.

Applied patches suggested by Omer van der Horst Jansen to enable dom4j to fully work properly on JDK1.1 platforms. There were some uses of java.util.Stack which have been changed to ArrayList.

Applied patches supplied by Maarten Coene that fixes some issues with using the correct DocumentFactory when using the DOM implementation.

Updated the MSV support to comply with the latest MSV version, 1.12 (Nov 01 2001). In addition the MSVDemo.java in dom4j/src/samples/validate has been replaced by JARVDemo.java which now uses the JARV API to validate a dom4j document using the MSV implementation. This demo can validate any XML document against any DTD, XML Schema, Relax NG, Relax or Trex schema - thanks to the excellent JARV API and MSV library.

Applied patches supplied by Steen Lehmann that fixes handling of external DTD entities in SAXContentHandler and fix the XML output of the ExternalEntityDecl

Applied patch to bug found by Steen Lehmann that XPath expressions on the root element were not correctly handling namespaces correctly. The test case is demonstrated in dom4j/src/test/org/dom4j/xpath/TestSelectSingleNode.java

Added patch found by Howard Moore when using XTags that XPath string values which contained strings with entities, such as the use of &amp; in a text, would result in redundant spaces occuring, breaking URLs.

Added a new package, org.dom4j.dtd which contains some DTD declaration classes which are added to the DocumentType interfaces List of declarations. This is useful for finding out details of the attribute or element delcarations inside either the internal or external DTD subset of a document.

To expand internal or external DTD subsets when parsing with SAXReader use the 2 properties on SAXReader (and SAXContentHandler).

SAXReader reader = new SAXReader();
reader.setIncludeInternalDTDDeclarations( true );
reader.setIncludeExternalDTDDeclarations( true );
Document doc = reader.read( "foo.xml" );

DocumentType docType = doc.getDocType();
List internalDecls = docType.getInternalDeclarations();
List externalDecls = docType.getExternalDeclarations();

This new feature means that XML documents which use internal DTD subsets, external DTDs or a mixture of internal and external DTD subsets can now be properly round tripped.

Note that there appears to be a bug in Crimson 1.1.3 which does not properly differentiate between internal or external DTD subsets. Refer to the startDTD() method of LexicalHandler for details of how startEntity/endEntity is meant to demark external DTD subsets.

Its our intention to expand internal DTD subsets by default (so that documents can be properly round tripped by default) but require external DTD subsets to be explicitly enabled via the property on the SAXReader (or SAXContentHandler). This bug in Crimson causes all DTD declarations to appear as internal DTD subsets, which both is a performance overhead and breaks round tripping of documents which just use external DTD declarations. So until this matter is resolved both internal and external declarations are not expanded by default.

Note that the code works perfectly against Xerces.

Applied patch submitted by Yuxin Ruan which fixes some issues with XML Schema Data Type support

Followed Dennis Sosnoski's suggestion, adding a null text String to an Element now throws an IllegalArgumentException. To ensure that the IllegalArgumentException is not thrown its advisable to check for null first. For example...

Element element = ...;
String text = ...;

// might throw IllegalArgumentException
// if text == null
element.addText( text );

// safer to do this
if ( text != null ) {
  element.addText( text );
}

Fixed problem found by Kesav Kumar Kolla whereby a deserialized Document could have problems if new elements were attempted to be added. The problem was an issue with DocumentFactory not correctly deserializing itself properly.

Fixed problem found by David Hooker with Ant build file for the binary and source distribution that was not including the manifest file in the distribution.

Applied patch submitted by Lari Hotari that was causing the XMLWriter to fail when used as a SAX XMLFilter or ContentHandler to turn SAX events into XML text. Thanks Lari!

Fixed bug found by Kohsuke Kawaguchi that there was a problem in XMLWriter during its serialization of a document which redeclared the default namespace prefix. It turned out to be a bug in org.dom4j.tree.NamespaceStack where redeclarations of namespace prefixes were not being handled properly during serialization. The test cases in org.dom4j.TestXMLWriter and org.dom4j.TestNamespaces have been improved to test these features more rigorously.

Fixed bug found by Toby that was causing a security exception in applets when using a DocumentFactory.

Implemented the suggestion by Kesav Kumar, that the detach() method now returns the node (this) so that moving nodes from one part of a document to any another can now be one line of code. Here's an example of it in use.

Document doc1 = ...;
Document doc2; = ...;
Element destination = doc2.getRootElement();
Element source = doc1.selectSingleNode( "//foo[@style='bar']" );

// lets move the source to the destination
destination.add( source.detach() );

Added better checking in selectSingleNode() implementation so that XPath expressions which do not return a Node throw a meaningful exception (not ClassCastException) informing the user of why the XPath expression did not succeed.

Added patch found by Kesav Kumar that a document containing null Strings would cause a NullPointerException to be thrown if it was passed into SAXWriter (used by the JAXP - XSLT code). Now the SAXWriter will quietly ignore null Strings, as will XMLWriter.

Added helper method setXMLFilter() to SAXReader making it easier to install SAX filters to filter or preprocess SAX events before a dom4j Document is created. Also added a new sample program called sax.FilterDemo that demonstrates how to use a SAX filter with dom4j.

Added full support for Jaxen function, namespace and variable context interfaces. This allows the XPath engine to be fully customized. e.g.

XPath xpath = document.createXPath( "//foo[@code='123']" );

// customize function, namespace and variable contexts
xpath.setFunctionContext( myFunctionContext );
xpath.setNamespaceContext( myNamespaceContext );
xpath.setVariableContext( myVariableContext );

List nodes = xpath.selectNodes( document );

Added new helper class org.dom4j.util.XMLErrorHandler which turns SAX ErrorHandler callbacks into XML that can then be output in a JAXM or SOAP message or styled via XSLT or whatever.

Added new helper method DocumentHelper.makeElement(doc, "a/b/c") which will navigate from a document or element to the given simple path, creating new elements along the way if need be. This allows elements to be found or created using a simple path expression mechansim.

Added helper method getQName(String qualifiedName) to Element so that easier element name matching can be done. Here are some examples of it in use.

// find all elements with a local name of "foo" 
// in any namespace
List list = element.elements( "foo" );

// find all elements with a local name "foo" 
// and the default namespace URI
List list = element.elements( element.getQName( "foo" ) );

// find all elements which match the local name "foo" 
// and the namespace URI mapped to the "x" prefix
List list = element.elements( element.getQName( "x:foo" ) );

Added helper method on org.dom4j.DocumentFactory called getQNames that returns a List of all the QNames that were used to parse the documents.

Added an EntityResolver property to SAXReader to make it easier to configure a specific EntityResolver.

Added patch so that patterns such as @id='123' and name()='foo' are now working properly again. Also patterns such as not(@id='123') work now too.

Patched the dynamic loading of classes to fix some ClassLoader issues found with some application servers.

Ported the data type support to work with the latest MSV library from Sun

Fixed bug spotted by Stefan Graeber that was causing a DocumentException to be thrown with Xerces when turning validation mode on.

Patched bug in QName which was using the qualified name rather than the local name along with the namespace URI to determine equality.

Added patch kindly supplied by Michal Palicka that SAXReader was passing in the wrong name for the SAX string-interning feature. Thanks Michal!

Fixed the behaviour of DocumentFactory.createXPathFilter() to use XPath filtering rather than XSLT style patterns. One of the major differences is that an XSLT pattern (used in the <xsl:template match="pattern"/> element in XSLT) works slightly differently. An element <foo> would match an XSLT pattern "foo" whereas an element <bar> could match an XPath filter "foo" if it contained a child <foo> element.

Patched the behaviour of Node.matches(String xpathExpression) so that it uses XPath filters now rather than XSLT patterns.

Patched bug in XRule implementation in org.dom4j.rule that was causing ordering problems when using stylesheets - the Rule precendence order was not being correctly used.

Backed out a previous patch added to 0.9 such that attributes with no namespace prefix are in no namespace. An attribute does not inherit the default namespace - the only way to put an attribute into a namespace is via a namespace prefix.

Patched XMLWriter to that a flush() is not required when using an OutputStream and the various sub-document write() methods are called such as write(Element), write(Attribute), write(Node), write(Namespace) etc.

Fixed bug in SAXReader that setEntityResolver() was not always behaving properly. Also the default entity resolver used to locate XML Schemas seems to work properly now.

Moved the XML Schema Data Type supporting classes in org.dom4j.schema.Schema* to org.dom4j.datatype.Datatype*. This should avoid confusion and better describe the intent of the classes, to implement Data typing, rather than schema validation. We hope to use the MSV library for all of our schema validation requirements.

The XPath engine in dom4j has been migrated to using Jaxen. This single XPath engine can be plugged into any model such that Jaxen will support DOM, dom4j, EXML and JDOM. Hopefully we'll get Jaxen working on Java Beans too.

In general this will mean a much better, more compliant and more bug-free XPath engine for dom4j as it will be used extensively across XML object models.

Already numerous irregularities have been fixed in the XPath support in dom4j. We have donated the dom4j XPath test harness to Jaxen so that we now have a large rigorous test harness to ensure correct XPath behaviour - this test harness is run against all 4 current XML object models to ensure consistent behaviour and valid XPath compliance.

We are also in the process of migrating over our XPath extension functions as well as adding additional XPath functions such as those defined in XSLT and XPointer.

New class org.dom4j.io.XMLResult which is-a JAXP Result which uses the same org.dom4j.io.OutputFormat object to provide its formatting options to allow XML output from JAXP (such as via XSLT) to be pretty printed.

XMLWriter now implements the SAX XMLFilter interface so that it can be added to a SAX parsing filter chain to output the XML being parsed in a simple way. Many thanks to Joseph Bowbeer for his help in this area.

Added setProperty() and setFeature() methods to SAXReader to allow the easy configuration of custom parser properties via SAXReader, such as being able to specify the location of schema or DTD resources.

Added new method OutputFormat.createCompactFormat() for those wishing to output their XML in a compact format, such as in messaging systems.

Fixed bug in getNamespaceForPrefix() where if the prefix is null or "" and there is a default namespace defined, this method was returning a namespace instance with the incorrect URI.

Patched DOM writer so that it uses JAXP if it is available on the CLASSPATH using namespace aware mode by default.

Fixed a number of issues relating to namespaces and the redefinition of namespace prefixes. We now have a quite aggressive JUnit test harness to ensure that we handle namespace URIs correctly when prefixes are mapped and unmapped.

Applied patch from Andrew Wason for HTMLWriter to support the full HTML 4.01 DTD elements which do not require proper XML element closes. The new elements are PARAM, AREA, LINK, COL, BASE and META.

Fixed bug found by Dennis Sosnoski that SAX warnings were causing exceptions to be thrown by the SAXReader. Now warnings are silently ignored. If you want to detect warnings then an ErrorHandler should be registered with the SAXReader.

Patched bug that was also found by Jonathan Doughty for the non-standard behaviour of the FilterIterator. Also added Jonathan's JUnit test case to the distribution so that this problem should not come back.

Fixed bug that when round tripping into JAXP and back again, sometimes additional namespace attributes were appearing. Now the TestRoundTrip JUnit test case includes JAXP round tripping.

Fixed bug that attributes without a namespace prefix which are inside an element with a default namespace declaration of the form xmlns="theURI", the attribute now correctly inherits the namespace URI.

Applied patch found by Stefan Graeber that the UserDataFactory was not correctly creating UserDataAttribute instances.

Fixed bug that SAXWriter and DocumentSource were not correctly producing lexical events such as entities, comments and DOCTYPE declarations. Many thanks to Joseph Bowbeer for his help in this area.

hasContent()

has been added to the Node interface so that it is easy to decide if a node is a leaf node or not. This method was suggested by Dane Foster. This method returns true if the node is a Branch (i.e. an Element or Document) which contains at least one node.

getPath(Element context)
getUniquePath(Element context)

These new methods allow paths and unique paths to be created relatively. Previously both getPath() and getUniquePath() would create absolute XPath expressions. These new methods allow relative path expressions to be created by providing an ancestor Element from which to make the path expression. This method was suggested by Chris Nokleberg.

Fixed bug found by Chris Nokleberg when using the UserDataElement that the clone() and createCopy() methods were not correctly copying the user data object. A JUnit test case has been added that tests this fix (org.dom4j.TestUserData). If any deep copying of user data objects is required then UserDataElement now has a method getCopyOfUserData() which can be overloaded to perform a deep copy of any user data objects if required.

Minor patch for dom4j implementors wishing to create their own QName implementations. Previously the DocumentFactory class was hardwired to use QNameCache internally which was hard wired to only create QName instances. Now some factory methods have been added such that you can derive your own DocumentFactory which uses your own QNameCache which creates your own QName classes.

If JAXP can be found in the CLASSPATH then it is now used first by the SAXReader to find the correct SAX parser class. We have found that sometimes (e.g. Tomcat 4.0 beta 6) the value of the org.xml.sax.driver system property is set to a class which is not in the CLASSPATH but a valid JAXP parser is present. So now we try JAXP first, then the SAX system property then if all else fails we use the bundled Aelfred SAX parser.

Fixed XPath bug found by James Elson that the path /foo[@a and @b] or /foo[@a='1' and @b='2'] was no longer working correctly. This is now fixed and many tests of this nature have been added to the JUnit test harness.

Fixed some namespace related bugs found by Steen Lehmann. It appears that for a document of:-

<a xmlns="dummyNamespace">
  <b>
    <c>Hello</c>
  </b>
</a>

Then the path /a/b/c will not find anything - this is correct according to the XPath spec. Instead the path /*[name()='a']/*[name()='b']/*[name()='c'] is required. These changes have been applied to getPath() and getUniquePath() such that these methods now work, irrespectively of the namespaces used in a document. Finally many new test cases have been added to validate a variety of XPath expressions with various uses of namespaces.

SAXWriter now fully supports the SAX feature "http://xml.org/sax/features/namespace-prefixes". Failure to support this feature properly was causing problems when outputting a dom4j Document using JAXP - the namespace declarations often did not appear correctly.

Patched bug in XMLWriter which caused multiple duplicate namespace declarations to sometimes appear.

The SAXPath project is a Simple API for XPath parsing. Its analogous to SAX in that the API abstracts away the details of parsing XPath expressions and provides a simple event based callback interface.

Originally dom4j was using a parser generated via the Antlr tool which resulted in a considerably larger code base. Now dom4j uses SAXPath for its XPath parsing which results in faster XPath parsing and a much smaller code base.

The dom4j.jar is now about 100 Kb smaller! Also several XPath related bugs are now fixed. For example the numeric paths like '2 + count(//foo)' are now working.

Fixed bug found by Tobias Rademacher that XML Schema Data Type support wasn't working correctly when the XSD document used a namespace prefix. The bug was hidden by a further bug in the JUnit test case that was not correctly testing this case. Both these bugs are now fixed.

Fixed bug found by Piero de Salvia that some invalid XPath expressions were not correctly throwing exceptions. Now any attempt to use any invalid XPath expressions should result in an InvalidXPathException being thrown.

Applied patch submitted by Theodor Schwarzinger that fixes the preceding-sibling and preceding axes.

Fixed bug found my James Elson that the normalize() method was being quite agressive and removing all text nodes! New JUnit test case added to ensure this doesn't break again.

Improved the setContent() semantics on Branch (and so Element and Document) such that the parent and document relationships are correctly removed for old content and added for new content. As a helper method, the setContent() method will clone any content nodes which are already part of an existing document. So for example the following code will clone the content of a document.

    Document doc1 = ...;
    Document doc2 = DocumentHelper.createDocument();  
    doc2.setContent( doc1.content() );
Though this behaviour is much more useful when used with elements...
    Element sourceElement;
    Element destElement;

    // copy the content of sourceElemenet
    destElement.setContent( sourceElement.content() );

Support has been added for Java Serialization so dom4j documents can be serialized over RMI or EJB calls. Note that currently Serialization is much slower (by a factor of 2-5 times) than using the textual format of XML so we recommend sending XML text over RMI rather than serialization if possible. Over time we will tune the serialization implementation to be at least as fast as using the text format (even if that means under the covers we just use the text format).

Fixed bug in XPath engine found by Christophe Ponsard for paths of the form /* which were not finding anything. Now we have an extensible XPath test harness (in src/test/org/dom4j/TestXPathExamples.java) which contains some test cases for these kinds of paths. We can extend these cases to test other XPath expressions easily.

Fixed bug in elementByID() method found by Thomas Nichols that was resulting in the element not being found correctly.

Fixed bug in IndexedElement reported by Kerstin Gr�nefeld that was causing a null pointer exception when using XPath on an IndexedElement.

Applied the patch supplied by Mike Skells that fix problems with the getUniquePath() method not returning properly indexed elements

Applied a fix to the problem found by Dane Foster when using dom4j with JTidy. JTidy returns null for getLocalName() so DOMReader has been patched to handle nulls returned from either getLocalName() or getName().

Fixed bug reported anonymously to the Sourceforge Site here that explicitly creating a Document from an existing Element could cause problems when using XMLWriter.

Assorted performance tunings of SAX parsing, avoiding unnecessary repeated code paths.

Tidied factory and construction of Element code such that there are no longer dependencies on the SAX Attributes class. This was originally added as a performance enhancement, but after further refactoring this is now no longer needed. This makes the process of creating new Element derivations or DocumentFactory implementations easier.

For those wishing to do value based comparisons of Nodes, Element, Attributes, Documents or Document fragments there is a new NodeComparator class which implements the Comparator interface from the Java Collections Framework.

A new helper method has been added for parsing text. For example:-

    Document document = DocumentHelper.parseText(
        "<team> <author>James</author> </team>"
    );

The Branch interface (and so Document and Element interfaces) has a new normalize() method that has the same semantics as the same method in the DOM API to remove empty Text nodes and merge adjacent Text nodes.

A document can now be constructed more easily now that the addXXX() methods return a reference to the Document or Element which created them. An example is shown below

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Foo {

    public Document createDocument() {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement( "root" );

        Element author1 = root.addElement( "author" )
            .addAttribute( "name", "James" )
            .addAttribute( "location", "UK" )
            .addText( "James Strachan" );
        
        Element author2 = root.addElement( "author" )
            .addAttribute( "name", "Bob" )
            .addAttribute( "location", "Canada" )
            .addText( "Bob McWhirter" );

        return document;
    }
}

Note that the addElement() method returns the new child element not the parent element.

To promote consistency, the Element.setAttributeValue() method is now deprecated and should be replaced with Element.addAttribute().

Applied Theo's patch for cloning of Documents correctly together with JUnit test cases to ensure this keeps working.

Applied Rob Wilson's patch that NullPointerExceptions were being thrown if a Document is output with the XMLWriter and an attribute value is null.

Fixed problem found by Nicolas Fonrose that XPath expressions using namespace prefixes were not working correcty.

Fixed problem found by Thomas Nichols whereby default namespaces with no prefix were not being processed correctly. As a result of finding this bug we now have a rigorous JUnit round trip test harness in place which highlighted a number of issues with namespaces when round tripping from dom4j to SAX to DOM to Text and back again. These issues have now been fixed and should not show up again hopefully.

Fixed some detach() bugs that were found with Attributes.

Default encoding is now "UTF-8" rather than "UTF8". Thanks to Thomas Nichols for spotting that one. Also the default line seperator when using XMLWriter is now "\n" rather than "\r\n"

If an XMLWriter is used with an OutputStream then an explicit call to flush() is no longer required after calling write(Document)

Some housekeeping was performed in the naming of some implementation classes. The old XPathXXX.java classes in the org.dom4j.tree package where XXX = Attribute, CDATA, Comment, Entity, ProcessingInstruction and Text have been renamed to DefaultXXX and the corresponding DefaultXXX has been renamed to FlyweightXXX. This makes it clearer the purpose of these implementation classes. The default implementations of the leaf nodes are mutable but cannot be shared across elements. The FlyweightXXX implementations are immutable and can be shared across nodes and documents.

A new enhanced event notification mechanism has been implemented by David White. Now you can register multple ElementHandler instances with a SAXReader object before you parse a document such that the different handlers are notified when different paths are reached.

The ElementHandler interface now has both onStart() and onEnd() allowing more fine grained control over when you are called and the ability to perform actions before or after the content for an Element is populated. The methods also take a reference to a ElementPath to allow more optimised and powerful access to the path to the specified document.

This release contains an alpha release of XML Schema Data Type support. The main class in question is the XML Schema Data Type aware DatatypeDocumentFactory which will create an XML Schema Data Type aware XML object model.

The getData() and setData(Object) methods on Attribute and Element allow access to the concrete data types such as Dates and Numbers.

Applied Theo's patch for the XPath substring function that was causing the incorrect string indexes to be returned. The substring now returns the correct answer.

Applied Theo's patch for incorrectly escaping of element text.

Fixed bug in the XPath engine for absolute path expressions which now work correctly when applied to leaf nodes.

Fixed bug in the name() and local-name() functions such that the following expressions now work fine local-name(..), name(parent::*).

A variety of minor performance tuning optimisations have been made.

The org.dom4j.io.OutputFormat class now has a new helper method to make it easier to create pretty print formatting objects. The new method is OutputFormat.createPrettyPrint(). So to pretty print some XML (trimming all whitespace and indenting nicely) the following code should do the job...

    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter( out, format );
    writer.write( document );
    writer.close();

SAXReader.read(String url) can now accept either a URL or a file name which makes things a little easier. The logic uses the existence of a ':' in the url String to determine if it should be treated as a URL or a File name.

For more explicit control over whether documents are Files or URLs call SAXReader.read(File file) or SAXReader.read(URL url)

A new extension function, matrix-concat() was submitted by James Pereira. By default, doing concat() functions in XPath the 'string-value' is taken for each argument. So for a document:-

<root project="dom4j">
    <contributor>James Pereira</contributor>
    <contributor>Bob McWhirter</contributor>
</root;>

Then the XPath

concat( 'thanks ', /root/contributor )

would return

"thanks James Pereira"

as the /root/contributor expression matches a node set of 2 elements, but the "string-value" takes the first elements text. Whereas matrix-contact will do a cartesian product of all the arguments and then do the concatenation of each combination of nodes. So

matrix-concat( 'thanks ', /root/contributor )

will produce

"thanks James Pereira"
"thanks Bob McWhirter"

The cartesian product is done such that multiple paths can be used.

matrix-concat( 'thanks ', /root/contributor, ' for working on ', '/@project' )

will produce

"thanks James Pereira for working on dom4j"
"thanks Bob McWhirter for working on dom4j"

Fixed bug where XMLWriter.write(Object) was not correctly writing a Document instance.

Finally, a couple of small issues with the build process have been fixed. The dom4j.jar no longer contains any SAX or DOM classes (they are all in dom4j-full.jar) And the Antlr grammar files for the XPath parser are now corrrectly included in the binary distribution.

There following new features were added:-

  • Clean integration with XSLT via JAXP / TrAX API.
  • New SAXValidator to allow validation on prebuild Document instances
  • XMLWriter and HTMLWriter rewritten so that they work at either the SAX level or the dom4j level. API much improved and more like Reader and Writer in the JDK.
  • API modified to avoid clashes with WC3 DOM such that a dual implementation of dom4j and DOM is now possible. An early alpha release of a DOM implementation of dom4j is available.
  • New sorting method added to Node for easier selections of nodes which are sorted via an XPath expression. The following code sorts all CUSTOMER elements by their name attributes and removes duplicates:-
    Document document 
      = new SAXReader().read( new File( "customers.xml" ) );
    
    List customers 
      = document.selectNodes( "//CUSTOMER", "@name", true );
                  
  • The getText() and getStringValue() methods of Element now return the textual values of CDATA, Entity and Text nodes. The previous version only returned Text node values.
  • Refactored code and removed XPathEngine, XPathHelper and all the static newXXX() methods in DocumentFactory. Added equivalent methods to DocumentHelper and DocumentFactory.

This release also includes full XPath source code.

Initial release which comes complete with DOM, JAXP and SAX support and integrated XPath

  • The internal subset does not pass through DOMReader and DOMWriter. This needs patching!
  • We should add support for Xerces XNI API via an XNIReader and XNIWriter. This would also allow dom4j users to make good use of the NekoHTML parser thats layered on top of XNI.
  • Better documentation and user guides
  • A lazy parser; implement a special Element implementation (or probably a special List) which allows the XPP (XML Pull Parser) to parse the document as it is navigated rather than all up front.
  • Build a dom4j validator based on top of Suns MSV library
  • Ensure that the optional DOM implementation passes the DOM compliance tests
  • Implement a ValidatingDocumentFactory and an EncodingDocumentFactory which can be used by developers where invalid strings may be specified allowing validation or encoding of names or text values to be done in one place for use across parsers or application code. This would avoid any performance hit by making this kind of validation the default behaviour.
  • Implement a canonical XML processor
  • Implement XML Signature
  • Implement XPointer, XLink and XInclude
  • Build a version of XMLC which uses the dom4j API rather than DOM which could also make use of XPath, XSLT and Java 2 Collections support.
  • Consider adding support for Java Generics such that typesafe Iterators can be used. For example
    Iterator<Node> iter = element.nodeIterator();
    while ( iter.hasNext() ) {
        Node node = iter.next();
    }
    
    Iterator<Element> iter2 = element.elementIterator( "foo" );
    while ( iter2.hasNext() ) {
        Element foo = iter2.next();
    }
              
  • Implement XSLT engine on top of dom4j?
  • XML Query implementation on top of dom4j?

The following functions are not yet fully supported in the inbuilt XPath engine

  • id()
  • generate-id()
  • format-number()

The optional W3C DOM implementation of the dom4j API is not yet at full DOM compliance

The following people have contributed to the dom4j project. Many thanks to you all!

  • James Strachan
  • Bob McWhirter
  • James Dodd
  • James Elson
  • Jakob Jenkov
  • James Pereira
  • David White
  • Tobias Rademacher
  • Rashmi Mathew
  • Jonathan Doughty
  • Joseph Bowbeer
  • Michal Palicka
  • Yuxin Ruan
  • Steen Lehmann
  • Maarten Coene
  • Stefan Graeber
dom4j-1.6.1/xdocs/faq.fml0000644000175000017500000005334110242120024014444 0ustar ebourgebourg General What is dom4j?

dom4j is an Open Source XML framework for Java. dom4j allows you to read, write, navigate, create and modify XML documents. dom4j integrates with DOM and SAX and is seamlessly integrated with full XPath support.

What is the dom4j license?

We use an Apache-style open source license which is one of the least restrictive licenses around, you can use dom4j to create new products without them having to be open source.

You can find a copy of the license here.

What do I need to add to my CLASSPATH?

The dom4j.jar only contains the dom4j classes. If you want to use a SAX parser, you'll have to include the SAX classes and the SAX parser of your choice to your CLASSPATH. If you want to use XPath expressions, you also have to include the jaxen.jar to your CLASSPATH.

dom4j can use your existing XML parser and/or DOM implementation (such as Crimson or Xerces if you want it to. dom4j can also use JAXP to configure which SAX Parser to use - just add the jaxp.jar to your CLASSPATH and whichever SAX parser you wish away you go.

How does dom4j relate to DOM?

DOM is a quite large language independent API. dom4j is a simpler, lightweight API making extensive use of standard Java APIs such as the Java 2 collections API.

Remark that dom4j fully supports the DOM standard allowing both APIs to be used easily together.

How does dom4j relate to JDOM?

dom4j is a different project and different API to JDOM though they both have similar goals. They both attempt to make it easier to use XML on the Java platform. They differ in their design, API and implementation.

dom4j is based on Java interfaces so that plug and play document object model implementations are allowed and encouraged such as small, read only, quick to create implementations or bigger, highly indexed fast to naviagte implementations or implementations which read themselves lazily from a database or Java Beans etc.

dom4j uses polymorphism extensively such that all document object types implement the Node interface. Also both the Element and Document interfaces can be used polymorphically as they both extend the Branch interface.

dom4j is fully integrated with XPath support throughout the API so doing XPath expressions is as easy as

SAXReader reader = new SAXReader();
Document document = reader.read( url );
List links = document.selectNodes( "//a[@href]" );
String title = document.valueOf( "/head/title" );

dom4j will soon provide a configuration option to support the W3C DOM API natively to avoid unnecessary tree duplication when using dom4j with XSLT engines etc.

How does dom4j work with DOM and SAX?

You can create dom4j documents from XML text, SAX events or existing DOM trees or you can write dom4j documents as SAX events, DOM trees or XML text.

Using dom4j How can I use XSLT with dom4j?

dom4j integrates with XSLT using the JAXP standard (TrAX) APIs. A dom4j Document can be used as the source of XML to be styled or the source of the stylesheet. A dom4j Document can also be used as the result of a transformation.

First you'll need to use JAXP to load a Transformer.

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import org.dom4j.Document;
import org.dom4j.DocumentResult;
import org.dom4j.DocumentSource;
...

TransformerFactory factory 
  = TransformerFactory.newInstance();

Transformer transformer 
  = factory.newTransformer( new StreamSource( "foo.xsl" ) );

Now that you have a transformer its easy to style a Document into a new Document.

DocumentSource source = new DocumentSource( document );
DocumentResult result = new DocumentResult();
transformer.transform( source, result );

Document transformedDoc = result.getDocument();

If you want to transform a Document into XML text you can use JAXP as follows:-

DocumentSource source = new DocumentSource( document );
DocumentResult result = new StreamResult( new FileReader( "output.xml" ) );
transformer.transform( source, result );

For more information on JAXP and (TrAX) try Sun's JAXP site.

How can I pretty print my XML document?

You can control the format of the XML text output by XMLWriter by using the OutputFormat object. You can explicitly set the various formatting options via the properties methods of the OutputFormat object. There is also a helper method OutputFormat.createPrettyPrint() which creates the default pretty-print format.

So to pretty print some XML (trimming all whitespace and indenting nicely) the following code should do the job...

    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter( out, format );
    writer.write( document );
    writer.close();
How can I parse a document from a String?

Sometimes you have a String (or StringBuffer) which contains the XML to be parsed. This can be parsed using SAXReader and the StringReader from the JDK. For example:-

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

public class Foo {

    public Document getDocument() throws DocumentException {
        return DocumentHelper.parseText( 
            "<root> <child id='1'>James</child> </root>"
        );
    }
}
      
How do I compare 2 nodes for equality?

dom4j by default uses identity based equality for performance. It avoids having to walk entire documents or document fragments when putting nodes in collections.

To compare 2 nodes (attributes, elements, documents etc) for equality the NodeComparator can be used.

    Node node1 = ...;
    Node node2 = ...;
    NodeComparator comparator = new NodeComparator();
    if ( comparator.compare( node1, node2 ) == 0 ) {
        // nodes are equal!
    }

If you are having problems comparing documents that you think are equal but the NodeComparator decides that they are different, you might find the following useful.

In dom4j/test/src/org/dom4j/AbstractTestCase.java is-a JUnit TestCase and is an abstract base class for dom4j test cases. It contains a whole bunch of useful assertion helper methods for testing documents, nodes and fragments being equal. The nice thing is that you get useful messages telling you exactly why they are different, so its pretty easy to track down. For example.

    
public MyTest extends AbstractTestCase {
    ...
    public void testSomething() {
        Document doc1 = ...;
        Document doc2 = ...;

        assertDocumentsEqual( doc1, doc2 );
        ...

        assertNodesEqual( doc1.getRootElement(), doc2.getRootElement() );
    }
}
How does dom4j handle very large XML documents?

dom4j provides an event based model for processing XML documents. Using this event based model allows developers to prune the XML tree when parts of the document have been successfully processed avoiding having to keep the entire document in memory.

For example, imagine you need to process a very large XML file that is generated externally by some database process and looks something like the following (where N is a very large number).


    
        ...
    
    
        ...
    
    ...
    
        ...
    
]]>     
      

We can process each <ROW> at a time, there is no need to keep all of them in memory at once. dom4j provides a Event Based Mode for this purpose. We can register an event handler for one or more path expressions. These handlers will then be called on the start and end of each path registered against a particular handler. When the start tag of a path is found, the onStart method of the handler registered to the path is called. When the end tag of a path if found, the onEnd method of the handler registered to that path is called.

The onStart and onEnd methods are passed an instance of an ElementPath, which can be used to retrieve the current Element for the given path. If the handler wishes to "prune" the tree being built in order to save memory use, it can simply call the detach() method of the current Element being processed in the handlers onEnd() method.

So to process each <ROW> individually we can do the following.

// enable pruning mode to call me back as each ROW is complete
SAXReader reader = new SAXReader();
reader.addHandler( "/ROWSET/ROW", 
    new ElementHandler() {
        public void onStart(ElementPath path) {
            // do nothing here...    
        }
        public void onEnd(ElementPath path) {
            // process a ROW element
            Element row = path.getCurrent();
            Element rowSet = row.getParent();
            Document document = row.getDocument();
            ...
            // prune the tree
            row.detach();
        }
    }
);

Document document = reader.read(url);

// The document will now be complete but all the ROW elements
// will have been pruned.
// We may want to do some final processing now
...
      
Does dom4j support the Visitor Pattern?

Yes. dom4j supports the visitor pattern via the Visitor interface.

Here is an example.

protected void foo(Document doc) {
  
    // lets use the Visitor Pattern to 
    // navigate the document for entities

    Visitor visitor = new VisitorSupport() {
        public void visit(Entity entity) {
            System.out.println( 
                "Entity name: " + entity.getName() 
                + " text: " + entity.getText() 
            );
        }
    };

    doc.accept( visitor );
}
      
Can I sort the List returned by Node.selectNodes()?

Yes. The selectNodes() is a really useful feature to allow nodes to be selected from any object in the dom4j object model via an XPath expression. The List that is returned can be sorted by specifying another XPath expression to use as the sorting comparator.

For example the following code parses an XML play and finds all the SPEAKER elements sorted in name order.

SAXReader reader = new SAXReader();
Document document = reader.read( new File( "xml/much_ado.xml" ) );
List speakers = document.selectNodes( "//SPEAKER", "." );
      

In the above example the name of the SPEAKER is defined by the XPath expression "." as the name is stored in the text of the SPEAKER element. If the name was defined by an attribute called "name" then the XPath expression "@name" should be used for sorting.

You may wish to remove duplicates while sorting such that (for example) the distinct list of SPEAKER elements is returned, sorted by name. To do this add an extra parameter to the selectNodes() method call.

List distinctSpeakers = document.selectNodes( "//SPEAKER", ".", true );
      
What features are optional in dom4j?

In dom4j being able to navigate up a tree towards the parent and to be able to change a tree are optional features. These features are optional so that an implementation can create memory efficient read only document models which conserve memory by sharing imutable objects (such as interning Atttributes).

There are some helper methods to determine if optional features are implemented. Here is some example code demonstrating their use.

protected void foo(Node node) {
  
    // can we do upward navigation?
    if ( ! node.supportsParent() ) {
        throw new UnsupportedOperationException(
          "Cannot navigate upwards to parent"
        );
    }
    Element parent = node.getParent();

    System.out.println( "Node: " + node 
        + " has parent: " + parent 
    );

    if ( parent != null ) {

        // can I modify the parent?
        if ( parent.isReadOnly() ) {
            throw new UnsupportedOperationException(
              "Cannot modify parent as it is read only"
            );
        }

        parent.setAttributeValue( "bar", "modified" );
    }
}
      
What does the following mean 'Warning: Error occurred using JAXP to load a SAXParser. Will use Aelfred instead'

If dom4j detects JAXP on the classpath it tries to use it to load a SAX parser. If it can't load the SAX parser via JAXP it then tries to use the org.xml.sax.driver system property to denote the SAX parser to use. If none of the above work dom4j outputs a warning and continues, using its own internal Aelfred2 parser instead.

The following warning is a result of JAXP being in the classpath but either an old JAXP1.0 version was found (rather than JAXP 1.1) or there is no JAXP configured parser (such as crimson.jar or xerces.jar) on the classpath.

Warning: Error occurred using JAXP to load a SAXParser. Will use Aelfred instead

So the warning generally indicates an incomplete JAXP classpath and is nothing to worry excessively about. If you'd like to see the full verbose reason why the load of a JAXP parser failed then you can try setting the system property org.dom4j.verbose=true. e.g.

java -Dorg.dom4j.verbose=true MyApp

And you should see a verbose list of why the load of a SAX parser via JAXP failed.

To avoid this warning happening either remove the jaxp.jar from your classpath or add a JAXP 1.1. jaxp.jar together with a JAXP 1.1 parser such as crimson.jar or xerces.jar to your classpath.

What XML parser does dom4j use?

dom4j works with any SAX parser via JAXP. So putting a recent distribution of crimson.jar or xerces.jar on the CLASSPATH will allow Crimson or Xerces's parser to be used.

If no SAX parser is on the classpath via JAXP or the SAX org.xml.sax.driver system property then the embedded Aelfred distribution will be used instead. Note that the embedded Aelfred distribution is a non validating parser, though it is quite fast

How can I validate my document?

If a recent version of crimson.jar or xerces.jar is on the CLASSPATH then dom4j will use that as the SAX parser via JAXP. If none of these are on the CLASSPATH then a bundled version of Aelfred is used, which does not validate.

So to perform DTD validation when parsing put crimson.jar or xerces.jar on the CLASSPATH. If you wish to validate against an XML Schema then try xerces.jar. Then use the following code.

// turn validation on
SAXReader reader = new SAXReader(true);
Document document = reader.read( "foo.xml" );

Note: if you want to validate against an XML Schema with xerces, you need to enable the XML Schema validation with the "setFeature" method. For more information about xerces features visit the xerces website. Below is a code sample to enable XML Schema validation.

// turn validation on
SAXReader reader = new SAXReader(true);
// request XML Schema validation
reader.setFeature("http://apache.org/xml/features/validation/schema", true);
Document document = reader.read( "foo.xml" );

An alternative approach is to use Sun's MSV library for validation, which allows you to use DTD, XML Schema, Relax NG, Relax or TREX as the schema languages. There's an example in the daily build at dom4j/src/samples/validate/JARVDemo.java

If you are validating an existing dom4j document then we recommend you try MSV as it avoids turning the document into text and then parsing it again - MSV can work purely off of SAX events generated from the dom4j document.

Using this approach your code will actually be based on the JARV API which allows alternative validation mechanisms to be plugged into your code.

How do I import dom4j into VAJ?

VisualAge for Java checks all dependencies in a JAR and displays warnings if there are any unresolved links. To avoid any warnings the following steps should be followed (thanks to Jan Haluza for this).

  1. Uninstall all the packages having anything in common with the xml (com.ibm.xml* , org.w3c.dom ..) (these packages contains older definitions DOM ver. 1 ...
  2. Install the following jars
    dom4j.jar
    xalan.jar
    PullParser.jar  
    relaxng.jar
    msv.jar
    isorelax.jar
    xsdlib.jar
    crimson.jar
    
Cannot find DTD; how can I tell dom4j where to find the DTD from a DOCTYPE?

A common way around this is to implement a SAX EntityResolver to load the DTD from somewhere else. e.g. you could include the DTD in your JAR with your java code and load it from there.

EntityResolver resolver = new EntityResolver() {
    public InputSource resolveEntity(String publicId, String systemId) {
        if ( publicId.equals( "-//Acme//DTD Foo 1.2//EN" ) ) {
            InputStream in = getClass().getResourceAsStream(
                "com/acme/foo.dtd"
            );
            return new InputSource( in );
        }
        return null;
    }
};

SAXReader reader = new SAXReader();
reader.setEntityResolver( resolver );
Document doc = reader.parse( "foo.xml" );
dom4j-1.6.1/xdocs/guide.xml0000644000175000017500000002045510242120025015015 0ustar ebourgebourg Quick Start Guide James Strachan

The Quick Start Guide will hopefully show you how to do the basic operations in dom4j.

One of the first things you'll probably want to do is to parse an XML document of some kind. This is easy to do in dom4j. The following code demonstrates how to this.

import java.net.URL;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class Foo {

    public Document parse(URL url) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(url);
        return document;
    }
}

A document can be navigated using a variety of methods that return standard Java Iterators. For example

    public void bar(Document document) throws DocumentException {

        Element root = document.getRootElement();

        // iterate through child elements of root
        for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
            Element element = (Element) i.next();
            // do something
        }

        // iterate through child elements of root with element name "foo"
        for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) {
            Element foo = (Element) i.next();
            // do something
        }

        // iterate through attributes of root 
        for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {
            Attribute attribute = (Attribute) i.next();
            // do something
        }
     }

In dom4j XPath expressions can be evaluated on the Document or on any Node in the tree (such as Attribute, Element or ProcessingInstruction). This allows complex navigation throughout the document with a single line of code. For example.

    public void bar(Document document) {
        List list = document.selectNodes( "//foo/bar" );

        Node node = document.selectSingleNode( "//foo/bar/author" );

        String name = node.valueOf( "@name" );
    }

For example if you wish to find all the hypertext links in an XHTML document the following code would do the trick.

    public void findLinks(Document document) throws DocumentException {

        List list = document.selectNodes( "//a/@href" );

        for (Iterator iter = list.iterator(); iter.hasNext(); ) {
            Attribute attribute = (Attribute) iter.next();
            String url = attribute.getValue();
        }
    }

If you need any help learning the XPath language we highly recommend the Zvon tutorial which allows you to learn by example.

If you ever have to walk a large XML document tree then for performance we recommend you use the fast looping method which avoids the cost of creating an Iterator object for each loop. For example

    public void treeWalk(Document document) {
        treeWalk( document.getRootElement() );
    }

    public void treeWalk(Element element) {
        for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
            Node node = element.node(i);
            if ( node instanceof Element ) {
                treeWalk( (Element) node );
            }
            else {
                // do something....
            }
        }
    }

Often in dom4j you will need to create a new document from scratch. Here's an example of doing that.

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Foo {

    public Document createDocument() {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement( "root" );

        Element author1 = root.addElement( "author" )
            .addAttribute( "name", "James" )
            .addAttribute( "location", "UK" )
            .addText( "James Strachan" );
        
        Element author2 = root.addElement( "author" )
            .addAttribute( "name", "Bob" )
            .addAttribute( "location", "US" )
            .addText( "Bob McWhirter" );

        return document;
    }
}

A quick and easy way to write a Document (or any Node) to a Writer is via the write() method.

  FileWriter out = new FileWriter( "foo.xml" );
  document.write( out );

If you want to be able to change the format of the output, such as pretty printing or a compact format, or you want to be able to work with Writer objects or OutputStream objects as the destination, then you can use the XMLWriter class.

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class Foo {

    public void write(Document document) throws IOException {

        // lets write to a file
        XMLWriter writer = new XMLWriter(
            new FileWriter( "output.xml" )
        );
        writer.write( document );
        writer.close();


        // Pretty print the document to System.out
        OutputFormat format = OutputFormat.createPrettyPrint();
        writer = new XMLWriter( System.out, format );
        writer.write( document );

        // Compact format to System.out
        format = OutputFormat.createCompactFormat();
        writer = new XMLWriter( System.out, format );
        writer.write( document );
    }
}

If you have a reference to a Document or any other Node such as an Attribute or Element, you can turn it into the default XML text via the asXML() method.

        Document document = ...;
        String text = document.asXML();

If you have some XML as a String you can parse it back into a Document again using the helper method DocumentHelper.parseText()

        String text = "<person> <name>James</name> </person>";
        Document document = DocumentHelper.parseText(text);

Applying XSLT on a Document is quite straightforward using the JAXP API from Sun. This allows you to work against any XSLT engine such as Xalan or SAXON. Here is an example of using JAXP to create a transformer and then applying it to a Document.

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;

import org.dom4j.Document;
import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;

public class Foo {

    public Document styleDocument(
        Document document, 
        String stylesheet
    ) throws Exception {

        // load the transformer using JAXP
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer( 
            new StreamSource( stylesheet ) 
        );

        // now lets style the given document
        DocumentSource source = new DocumentSource( document );
        DocumentResult result = new DocumentResult();
        transformer.transform( source, result );

        // return the transformed document
        Document transformedDoc = result.getDocument();
        return transformedDoc;
    }
}
dom4j-1.6.1/xdocs/compare.xml0000644000175000017500000001056310242120020015340 0ustar ebourgebourg XML Object Model Comparisons James Strachan

This page attempts to survey the landscape of available XML object models and compare and contrast their features. The information in this table is correct to the best of our knowledge and we will try and keep this information as up to date as possible. If you think there's anything wrong, please let us know here.

Feature WC3 DOM DOM4J 1.5 JDOM 1.0 XOM 1.O
Open Source Yes Yes Yes Yes
Based on Java Interfaces Yes Yes No No
Supports Java 2 Collections No Yes Yes No
Can use any SAX parser and XMLFilter Yes (usually) Yes Yes Yes
Convert to and from DOM trees Yes Yes Yes Yes
Implements DOM interfaces Yes Yes (optional) No No
Integrated XPath API support No Yes No No
Bundled XPath implementation No Yes Optional No
Support for JAXP/TrAX for XSLT integration Yes Yes Yes Yes
Capable of processing a continuous XML streams Don't know Yes No Yes
Capable of processing massive documents Don't know Yes No Yes
XML Schema Data Type support No Yes No Don't know
XInclude support Don't know No No Yes
Canonical XML support Don't know No No Yes

Dennis Sosnoski has published an interesting article on IBM's developerWorks which compares the performance of a variety of XML document models for the Java platform including dom4j. You can find the very interesting results here.

Also you might find these new Performance Benchmarks interesting comparing dom4j and Jaxen against Xerces and Xalan.

dom4j-1.6.1/xdocs/images/0000755000175000017500000000000012133227266014455 5ustar ebourgebourgdom4j-1.6.1/xdocs/images/logo.gif0000644000175000017500000000206410242120015016065 0ustar ebourgebourgGIF89aff333???_L̿OOfff첟e???333OOOff?rOfffY/饏￯!,,@pH,LjgD:Шt*T2=vD_x4ig  p*oޱn}mHz|Fs_o,"%{GF)[) \N` ~`F oDPzxE D!u!G~aE D` mB@C6 gLu>L3ჺ ^` d<86B aju bq 8D%)} 姀I A"x+L01X 4|L yE䐶`lz!a2C(XuͣEHHHkH0jbCSB~KnCBtkwFÐlMvR P)`B nY7,T1A`z#{u6Oq=~ 8̄HЧE SC{t|-" Trʆ2D BDE$= 1brۄO\vYFTzF\{,0W>3W{1"!ʉ:AD Wr`dH. ^_6J !7"LZ& awf9HP[SG~@ CĒT@?GB(# ddm*Q ZժRh=Zc\!$pp=PlIqĪIOĊ,4)Mn@QX<@hzÒ`DE$lp+{ GH[RW,Iglq$`si |&;dom4j-1.6.1/xdocs/download.xml0000644000175000017500000000411510242120022015517 0ustar ebourgebourg Download dom4j James Strachan

The current release can be downloaded at SourceForge

You can download an interim snapshot build from the Maven repository

You can browse the current CVS repository here

To learn more about CVS go here.

This project's SourceForge CVS repository can be checked out through anonymous (pserver) CVS with the following instruction set. When prompted for a password for anonymous, simply press the Enter key.

cvs -d:pserver:anonymous@cvs.dom4j.org:/cvsroot/dom4j login 

cvs -d:pserver:anonymous@cvs.dom4j.org:/cvsroot/dom4j co dom4j
        

Updates from within the module's directory do not need the -d parameter.

Only project developers can access the CVS tree via this method. SSH1 must be installed on your client machine. Substitute developername with the proper values. Enter your site password when prompted.

export CVS_RSH=ssh 
 
cvs -d:ext:developername@cvs.dom4j.org:/cvsroot/dom4j co dom4j
        
dom4j-1.6.1/xdocs/benchmarks/0000755000175000017500000000000010242120006015304 5ustar ebourgebourgdom4j-1.6.1/xdocs/benchmarks/xpath/0000755000175000017500000000000012133227266016451 5ustar ebourgebourgdom4j-1.6.1/xdocs/benchmarks/xpath/item.xslt0000644000175000017500000000173510242120006020310 0ustar ebourgebourg
dom4j-1.6.1/xdocs/benchmarks/xpath/PerfDOM4J.java0000644000175000017500000002216610242120010020727 0ustar ebourgebourg import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.XPath; import org.dom4j.io.DOMWriter; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class PerfDOM4J { public static void main(String args[]) { Document doc; try { int numrec = 1; numrec = 10000; System.out.println("\n10000 Elements ------------------"); doc = PerfDOM4J.createDocument(numrec, 20, 1); PerfDOM4J.createW3CDOM(doc); PerfDOM4J.write(doc, "dom4j_" + numrec + ".xml"); // PerfDOM4J.parse(numrec,1); // PerfDOM4J.transform(doc,"item.xslt",1); PerfDOM4J.xpath(doc, "/*/*/Attr1x1", 1); PerfDOM4J.xpath(doc, "/*/*/Attr1x5000", 1); PerfDOM4J.xpath(doc, "/*/*/Attr1x9999", 1); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x1", 1); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x5000", 1); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x9999", 1); PerfDOM4J.xpathNodes(doc, "/*/Item", 3); numrec = 1000; System.out.println("\n1000 Elements -------------------"); doc = PerfDOM4J.createDocument(numrec, 20, 1); PerfDOM4J.createW3CDOM(doc); PerfDOM4J.write(doc, "dom4j_" + numrec + ".xml"); PerfDOM4J.parse(numrec, 3); PerfDOM4J.transform(doc, "item.xslt", 3); PerfDOM4J.xpath(doc, "/*/*/Attr1x1", 3); PerfDOM4J.xpath(doc, "/*/*/Attr1x500", 3); PerfDOM4J.xpath(doc, "/*/*/Attr1x999", 3); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x1", 3); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x500", 3); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x999", 3); PerfDOM4J.xpathNodes(doc, "/*/Item", 10); numrec = 100; System.out.println("\n100 Elements --------------------"); doc = PerfDOM4J.createDocument(numrec, 20, 10); PerfDOM4J.createW3CDOM(doc); PerfDOM4J.write(doc, "dom4j_" + numrec + ".xml"); PerfDOM4J.parse(numrec, 10); PerfDOM4J.transform(doc, "item.xslt", 10); PerfDOM4J.xpath(doc, "/*/*/Attr1x1", 10); PerfDOM4J.xpath(doc, "/*/*/Attr1x50", 10); PerfDOM4J.xpath(doc, "/*/*/Attr1x99", 10); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x1", 10); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x50", 10); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x99", 10); PerfDOM4J.xpathNodes(doc, "/*/Item", 100); numrec = 10; System.out.println("\n10 Elements ---------------------"); doc = PerfDOM4J.createDocument(numrec, 20, 100); PerfDOM4J.createW3CDOM(doc); PerfDOM4J.write(doc, "dom4j_" + numrec + ".xml"); PerfDOM4J.parse(numrec, 100); PerfDOM4J.transform(doc, "item.xslt", 10); PerfDOM4J.xpath(doc, "/*/*/Attr1x5", 1000); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x1", 1000); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x5", 1000); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x9", 1000); PerfDOM4J.xpathNodes(doc, "/*/Item", 1000); numrec = 1; System.out.println("\n1 Element -----------------------"); doc = PerfDOM4J.createDocument(numrec, 20, 100); PerfDOM4J.createW3CDOM(doc); PerfDOM4J.write(doc, "dom4j_" + numrec + ".xml"); PerfDOM4J.parse(numrec, 100); PerfDOM4J.transform(doc, "item.xslt", 10); PerfDOM4J.xpath(doc, "/*/*/Attr1x1", 1000); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x1", 1000); PerfDOM4J.xpathNodes(doc, "/*/Item", 1000); } catch (IOException ie) { ie.printStackTrace(); } } public static Document createDocument(int iNumRecs, int iNumFlds, int pp) { double start = System.currentTimeMillis(); Document document = null; for (int kk = 0; kk < pp; kk++) { document = DocumentHelper.createDocument(); Element root = document.addElement("ItemResultSet"); for (int ii = 0; ii < iNumRecs; ii++) { Element Record = root.addElement("Item"); for (int jj = 0; jj < iNumFlds; jj++) { Record.addElement("Attr" + jj + "x" + ii).addText( "123456789"); } } } double end = System.currentTimeMillis(); System.err.println("Creation time : " + (end - start) / pp); return document; } public static Document parse(int iNumRecs, int kk) { File file = new File("dom4j_" + iNumRecs + ".xml"); double start = System.currentTimeMillis(); Document document = null; for (int pp = 0; pp < kk; pp++) { try { SAXReader SAXrd = new SAXReader(); SAXrd.read(file); } catch (Exception e) { e.printStackTrace(); } } double end = System.currentTimeMillis(); System.err.println("Parsing time for :" + 1.000 * (end - start) / kk); return document; } public static void createW3CDOM(Document doc) { long start = System.currentTimeMillis(); try { DOMWriter dw = new DOMWriter(); dw.write(doc); } catch (Exception de) { } long end = System.currentTimeMillis(); System.err.println("W3C Creation time for :" + (end - start)); } public static void write(Document document, String name) throws IOException { long start = System.currentTimeMillis(); // lets write to a file try { OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter(name), format); writer.write(document); writer.close(); } catch (IOException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.err.println("DOM4J File write time :" + (end - start) + " " + name); } public static void transform(Document xmlDoc, String xslFile, int kk) { System.err.println("DOM4J start transform "); int ii = 1; try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource( xslFile)); long start = System.currentTimeMillis(); for (ii = 0; ii < kk; ii++) { Source source = new DocumentSource(xmlDoc); DocumentResult result = new DocumentResult(); transformer.transform(source, result); // output the transformed document } long end = System.currentTimeMillis(); System.err .println("DOM4J transform time :" + (end - start) / ii); } catch (Exception e) { e.printStackTrace(); } } public static void xpath(Document document, String xpathExp, int kk) { long start = System.currentTimeMillis(); XPath xpath = document.createXPath(xpathExp); for (int ii = 0; ii < kk; ii++) { Node node = xpath.selectSingleNode(document); if ((node != null) & (ii == 0)) { String val = node.getStringValue(); // System.out.println(val); } } long end = System.currentTimeMillis(); System.err.println("DOM4J xpath time :" + (end - start) / kk); } public static void xpathNodes(Document document, String xpathExp, int kk) { long start = System.currentTimeMillis(); XPath xpath = document.createXPath(xpathExp); for (int ii = 0; ii < kk; ii++) { try { List nodeList = xpath.selectNodes(document); if ((nodeList != null) && (nodeList.size() > 0)) { Node node = (Node) nodeList.get(0); if ((node != null) & (ii == 0)) { String val = node.getStringValue(); // System.out.println(val); } } } catch (Exception e) { e.printStackTrace(); } } long end = System.currentTimeMillis(); System.err.println("DOM4J xpath Nodes time :" + 1.000 * (end - start) / kk); } } dom4j-1.6.1/xdocs/benchmarks/xpath/w3c_100.xml0000644000175000017500000042212110242120011020224 0ustar ebourgebourg 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 dom4j-1.6.1/xdocs/benchmarks/xpath/index.html0000644000175000017500000013017510242120013020432 0ustar ebourgebourg Dom4J performance versus Xerces

Dom4J performance versus Xerces / Xalan

Martin Bhm, Jean-Jacques Dubray

Eigner Precision Lifecycle Management

www.eigner.com

Introduction

We have created a simple test bed to evaluate the performance of DOM4J versus Xerces/Xalan. These results are intended to give a rough idea rather than exhaustive test suite. In particular we focus our study on XML document which look like database result set. It is pretty clear that performance results may vary greatly based on the topology of your XML.

The test was designed with two topologies in mind: 

a) to have elements only and each element name is unique in the whole document.

<?xml version="1.0" encoding="UTF-8"?>

<ItemResultSet>

<Item>

<Attr0x0>123456789</Attr0x0>

<Attr1x0>123456789</Attr1x0>

<Attr2x0>123456789</Attr2x0>

<Attr3x0>123456789</Attr3x0>

<Attr4x0>123456789</Attr4x0>

<Attr5x0>123456789</Attr5x0>

<Attr6x0>123456789</Attr6x0>

<Attr7x0>123456789</Attr7x0>

<Attr8x0>123456789</Attr8x0>

<Attr9x0>123456789</Attr9x0>

<Attr10x0>123456789</Attr10x0>

<Attr11x0>123456789</Attr11x0>

<Attr12x0>123456789</Attr12x0>

<Attr13x0>123456789</Attr13x0>

...

</Item>

<Item>

<Attr0x1>123456789</Attr0x1>

<Attr1x1>123456789</Attr1x1>

<Attr2x1>123456789</Attr2x1>

...

</ItemResultSet>

b) To use attributes only

<?xml version="1.0" encoding="UTF-8"?>

<ItemResultSet>

<Item guid="0" Attr0="123456789" Attr1="123456789" .../>

<Item guid="1" Attr0="123456789" Attr1="123456789" .../>

</ItemResultSet>

 

 

We have tested for 1000,100,10,1 items the time it takes to:

  • create a document
  • write it to disk
  • reparse it from disk (I don't have a good disk)
  • transform it to some other XML format
  • run a series of XPath statements for both selectNodes and selectSingleNode (where applicable)

    a) 

    /*/*/Attr1x1

    /*/*/Attr1x500

    /*/*/Attr1x999

    /*/*/Item

    b) 

    /*/*[@id="1"]

    /*/*[@id="500"]

    /*/*[@id="999""]

All tests are running on my lapdog (PIII, 500MHz, 512Mb) We allocate a heap size of 256 Mb when we start the test.

 

Results

case a), comparison between Dom4j/Jaxen versus Xerces/Xalan

All times in ms
Create Document Write Document to disk Reparse the document from disk
Items dom4j xalan dom4j xalan dom4j xalan
1000 641.0 571.0 531 852 2020 2664
100 9.0 20.0 60 61 62.99 68.6
10 0.7 1.0 10 10 11.92 14.62
1 0.1 0.0 10 10 8.01 8.31

 

The most surprising result comes from executing XPath statements. Xalan does warn us in the JavaDoc that things could be a little slow.

selectSingleNode()

All times in ms 1000 Items in the document
dom4j Xalan
/*/*/Attr1x1 127 10
/*/*/Attr1x500 20 661
/*/*/Attr1x999 23 1662
100 Items in the document
dom4j  Xalan
/*/*/Attr1x1 2 3.0
/*/*/Attr1x50 3 13.0
/*/*/Attr1x99 2 55.1

 

selectNodes()

All times in ms 1000 Items in the document
dom4j Xalan
/*/*/Attr1x1 16.6 1633
/*/*/Attr1x500 20 1772
/*/*/Attr1x999 20.0 1733
/*/Item 2.0 1742
100 Items in the document
dom4j Xalan
/*/*/Attr1x1 1.0 35.0
/*/*/Attr1x50 2.0 36.1
/*/*/Attr1x99 1.0 49.0
/*/Item 0.2 49.0

 

selectNodes()

All times in ms /*/*/Attr1x500
dom4j  Xalan
1000 20.0 1793
100 2.0 36.1
10 0.1 11.72
1 0.1 4.3

 

case b), we use Dom4j/Jaxen and compare how it behaves with a document that contains only element elements versus document that model the same data as attribute attributes

All times in ms
Create Document Write Document to disk Reparse the document from disk
Items dom4j - elements dom4j - attrs dom4j - elements dom4j - attrs dom4j - elements dom4j - attrs
1000 641.0 100 531 140 2020 207
100 9.0 8.0 60 20 62.99 24
10 0.7 0.9 10 10 11.92 8.31
1 0.1 0.1 10 10 8.01 6.81

 

The most surprising result comes from executing XPath statements. Xalan does warn us in the JavaDoc that things could be a little slow.

selectSingleNode()

All times in ms 1000 Items in the document
Dom4j - elements dom4j - attrs
/*/*/Attr1x1 127 36
/*/*/Attr1x500 20 33
/*/*/Attr1x999 23 37
100 Items in the document
Dom4j - elements dom4j - attrs
/*/*/Attr1x1 2 4
/*/*/Attr1x50 3 4
/*/*/Attr1x99 2 4

 

selectNodes()

All times in ms 1000 Items in the document
dom4j - elements dom4j - attrs
/*/*/Attr1x1 16.6 36.6
/*/*/Attr1x500 20 36.6
/*/*/Attr1x999 20.0 36.6
/*/Item 2.0 1.7
100 Items in the document
Dom4j - elements dom4j - attrs
/*/*/Attr1x1 1.0 3.0
/*/*/Attr1x50 2.0 4.1
/*/*/Attr1x99 1.0 4
/*/Item 0.2 0.2

 

selectNodes()

All times in ms /*/*/Attr1x500
dom4j - elements dom4j - attrs
1000 20.0 36.6
100 2.0 4.1
10 0.1 0.4
1 0.1 0.1

 

c) We also run a simple XSLT test which took the first XML formant (elements) and transformed it to the second format (attr) or conversely.

All times in ms. dom4j el -> attr dom4j attr -> el Xalan el -> attr
10000 12558  10044  12338
1000 1181 874 1913
100 98 83 123
10 12 11 20
1 3 4 10

Conclusion

These number suggest one should use the XPathAPI class of Xalan with great caution, if at all

The syntax of Xpath statements must be chosen carefully. Contrary to some belief, and of the topology of our XML format, using /*/* or // was most efficient compared to the absolute path /ItemResultSet/Item

It appears more efficient to use selectNodes with Dom4j even if one needs a single node.

With DOM4J, it is about twice as fast when running XPath against a document which contains elements vs attributes.

In our case, we found that Dom4j is faster than Xalant for XSLT transformations. We do not claim this is  a general result, but rather a datapoint

Resources

Here's the source code and data for these tests. Try them for yourself

PerfDOM4J.java
PerfDOM4JAttr.java
PerfW3C.java
item.xslt
w3c_100.xml

 

 

dom4j-1.6.1/xdocs/benchmarks/xpath/PerfDOM4JAttr.java0000644000175000017500000002445210242120011021563 0ustar ebourgebourg import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.XPath; import org.dom4j.io.DOMWriter; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class PerfDOM4JAttr { public static void main(String args[]) { Document doc; try { int numrec = 1; numrec = 10000; System.out.println("\n1000 Elements -------------------"); doc = PerfDOM4JAttr.createDocument(numrec, 20, 1); PerfDOM4JAttr.createW3CDOM(doc); PerfDOM4JAttr.write(doc, "DOM4JAttr_" + numrec + ".xml"); PerfDOM4JAttr.parse(numrec, 1); // PerfDOM4JAttr.transform(doc,"item.xslt",1); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"1\"]", 3); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"500\"]", 3); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"999\"]", 3); PerfDOM4JAttr .xpathNodes(doc, "/ItemResultSet/Item[@guid=\"1\"]", 3); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"500\"]", 3); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"999\"]", 3); PerfDOM4JAttr.xpathNodes(doc, "/*/Item", 100); numrec = 1000; System.out.println("\n1000 Elements -------------------"); doc = PerfDOM4JAttr.createDocument(numrec, 20, 1); PerfDOM4JAttr.createW3CDOM(doc); PerfDOM4JAttr.write(doc, "DOM4JAttr_" + numrec + ".xml"); PerfDOM4JAttr.parse(numrec, 3); PerfDOM4JAttr.transform(doc, "item.xslt", 3); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"1\"]", 3); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"500\"]", 3); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"999\"]", 3); PerfDOM4JAttr .xpathNodes(doc, "/ItemResultSet/Item[@guid=\"1\"]", 3); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"500\"]", 3); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"999\"]", 3); PerfDOM4JAttr.xpathNodes(doc, "/*/Item", 100); numrec = 100; System.out.println("\n100 Elements --------------------"); doc = PerfDOM4JAttr.createDocument(numrec, 20, 10); PerfDOM4JAttr.createW3CDOM(doc); PerfDOM4JAttr.write(doc, "DOM4JAttr_" + numrec + ".xml"); PerfDOM4JAttr.parse(numrec, 10); PerfDOM4JAttr.transform(doc, "item.xslt", 10); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"1\"]", 10); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"50\"]", 10); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"99\"]", 10); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"1\"]", 10); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"50\"]", 10); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"99\"]", 10); PerfDOM4JAttr.xpathNodes(doc, "/*/Item", 100); numrec = 10; System.out.println("\n10 Elements ---------------------"); doc = PerfDOM4JAttr.createDocument(numrec, 20, 100); PerfDOM4JAttr.createW3CDOM(doc); PerfDOM4JAttr.write(doc, "DOM4JAttr_" + numrec + ".xml"); PerfDOM4JAttr.parse(numrec, 100); PerfDOM4JAttr.transform(doc, "item.xslt", 10); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"1\"]", 100); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"5\"]", 100); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"9\"]", 100); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"1\"]", 100); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"5\"]", 100); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"9\"]", 100); PerfDOM4JAttr.xpathNodes(doc, "/*/Item", 100); numrec = 1; System.out.println("\n1 Element -----------------------"); doc = PerfDOM4JAttr.createDocument(numrec, 20, 100); PerfDOM4JAttr.createW3CDOM(doc); PerfDOM4JAttr.write(doc, "DOM4JAttr_" + numrec + ".xml"); PerfDOM4JAttr.parse(numrec, 100); PerfDOM4JAttr.transform(doc, "item.xslt", 10); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"1\"]", 100); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"1\"]", 100); PerfDOM4JAttr.xpathNodes(doc, "/*/Item", 100); } catch (IOException ie) { ie.printStackTrace(); } } public static Document createDocument(int iNumRecs, int iNumFlds, int pp) { double start = System.currentTimeMillis(); Document document = null; for (int kk = 0; kk < pp; kk++) { document = DocumentHelper.createDocument(); Element root = document.addElement("ItemResultSet"); for (int ii = 0; ii < iNumRecs; ii++) { Element Record = root.addElement("Item").addAttribute("guid", "" + ii); for (int jj = 0; jj < iNumFlds; jj++) { Record.addAttribute("Attr" + jj, "123456789"); } } } double end = System.currentTimeMillis(); System.err.println("Creation time : " + (end - start) / pp); return document; } public static Document parse(int iNumRecs, int kk) { File file = new File("DOM4JAttr_" + iNumRecs + ".xml"); double start = System.currentTimeMillis(); Document document = null; for (int pp = 0; pp < kk; pp++) { try { SAXReader SAXrd = new SAXReader(); SAXrd.read(file); } catch (Exception e) { e.printStackTrace(); } } double end = System.currentTimeMillis(); System.err.println("Parsing time for :" + 1.000 * (end - start) / kk); return document; } public static void createW3CDOM(Document doc) { long start = System.currentTimeMillis(); try { DOMWriter dw = new DOMWriter(); dw.write(doc); } catch (Exception de) { } long end = System.currentTimeMillis(); System.err.println("W3C Creation time for :" + (end - start)); } public static void write(Document document, String name) throws IOException { long start = System.currentTimeMillis(); // lets write to a file try { OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter(name), format); writer.write(document); writer.close(); } catch (IOException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.err.println("DOM4JAttr File write time :" + (end - start) + " " + name); } public static void transform(Document xmlDoc, String xslFile, int kk) { System.err.println("DOM4JAttr start transform "); int ii = 1; try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource( xslFile)); long start = System.currentTimeMillis(); for (ii = 0; ii < kk; ii++) { Source source = new DocumentSource(xmlDoc); DocumentResult result = new DocumentResult(); transformer.transform(source, result); // output the transformed document } long end = System.currentTimeMillis(); System.err.println("DOM4JAttr transform time :" + (end - start) / ii); } catch (Exception e) { e.printStackTrace(); } } public static void xpath(Document document, String xpathExp, int kk) { long start = System.currentTimeMillis(); XPath xpath = document.createXPath(xpathExp); for (int ii = 0; ii < kk; ii++) { Node node = xpath.selectSingleNode(document); if ((node != null) & (ii == 0)) { String val = node.getStringValue(); // System.out.println("xpath OK:"+val); } } long end = System.currentTimeMillis(); System.err.println("DOM4JAttr xpath time :" + (end - start) / kk); } public static void xpathNodes(Document document, String xpathExp, int kk) { long start = System.currentTimeMillis(); XPath xpath = document.createXPath(xpathExp); for (int ii = 0; ii < kk; ii++) { try { List nodeList = xpath.selectNodes(document); if ((nodeList != null) && (nodeList.size() > 0)) { Node node = (Node) nodeList.get(0); if ((node != null) & (ii == 0)) { String val = node.getStringValue(); // System.out.println("xpathNodes OK:"+val); } } } catch (Exception e) { e.printStackTrace(); } } long end = System.currentTimeMillis(); System.err.println("DOM4JAttr xpath Nodes time :" + 1.000 * (end - start) / kk); } } dom4j-1.6.1/xdocs/benchmarks/xpath/PerfW3C.java0000644000175000017500000002074310242120012020507 0ustar ebourgebourg import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import org.apache.xerces.dom.DocumentImpl; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.apache.xpath.XPathAPI; import org.dom4j.io.SAXReader; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class PerfW3C { public static void main(String args[]) { Document doc; System.err.println("W3C createDocument:"); int numrec; long start = 0; long end = 0; numrec = 1000; System.out.println("\n1000 Elements ---------------------------------"); doc = PerfW3C.createDocument(numrec, 20, 1); PerfW3C.write(doc, "w3c_" + numrec + ".xml"); PerfW3C.parse(numrec, 1); PerfW3C.transform(doc, "item.xslt", 1); PerfW3C.xpath(doc, "/*/*/Attr1x1", 1); PerfW3C.xpath(doc, "/*/*/Attr1x500", 1); PerfW3C.xpath(doc, "/*/*/Attr1x999", 1); PerfW3C.xpathNodes(doc, "/*/*/Attr1x1", 1); PerfW3C.xpathNodes(doc, "/*/*/Attr1x500", 1); PerfW3C.xpathNodes(doc, "/*/*/Attr1x999", 1); PerfW3C.xpathNodes(doc, "/*/Item", 1); numrec = 100; System.out.println("\n100 Elements ----------------------------------"); doc = PerfW3C.createDocument(numrec, 20, 1); PerfW3C.write(doc, "w3c_" + numrec + ".xml"); PerfW3C.transform(doc, "item.xslt", 10); PerfW3C.parse(numrec, 10); PerfW3C.xpath(doc, "/*/*/Attr0x1", 10); PerfW3C.xpath(doc, "/*/*/Attr0x50", 10); PerfW3C.xpath(doc, "/*/*/Attr0x99", 10); PerfW3C.xpathNodes(doc, "/*/*/Attr0x0", 10); PerfW3C.xpathNodes(doc, "/*/*/Attr1x50", 10); PerfW3C.xpathNodes(doc, "/*/*/Attr1x99", 10); PerfW3C.xpathNodes(doc, "/*/Item", 10); numrec = 10; System.out.println("\n10 Elements -----------------------------------"); doc = PerfW3C.createDocument(numrec, 20, 10); PerfW3C.write(doc, "w3c_" + numrec + ".xml"); PerfW3C.parse(numrec, 50); PerfW3C.transform(doc, "item.xslt", 10); PerfW3C.xpath(doc, "/*/*/Attr5", 100); PerfW3C.xpathNodes(doc, "/*/*/Attr1x5", 100); PerfW3C.xpathNodes(doc, "/*/Item", 100); numrec = 1; System.out.println("\n1 Elements ------------------------------------"); doc = PerfW3C.createDocument(numrec, 20, 10); PerfW3C.write(doc, "w3c_" + numrec + ".xml"); PerfW3C.parse(numrec, 100); PerfW3C.transform(doc, "item.xslt", 10); PerfW3C.xpath(doc, "/*/*/Attr1x0", 100); PerfW3C.xpathNodes(doc, "/*/*/Attr1x0", 100); PerfW3C.xpathNodes(doc, "/*/Item", 100); } public static Document createDocument(int iNumRecs, int iNumFlds, int pp) { double start = System.currentTimeMillis(); Document document = null; for (int kk = 0; kk < pp; kk++) { document = new DocumentImpl(); Element root = document.createElement("ItemResultSet"); // Create // Root // Element document.appendChild(root); for (int ii = 0; ii < iNumRecs; ii++) { Element Record = document.createElement("Item"); root.appendChild(Record); for (int jj = 0; jj < iNumFlds; jj++) { /* * AttrImpl a = * (AttrImpl)document.createAttribute("Attr"+jj); * a.setNodeValue("123456789"); Record.setAttributeNode(a); */ Element field = document.createElement("Attr" + jj + "x" + ii); field.appendChild(document.createTextNode("123456789")); Record.appendChild(field); } } } double end = System.currentTimeMillis(); System.err.println("Creation time :" + (end - start) / pp); return document; } public static void write(Document document, String name) { long start = System.currentTimeMillis(); // lets write to a file OutputFormat format = new OutputFormat(document); // Serialize DOM format.setIndent(2); format.setLineSeparator(System.getProperty("line.separator")); format.setLineWidth(80); try { FileWriter writer = new FileWriter(name); BufferedWriter buf = new BufferedWriter(writer); XMLSerializer FileSerial = new XMLSerializer(writer, format); FileSerial.asDOMSerializer(); // As a DOM Serializer FileSerial.serialize(document); } catch (IOException ioe) { ioe.printStackTrace(); } long end = System.currentTimeMillis(); System.err.println("W3C File write time :" + (end - start) + " " + name); } public static Document parse(int iNumRecs, int kk) { File file = new File("dom4j_" + iNumRecs + ".xml"); double start = System.currentTimeMillis(); Document document = null; for (int pp = 0; pp < kk; pp++) { try { SAXReader SAXrd = new SAXReader(); SAXrd.read(file); } catch (Exception e) { e.printStackTrace(); } } double end = System.currentTimeMillis(); // System.err.println("DOM4J createDocument:" + "Num Rec. = " + iNumRecs // + " Num. Fld.=" + iNumFlds); System.err.println("Parsing time for :" + iNumRecs + " " + (end - start) / kk); return document; } public static void transform(Document xmlDoc, String xslFile, int kk) { int ii = 1; try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource( xslFile)); long start = System.currentTimeMillis(); for (ii = 0; ii < kk; ii++) { DOMSource source = new DOMSource(xmlDoc); DOMResult result = new DOMResult(); transformer.transform(source, result); } long end = System.currentTimeMillis(); System.err.println("W3C transform time :" + (end - start) / ii); } catch (Exception e) { e.printStackTrace(); } } public static void xpath(Document document, String xpathExp, int pp) { long start = System.currentTimeMillis(); for (int ii = 0; ii < pp; ii++) { try { Node node = XPathAPI.selectSingleNode(document, xpathExp); if ((node != null) & (ii == 0)) { String val = node.getNodeName(); // System.out.println(val); } } catch (Exception e) { e.printStackTrace(); } } long end = System.currentTimeMillis(); System.err.println("W3C xpath time :" + 1.000 * (end - start) / pp); } public static void xpathNodes(Document document, String xpathExp, int pp) { long start = System.currentTimeMillis(); for (int ii = 0; ii < pp; ii++) { try { NodeList nodeList = XPathAPI.selectNodeList(document, xpathExp); if ((nodeList != null) && (nodeList.getLength() > 0)) { Node node = nodeList.item(0); if ((node != null) & (ii == 0)) { String val = node.getNodeName(); // System.out.println(val); } } } catch (Exception e) { e.printStackTrace(); } } long end = System.currentTimeMillis(); System.err.println("W3C xpathNodes time :" + 1.000 * (end - start) / pp); } } dom4j-1.6.1/xdocs/goals.xml0000644000175000017500000000557310242120011015024 0ustar ebourgebourg Design Goals James Strachan

This document outlines our design goals for dom4j and our philosophy.

We think that an XML framework for Java should be simple, easy to use and intuitive for a Java programmer. We want to take the best features from DOM and SAX and put them together into a new unified API which is optimised the for the Java platform.

We want to fully support DOM and SAX together with existing Java platform standards such as the Java 2 Collections and J2EE.

We want complete XPath support integrated into the API and for it to be very easy to use. XPath is the ideal technology for navigating around XML documents simply and easily without writing lines and lines of code.

We want to be able to support very flexible, performant and memory efficient implementations of XML documents. So we want the API to be based on Java interfaces just like the Java 2 Collections framework.

Just as no single List implementation will suffice (the JDK comes with at least 3) we believe we need a framework allowing plug and play XML document implementations. For some users, using a LinkedList performs better than an ArrayList because their usage characteristics differ. Others like to use a Vector as it is synchronized. We believe an XML model should have the same flexibility.

One of the primary goals of dom4j is to be a flexible XML framework for Java which supports most users needs whether that be fast and efficient parsing with small memory overhead, processing very large documents or using the latest XML features such as XPath, XSLT and XML Query.

We found that we often needed to move from DOM to SAX to handle very large documents or to move from SAX to DOM to handle complex documents. Our aim is for dom4j to be the only framework you really need on the Java platform and for it to be a good citizen supporting and integrating with existing standards fully.

dom4j-1.6.1/xdocs/index.xml0000644000175000017500000002074210242120014015024 0ustar ebourgebourg dom4j: the flexible XML framework for Java James Strachan

dom4j is an easy to use, open source library for working with XML, XPath and XSLT on the Java platform using the Java Collections Framework and with full support for DOM, SAX and JAXP.

  • dom4j 1.6.1 has been relased! This is a bugfix relase. Take a look at the changelog to see what has changed.
  • dom4j 1.6 has been released! Take a look at the changelog to see what has changed.
  • JetBrains was so kind to provide an open-source license of its famous IntelliJ IDEA product.
  • The internal Aelfred2 parser has been removed from the dom4j codebase due to an incompatible license. You can download a version of dom4j without Aelfred2 from the downloads page.
  • A maintenance relase of dom4j is available. Click here to see what has changed in dom4j 1.5.1.
  • dom4j 1.5 is finally released! A list of changes can be found here.
  • dom4j now has an open source license for the use of Clover
  • RefactorIT has added dom4j to it's list of featured open source projects. This means that all the power of RefactorIT is available for the dom4j sources.
  • The new dom4j 1.4 release is finally out featuring numerous bug fixes and patches.
  • Check out these new Performance Benchmarks comparing dom4j and Jaxen against Xerces and Xalan.
  • The new dom4j 1.3 release is out featuring numerous bug fixes and patches.
  • Check out Dennis Sosnoski's new article for IBM comparing various XML object models - its good stuff.
  • The new dom4j 1.2 release is out featuring improved whitespace handling for more efficient parsing, a new Swing TableModel for displaying XML data in Swing and numerous bug fixes and patches.
  • The Velocity projects new DVSL technology uses dom4j.
  • Interesting article outlining the social dominance of DOM and SAX and the importance of XPath.
  • The new dom4j 1.1 release is out featuring support for DTD declarations and numerous bug fixes and patches.
  • Read the latest performance benchmarks on IBM's site comparing dom4j against all the other XML document models.
  • The new dom4j 1.0 release is out featuring better SAX and Jaxen support, some performance tuning and numerous patches.
  • Sun's reference implementation of JAXM (Java API for XML Messaging) is based on dom4j!
  • The new dom4j 0.9 release is out featuring full Jaxen support!
  • Toby's cookbook is now online!
  • Updated the quick start guide
  • designed for the Java platform with full support for the Java Collections Framework (Java 2 Collections)
  • full support for JAXP, TrAX, SAX, DOM, and XSLT
  • fully integrated XPath support for easy navigation of XML documents
  • event based proccessing mode to support for massive documents or XML streams
  • based on Java interfaces for flexible plug and play implementations.
  • support for XML Schema Data Type support using Kohsuke Kawaguchi's excellent Multi Schema Validator library

You can download the current release or a snapshot build via the download page.

For a quick overview of dom4j and how to use it try the reading the quick start guide or browsing the FAQ or the online JavaDoc.

To see how dom4j compares to other XML object models you could try reading our comparison

Contributors are welcome to join this project. Once you've browsed the FAQ you could try sending an email to one of the mailing lists below or check out the project page.

We really like XPath and if you are working with XML we highly recommend you try to experiment with it. If you need help learning XPath try the excellent Zvon tutorial .

Alternatively you could try Elliotte Rusty Harold's great XML in a nutshell .

Finally you could try reading the XPath spec.

For developers there is an email list at dom4j-dev where you can make requests for new features or changes to the API, discuss alternate implementation strategies, submit patches or just talk about any relevant topic of the day.

For dom4j users wanting help using dom4j there is an email list at dom4j-user where you can share ideas and experiences, ask for help, give us feedback or discuss your requirements.

You can browse the archives for here dom4j-dev or here dom4j-dev and here dom4j-user or here dom4j-user

dom4j-1.6.1/xdocs/license.xml0000644000175000017500000000451410242120023015336 0ustar ebourgebourg License James Strachan

Redistribution and use of this software and associated documentation ("Software"), with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain copyright statements and notices. Redistributions must also contain a copy of this document.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  3. The name "DOM4J" must not be used to endorse or promote products derived from this Software without prior written permission of MetaStuff, Ltd. For written permission, please contact dom4j-info@metastuff.com.
  4. Products derived from this Software may not be called "DOM4J" nor may "DOM4J" appear in their names without prior written permission of MetaStuff, Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
  5. Due credit should be given to the DOM4J Project - http://www.dom4j.org

THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.

dom4j-1.6.1/xdocs/changes.xml0000644000175000017500000003743310242120020015327 0ustar ebourgebourg dom4j changes Maarten Coene Updated the XPP2 implementation to version 2.1.10. Fixed a problem with XMLWriter that was causing too many new lines to be written to the resulting XML. Include more information about the cause if an XPathException or InvalidXPathException is thrown. Added a methods to SAXReader allowing to specify the encoding used when reading XML sources. Changed the DocumentHelper.parseText(String) method to make sure that the XML encoding is always set (if known) on the returned Document, even if the used SAXParser doesn't provide a way to retrieve that encoding. Added a setXMLEncoding(String) method to the Document interface. Removed a static OutputFormat field from AbstractBranch. This can cause problems if multiple threads are using the asXML() method simultaniously. Fixed a whitespace problem with the pretty-print OutputFormat. Fixed a bug in the DefaultElement.setContent(List) method that caused incorrectly resetting the parent of the nodes in the list. Removed persistence package and sub-package. Modified SAXEventRecorder to accomodate sax events generated when writing a DOMDocument. Fixed a problem in AbstractDocument.asXML() when an encoding was specified on the Document. The DefaultNamespace.isReadOnly() method now returns false. This fixes issues with cloning this Node. Updated DocumentFactory to create the instance untill the first time it is needed. Fixed a bug in Stylesheet when an xpath expressions was used to select the nodes. Added a SingletonStrategy class for managing singletons. This allows to use different strategies for singletons, like: one instance per VM, one instance per thread, ... This change removed the usage of ThreadLocals. Removed the internal Aelfred2 parser due to incompatible license. Added a SAXEventRecorder that can replay SAX events at a later time. This provides an alternative serialization approach. Fixed problem where the namespace prefix was lost using DOMDocument. Fixed bug in Document.asXML() which ignored the encoding of the document. Updated NamespaceCache to use WeakReferences to allow Namespace objects to be garbage collected. Updated JAXBReader to allow ElementHandlers to be notified when the specified path is encountered, without having to unmarshall XML content. Fixed a bug in XMLWriter where a NullPointerException was thrown if trying to write a CData section containing null content. Modified the internal Aelfred2 parser to no longer support the SAX2 Extensions 1.1 API. As a result, the SAX2 sources are no included with dom4j. Added support for the XPP3 parser. Fixed bug in XMLWriter.characters(...) where the escapeText property of the writer was ignored. Fixed the Stylesheet.removeRule(Rule) method which didn't remove the Rule but added it again. Fixed bug in BackedList causing new elements to always be added at the first position if the size of the list is 1. Upgraded the internal Aelfred2 parser to the latest version. Added initial JAXB support. Updated the STAX classes to provide document encoding. Added getXMLEncoding() method to org.dom4j.Document which returns the encoding of the document. Removed the DocumentHelper.parseText(String xml, String encoding) method that was introduced in dom4j-1.5-beta2. Added the GNU JAXP DOM implementation to the default list of implementations in DOMWriter. Added method to ElementStack and DispatchHandler to check if a handler is registered for a given path. ElementStack is now a public class. SAXContentHandler.endElement(...) can now throw SAXException. Added the namespace-prefix of attributes to the paths returned by Attribute.getPath(Element context) and Attribute.getUniquePath(Element context). Element.declaredNamespaces() now only returns the namespaces that are declared on that element. Element.additionalNamespaces() now only returns namespaces that are declared on that element and is not the same as the namespace of that element. Escape the values of internal DTD entity declarations when serializing to XML. Fixed bug in AbstractElement causing Node.getPath(Element context) to return an absolute path, even if a the current element was the same as the context element. The relative path "." is now returned. Added method to Element to retrieve all Namespaces for a given URI. Fixed bug in DOMReader causing namespace declarations to get lost in some situations. Added a booleanValueOf(Object node) method to XPath. Fixed bug in BeanElement which prevented proper execution of the bean samples. STAXEventWriter now uses XMLEventConsumer instead of XMLEventWriter. Fixed bug in SAXReader that caused problems parsing files in OSX. Fixed bug in XMLWriter that caused whitespace to be added between successive calls of the characters(...) method. This is used particularly frequent in Apache Jelly. Improved performance of NamespaceCache in multithreaded environments. Added flag to OutputFormat that supresses newline after XML declaration. Upgraded dependencies to their latest version on ibiblio. Added method to DocumentHelper that allows user to specify encoding when parsing an xml String. Fixed a ClassCastException bug in BeanElement. Fixed a bug in SAXContentHandler which caused a NullPointerException in some situations. Fixed bug which prevented an element's namespace prefix from being registered for use in xpath expressions. Fixed bug in XMLWriter that caused duplication of the default namespace declaration. Added a bunch of patches to make the dom4j DOM classes more DOM compliant. Fixed bug in DispatchHandler which made the handler not reusable. Fixed bug in SAXContentHandler that caused incorrect CDATA section parsing. Fixed bug in SAXContentHandler that caused incorrect entity handling. Fixed bug in XMLWriter causing padding to be disabled, even if enabled in the specified outputformat. Added initial support for STaX streams. Fixed encoding bug in Document.asXML() and DocumentHelper.parseText(). Fixed bug in SAXReader that caused problems resolving relative URIs when parsing java.io.File Objects. The iterators returned by the Element.elementIterator(...) methods now support remove(). DOMWriter writes now DOM Level 2 attributes and elements. Use latest implementation of the Aelfred parser. Fixed some problems with internal/external DTD declarations. Upgraded to Jaxen 1.1 beta 2. Ignore attribute order when comparing elements in NodeComparator. Fixed bug in XMLWriter where namespace declarations were duplicated. Fixed bug in parsing a ProcessingInstruction. Added support for Stylesheet modes. Don't escape " and ' characters in attribute values if it's not necessary. Fixed some DOMNodeHelper issues. Fixed some datatype issues. Fixed an bug where the EntityResolver was not set on the XMLReader. Fixed multithreaded access on DefaultElement. Fixed problem parsing XML Files. Added xml:space attribute support based on XML Specification 1.0. Maven build of dom4j is now nearly complete. Maven is now used for the website generation. Fixed some bugs in BackedList. dom4j-1.6.1/project.xml0000644000175000017500000002201610242120021014235 0ustar ebourgebourg 3 dom4j dom4j 1.6.1 MetaStuff Ltd. http://sourceforge.net/projects/dom4j http://sourceforge.net/sflogo.php?group_id=16035 /images/logo.gif 2001 org.dom4j Core Developer API org.dom4j,org.dom4j.io Utility classes org.dom4j.util XRule engine for declarative XSLT style processing org.dom4j.rule,org.dom4j.rule.* Alternative dom4j implementations org.dom4j.datatype,org.dom4j.dom,org.dom4j.bean Swing helper classes org.dom4j.swing Implementation classes org.dom4j.tree,org.dom4j.dtd,org.dom4j.xpp,org.dom4j.xpath dom4j : XML framework for Java dom4j dom4j: the flexible XML framework for Java http://dom4j.org http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/dom4j/dom4j/ dom4j/dom4j http://sourceforge.net/tracker/?group_id=16035 dom4j.org /home/groups/d/do/dom4j/htdocs scm:cvs:pserver:anonymous@cvs.sourceforge.net:/cvsroot/dom4j:dom4j scm:cvs:ext:${maven.username}@cvs.sourceforge.net:/cvsroot/dom4j:dom4j http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/dom4j/dom4j/ DOM4J_1_X_BRANCH dom4j user list http://lists.sourceforge.net/lists/listinfo/dom4j-user http://lists.sourceforge.net/lists/listinfo/dom4j-user http://www.mail-archive.com/dom4j-user%40lists.sourceforge.net/ dom4j developer list http://lists.sourceforge.net/lists/listinfo/dom4j-dev http://lists.sourceforge.net/lists/listinfo/dom4j-dev http://www.mail-archive.com/dom4j-dev%40lists.sourceforge.net/ dom4j commits list http://lists.sourceforge.net/lists/listinfo/dom4j-commits http://lists.sourceforge.net/lists/listinfo/dom4j-commits Curt Arnold carnold carnold@users.sourceforge.net David Lucas ddlucas ddlucas@users.sourceforge.net David White drwhite drwhite@users.sourceforge.net Jakob Jenkov jjenkov jjenkov@users.sourceforge.net James Strachan jstrachan jstrachan@apache.org SpiritSoft, Inc. Laramie Crocker laramiec laramiec@users.sourceforge.net Maarten Coene maartenc maartenc@users.sourceforge.net Cronos Michael Skells mskells mskells@users.sourceforge.net Nick Sanderson nicksanderson nicksanderson@users.sourceforge.net Steen Lehmann slehmann slehmann@users.sourceforge.net Tobias Rademacher tradem tradem@users.sourceforge.net Bob McWhirter werken werken@users.sourceforge.net Todd Wolff wolfftw wolfftw@users.sourceforge.net OuYang Chen yeekee yeekee@users.sourceforge.net Yuxin Ruan yruan2 yruan2@users.sourceforge.net jaxme jaxme-api 0.3 http://ws.apache.org/jaxme/index.html jaxen jaxen 1.1-beta-6 http://jaxen.codehaus.org/ msv xsdlib 20030807 https://msv.dev.java.net/ msv relaxngDatatype 20030807 https://msv.dev.java.net/ pull-parser pull-parser 2 http://www.extreme.indiana.edu/xgws/xsoap/xpp/ xpp3 xpp3 1.1.3.3 http://www.extreme.indiana.edu/xgws/xsoap/xpp/ stax stax 1.0 http://jcp.org/aboutJava/communityprocess/final/jsr173/index.html xml-apis xml-apis 2.0.2 http://xml.apache.org/xerces2-j/index.html junitperf junitperf 1.8 http://www.clarkware.com/software/JUnitPerf.html stax stax-ri 1.0 http://dev2dev.bea.com/technologies/stax/index.jsp xerces xercesImpl 2.6.2 http://xml.apache.org/xerces2-j/index.html xalan xalan 2.5.1 http://xml.apache.org/xalan-j/index.html src/java src/test **/*Test.java dom4j-dev@lists.sourceforge.net maven-changelog-plugin maven-changes-plugin maven-checkstyle-plugin maven-clover-plugin maven-developer-activity-plugin maven-faq-plugin maven-file-activity-plugin maven-javadoc-plugin maven-jdepend-plugin maven-junit-report-plugin maven-jxr-plugin maven-license-plugin dom4j-1.6.1/xml/0000755000175000017500000000000012133227266012670 5ustar ebourgebourgdom4j-1.6.1/xml/bean/0000755000175000017500000000000012133227266013575 5ustar ebourgebourgdom4j-1.6.1/xml/bean/gui.xml0000644000175000017500000000026110242120005015060 0ustar ebourgebourg dom4j-1.6.1/xml/namespaces.xml0000644000175000017500000000120510242120013015504 0ustar ebourgebourg <xsl:value-of select="JavaXML:Title" /> dom4j-1.6.1/xml/periodic_table.xml0000644000175000017500000034343210242120020016343 0ustar ebourgebourg Actinium 227 89 3 3470 Ac 10.07 [Rn] 6d1 7s2 1.1 1.88 22.5 0.12 5.17 12 Aluminum 26.98154 13 3 2740 933.5 Al 2.7 [Ne] 3s2 p1 1.18 1.61 1.43 290.8 10 10.7 5.986 0.9 237 Americium 243 95 6, 5, 4, 3 2880 1449 Am 13.7 [Rn] 5f7 7s2 1.3 1.84 20.8 6 10 Antimony 121.757 51 +/-3, 5 1860 903.91 Sb 6.69 [Kr] 4d10 5s2 p3 1.4 2.05 1.59 67.97 18.4 19.83 8.641 0.207 24.3 Argon 39.948 18 87.45 83.95 Ar 1.784 [Ne] 3s2 p6 0.98 0 0.88 6.506 24.2 1.188 15.759 0.52 0.0177 Arsenic 74.9216 33 +/-3, 5 876 1090 As 5.78 [Ar] 3d10 4s2 p3 1.2 2.18 1.39 32.4 13.1 27.7 9.81 0.33 50 Astatine 210 85 +/-1, 3, 5, 7 610 575 At [Xe] 4f14 5d10 6s2 p5 1.47 2.2 1.45 30 12 1.7 Gold 196.9665 79 3, 1 3130 1337.58 Au 19.3 [Xe] 4f14 5d10 6s1 1.34 2.54 1.46 324.43 10.2 12.36 9.225 0.128 317 Boron 10.811 5 3 4275 2365 B 2.34 1s2 2s2 p1 0.82 2.04 0.98 507.8 4.6 22.6 8.298 1.026 27 Barium 137.33 56 2 2078 1002 Ba 3.59 [Xe] 6s2 1.98 0.89 2.22 140.2 39 8.01 5.212 0.204 18.4 Beryllium 9.01218 4 2 3243 1560 Be 1.85 1s2 2s2 0.9 1.57 1.12 297 5 11.71 9.322 1.825 200 Bohrium 262 107 Bh [Rn] 5f14 6d5 7s2 Bismuth 208.9804 83 3, 5 1837 544.59 Bi 9.75 [Xe] 4f14 5d10 6s2 p3 1.46 2.02 1.7 179 21.3 11 7.289 0.122 7.87 Berkelium 247 97 4, 3 Bk [Rn] 5f9 7s2 1.3 6.23 10 Bromine 79.904 35 +/-1, 5 331.85 265.95 Br 3.12 [Ar] 3d10 4s2 p5 1.14 2.96 1.12 14.725 23.5 5.286 11.814 0.226 0.122 Carbon 12.011 6 +/-4, 2 5100 3825 C 2.26 1s2 2s2 p2 0.77 2.55 0.91 715 5.3 11.26 0.709 155 Calcium 40.078 20 2 1757 1112 Ca 1.55 [Ar] 4s2 1.74 1 1.97 154.67 29.9 8.53 6.113 0.647 200 Cadmium 112.41 48 2 1040 594.26 Cd 8.65 [Kr] 4d10 5s2 1.41 1.69 1.71 99.87 13.1 6.07 8.993 0.233 96.8 Cerium 140.12 58 3, 4 3715 1071 Ce 6.77 [Xe] 4f1 5d1 6s2 1.65 1.12 1.81 313.8 21 9.2 5.47 0.19 11.4 Californium 251 98 3 1170 Cf [Rn] 5f10 7s2 1.3 6.3 10 Chlorine 35.4527 17 +/-1, 3, 5, 7 239.18 172.17 Cl 3.214 [Ne] 3s2 p5 0.99 3.16 0.97 10.2 18.7 3.21 12.967 0.48 0.0089 Curium 247 96 3 1620 Cm 13.5 [Rn] 5f7 6d1 7s2 1.3 18.3 6.02 10 Cobalt 58.9332 27 2, 3 3143 1768 Co 8.9 [Ar] 3d7 4s2 1.16 1.88 1.25 373.3 6.7 16.19 7.86 0.421 100 Chromium 51.996 24 6, 3, 2 2945 2130 Cr 7.19 [Ar] 3d5 4s1 1.18 1.66 1.3 339.5 7.23 20 6.766 0.449 93.7 Cesium 132.9054 55 1 944 301.54 Cs 1.87 [Xe] 6s1 2.35 0.79 2.67 67.74 70 2.092 3.894 0.24 35.9 Copper 63.546 29 2, 1 2840 1356.6 Cu 8.96 [Ar] 3d10 4s1 1.17 1.9 1.28 300.5 7.1 13.14 7.726 0.385 401 Dubnium 262 105 Db [Rn] 5f14 6d3 7s2 Dysprosium 162.5 66 3 2840 1685 Dy 8.55 [Xe] 4f10 6s2 1.59 1.22 1.8 230 19 5.93 0.173 10.7 Erbium 167.26 68 3 3140 1802 Er 9.07 [Xe] 4f12 6s2 1.57 1.24 1.78 292.88 18.4 17.15 6.101 0.168 14.3 Einsteinium 252 99 1130 Es [Rn] 5f11 7s2 1.3 6.42 10 Europium 151.965 63 3, 2 1800 1095 Eu 5.24 [Xe] 4f7 6s2 1.85 1.2 1.99 175.73 28.9 9.21 5.67 0.182 13.9 Fluorine 18.9984 9 -1 85 53.55 F 1.696 1s2 2s2 p5 0.72 3.98 0.57 3.2698 17.1 0.26 17.422 0.824 0.0279 Iron 55.847 26 2, 3 3023 1808 Fe 7.874 [Ar] 3d6 4s2 1.17 1.83 1.26 349.5 7.1 13.8 7.87 0.449 80.2 Fermium 257 100 1800 Fm [Rn] 5f12 7s2 1.3 6.5 10 Francium 223 87 1 950 300 Fr [Rn] 7s1 0.7 2.7 64 2.1 0 15 Gallium 69.723 31 3 2478 302.92 Ga 5.91 [Ar] 3d10 4s2 p1 1.26 1.81 1.41 256.06 11.8 5.59 5.999 0.371 40.6 Gadolinium 157.25 64 3 3545 1585 Gd 7.9 [Xe] 4f7 5d1 6s2 1.61 1.2 1.8 311.71 19.9 10.46 6.15 0.236 10.6 Germanium 72.61 32 4 3107 1211.5 Ge 5.32 [Ar] 3d10 4s2 p2 1.22 2.01 1.37 334.3 13.6 31.8 7.899 0.32 59.9 Hydrogen 1.00794 1 1 20.28 13.81 H 0.0899 1s1 0.32 2.1 2.08 0.4581 14.1 0.0585 13.598 14.304 0.1815 Helium 4.0026 2 4.216 0.95 He 0.1785 1s2 0.93 0 0.084 31.8 0.021 24.587 5.193 0.152 Hafnium 178.49 72 4 4875 2504 Hf 13.31 [Xe] 4f14 5d2 6s2 1.44 1.3 1.67 661.07 13.6 21.76 6.65 0.14 23 Mercury 200.59 80 2, 1 629.88 234.31 Hg 13.55 [Xe] 4f14 5d10 6s2 1.49 2 1.6 59.3 14.8 2.292 10.437 0.140 8.34 Holmium 164.9303 67 3 2968 1747 Ho 8.8 [Xe] 4f11 6s2 1.58 1.23 1.79 251.04 18.7 11.06 6.02 0.165 16.2 Hassium 265 108 Hs [Rn] 5f14 6d6 7s2 Iodine 126.9045 53 +/-1, 5, 7 457.5 386.7 I 4.93 [Kr] 4d10 5s2 p5 1.33 2.66 1.32 20.9 25.7 7.76 10.451 0.145 0.449 Indium 114.82 49 3 2350 429.78 In 7.31 [Kr] 4d10 5s2 p1 1.44 1.78 1.66 226.35 15.7 3.26 5.786 0.233 81.6 Iridium 192.22 77 2, 3, 4, 6 4700 2720 Ir 22.6 [Xe] 4f14 5d7 6s2 1.27 2.2 1.36 563.58 8.54 26.36 9.1 0.13 147 Potassium 39.0983 19 1 1033 336.8 K 0.86 [Ar] 4s1 2.03 0.82 2.35 76.9 45.3 2.33 4.341 0.757 102.5 Krypton 83.8 36 120.85 116 Kr 3.75 [Ar] 3d10 4s2 p6 1.89 0 1.03 9.029 32.2 1.638 13.999 0.248 0.00949 Lanthanum 138.9055 57 3 3737 1191 La 6.15 [Xe] 5d1 6s2 1.25 1.1 1.38 399.57 22.5 11.3 5.58 0.19 13.5 Lithium 6.941 3 1 1615 453.7 Li 0.53 1s2 2s1 1.23 0.98 1.55 147.1 13.1 3 5.392 3.582 84.7 Lawrencium 262 103 1900 Lr [Rn] 5f14 6d1 7s2 10 Lutetium 174.967 71 3 3668 1936 Lu 9.84 [Xe] 4f14 5d1 6s2 1.56 1.27 1.75 355 17.8 18.6 5.43 0.15 16.4 Mendelevium 258 101 1100 Md [Rn] 5f13 7s2 1.3 6.58 10 Magnesium 24.305 12 2 1380 922 Mg 1.74 [Ne] 3s2 1.36 1.31 1.6 127.6 14 8.95 7.646 1.02 156 Manganese 54.938 25 7, 6, 4, 2, 3 2335 1518 Mn 7.44 [Ar] 3d5 4s2 1.17 1.55 1.35 219.74 7.39 14.64 7.435 0.48 7.82 Molybdenum 95.94 42 6, 5, 4, 3, 2 4912 2896 Mo 10.22 [Kr] 4d5 5s1 1.3 2.16 1.39 590.4 9.4 36 7.099 0.25 138 Meitnerium 266 109 Mt [Rn] 5f14 6d7 7s2 Nitrogen 14.0067 7 +/-3, 5, 4, 2 77.344 63.15 N 1.251 1s2 2s2 p3 0.75 3.04 0.92 2.7928 17.3 0.36 14.534 1.042 0.02598 Sodium 22.98977 11 1 1156 371 Na 0.97 [Ne] 3s1 1.54 0.93 1.9 98.01 23.7 2.601 5.139 1.23 141 Niobium 92.9064 41 5, 3 5015 2742 Nb 8.57 [Kr] 4d4 5s1 1.34 1.6 1.46 690.1 10.8 26.9 6.88 0.265 53.7 Neodymium 144.24 60 3 3347 1294 Nd 7.01 [Xe] 4f4 6s2 1.64 1.14 1.82 283.68 20.6 10.88 5.49 0.19 16.5 Neon 20.1797 10 27.1 24.55 Ne 0.900 1s2 2s2 p6 0.71 0 0.51 1.77 16.9 0.34 21.564 1.03 0.0493 Nickel 58.6934 28 2, 3 3005 1726 Ni 8.9 [Ar] 3d8 4s2 1.15 1.91 1.24 377.5 6.6 17.2 7.635 0.444 90.7 Nobelium 259 102 1100 No [Rn] 5f14 7s2 1.3 6.65 10 Neptunium 237.0482 93 6, 5, 4, 3 4175 912 Np 20.2 [Rn] 5f4 6d1 7s2 1.36 1.3 21.1 6.19 6.3 Oxygen 15.9994 8 -2 90.188 54.8 O 1.429 1s2 2s2 p4 0.73 3.44 0.65 3.4109 14 0.222 13.618 0.92 0.2674 Osmium 190.2 76 2, 3, 4, 6, 8 5300 3300 Os 22.6 [Xe] 4f14 5d6 6s2 1.26 2.2 1.35 627.6 8.43 29.29 8.7 0.13 87.6 Phosphorus 30.97376 15 +/-3, 5, 4 553 317.3 P 1.82 [Ne] 3s2 p3 1.06 2.19 1.28 12.4 17 0.63 10.486 0.769 0.235 Protactinium 231.0359 91 5, 4 4300 1845 Pa 15.4 [Rn] 5f2 6d1 7s2 1.5 1.61 15 5.88 47 Lead 207.2 82 4, 2 2023 600.65 Pb 11.35 [Xe] 4f14 5d10 6s2 p2 1.47 2.33 1.75 177.9 18.3 4.77 7.416 0.129 35.3 Palladium 106.42 46 2, 4 3240 1825 Pd 12 [Kr] 4d10 1.28 2.2 1.37 393.3 8.9 16.74 8.34 0.244 71.8 Promethium 145 61 3 3273 1315 Pm 7.22 [Xe] 4f5 6s2 1.63 1.13 22.4 5.55 17.9 Polonium 209 84 4, 2 527 Po 9.3 [Xe] 4f14 5d10 6s2 p4 1.53 2 1.67 120 22.7 13 8.42 20 Praseodymium 140.9077 59 3, 4 3785 1204 Pr 6.77 [Xe] 4f3 6s2 1.65 1.13 1.82 332.63 20.8 10.04 5.42 0.193 12.5 Platinum 195.08 78 2, 4 4100 2042.1 Pt 21.45 [Xe] 4f14 5d9 6s1 1.3 2.28 1.39 510.45 9.1 19.66 9 0.13 71.6 Plutonium 244 94 6, 5, 4, 3 3505 913 Pu 19.84 [Rn] 5f6 7s2 1.28 1.51 12.32 6.06 0.13 6.74 Radium 226.0254 88 2 1413 973 Ra 5 [Rn] 7s2 0.89 2.33 136.82 45.2 8.37 5.279 0.094 18.6 Rubidium 85.4678 37 1 961 312.63 Rb 1.532 [Kr] 5s1 2.16 0.82 2.48 69.2 55.9 2.34 4.177 0.363 58.2 Rhenium 186.207 75 7, 6, 4, 2, -1 5870 3455 Re 21 [Xe] 4f14 5d5 6s2 1.28 1.9 1.37 707.1 8.85 33.05 7.88 0.137 47.9 Rutherfordium 261 104 Rf [Rn] 5f14 6d2 7s2 Rhodium 102.9055 45 2, 3, 4 3970 2236 Rh 12.41 [Kr] 4d8 5s1 1.25 2.28 1.34 495.39 8.3 21.76 7.46 0.242 150 Radon 222 86 211.4 202 Rn 9.73 [Xe] 4f14 5d10 6s2 p6 0 1.34 16.4 50.5 2.9 10.748 0.094 0.00364 Ruthenium 101.07 44 2, 3, 4, 6, 8 4425 2610 Ru 12.37 [Kr] 4d7 5s1 1.25 2.2 1.34 567.77 8.3 25.52 7.37 0.238 117 Sulfur 32.066 16 +/-2, 4, 6 717.82 392.2 S 2.07 [Ne] 3s2 p4 1.02 2.58 1.27 10 15.5 1.73 10.36 0.71 0.269 Silver 107.868 47 1 2436 1235.08 Ag 10.5 [Kr] 4d10 5s1 1.34 1.93 1.44 250.63 10.3 11.3 7.576 0.232 429 Scandium 44.9559 21 3 3109 1814 Sc 2.99 [Ar] 3d1 4s2 1.44 1.36 1.62 304.8 15 16.11 6.54 0.568 15.8 Selenium 78.96 34 -2, 4, 6 958 494 Se 4.79 [Ar] 3d10 4s2 p4 1.16 2.55 1.4 26.32 16.5 5.54 9.752 0.32 2.04 Seaborgium 263 106 Sg [Rn] 5f14 6d4 7s2 Silicon 28.0855 14 4 2630 1683 Si 2.33 [Ne] 3s2 p2 1.11 1.9 1.32 359 12.1 50.2 8.151 0.70 148 Samarium 150.36 62 3, 2 2067 1347 Sm 7.52 [Xe] 4f6 6s2 1.62 1.17 1.81 191.63 19.9 11.09 5.63 0.197 13.3 Strontium 87.62 38 2 1655 1042 Sr 2.54 [Kr] 5s2 1.91 0.95 2.15 136.9 33.7 8.2 5.695 0.3 35.3 Tantalum 180.9479 73 5 5730 3293 Ta 16.65 [Xe] 4f14 5d3 6s2 1.34 1.5 1.49 737 10.9 36 7.89 0.14 57.5 Terbium 158.9253 65 3, 4 3500 1629 Tb 8.23 [Xe] 4f9 6s2 1.59 1.1 1.8 19.2 15.48 5.86 0.18 11.1 Technetium 98 43 7 4538 2477 Tc 11.5 [Kr] 4d5 5s2 1.27 1.9 1.36 502 8.5 23 7.28 0.24 50.6 Tellurium 127.6 52 -2, 4, 6 1261 722.72 Te 6.24 [Kr] 4d10 5s2 p4 1.36 2.1 1.42 50.63 20.5 17.49 9.009 0.202 2.35 Thorium 232.0381 90 4 5060 2028 Th 11.72 [Rn] 6d2 7s2 1.65 1.3 1.8 543.92 19.9 15.65 6.08 0.113 54 Tin 118.71 50 4, 2 2876 505.12 Sn 7.31 [Kr] 4d10 5s2 p2 1.41 1.96 1.62 290.37 16.3 7.2 7.344 0.228 66.6 Titanium 47.88 22 4, 3 3560 1945 Ti 4.54 [Ar] 3d2 4s2 1.32 1.54 1.45 425.2 10.6 18.6 6.82 0.523 21.9 Thallium 204.383 81 3, 1 1746 577 Tl 11.85 [Xe] 4f14 5d10 6s2 p1 1.48 2.04 1.71 162.09 17.2 4.27 6.108 0.129 46.1 Thulium 168.9342 69 3, 2 2223 1818 Tm 9.32 [Xe] 4f13 6s2 1.56 1.25 1.77 191 18.1 16.8 6.184 0.16 16.8 Uranium 238.029 92 6, 5, 4, 3 4407 1408 U 18.95 [Rn] 5f3 6d1 7s2 1.42 1.38 1.38 422.58 12.5 15.48 6.05 0.12 27.6 ununbium 277 112 Uub [Rn] 5f14 6d10 7s2 ununnilium 269 110 Uun [Rn] 5f14 6d8 7s2 unununium 272 111 Uuu [Rn] 5f14 6d9 7s2 Vanadium 50.9415 23 5, 4, 3, 2 3650 2163 V 6.11 [Ar] 3d3 4s2 1.22 1.63 1.34 446.7 8.35 20.8 6.74 0.489 30.7 Tungsten 183.85 74 6, 5, 4, 3, 2 5825 3695 W 19.3 [Xe] 4f14 5d4 6s2 1.3 2.36 1.41 422.58 9.53 35.4 7.98 0.13 174 Xenon 131.29 54 165.1 161.39 Xe 5.9 [Kr] 4d10 5s2 p6 1.31 2.6 1.24 12.64 42.9 2.3 12.13 0.158 0.00569 Yttrium 88.9059 39 3 3611 1795 Y 4.47 [Kr] 4d1 5s2 1.62 1.22 1.78 363.3 19.8 17.5 6.38 0.3 17.2 Ytterbium 173.04 70 3, 2 1469 1092 Yb 6.97 [Xe] 4f14 6s2 1.7 1.1 1.94 128 24.8 7.7 6.254 0.155 34.9 Zinc 65.39 30 2 1180 692.73 Zn 7.13 [Ar] 3d10 4s2 1.25 1.65 1.38 115.3 9.2 7.38 9.394 0.388 116 Zirconium 91.224 40 4 4682 2128 Zr 6.51 [Kr] 4d2 5s2 1.45 1.33 1.6 590.5 14.1 21 6.84 0.278 22.7 dom4j-1.6.1/xml/testPI.xml0000644000175000017500000000032710242120011014577 0ustar ebourgebourg Hello he said. The DOM4J home page. More text! dom4j-1.6.1/xml/nitf/0000755000175000017500000000000012133227266013630 5ustar ebourgebourgdom4j-1.6.1/xml/nitf/valid.xml0000644000175000017500000000611710242120006015435 0ustar ebourgebourg Use of Napster Quadruples By PETER SVENSSON AP Business Writer The Associated Press NEW YORK

Despite the uncertain legality of the Napster online music-sharing service, the number of people using it more than quadrupled in just five months, Media Metrix said Monday.

That made Napster the fastest-growing software application ever recorded by the Internet research company.

From 1.1 million home users in the United States in February, the first month Media Metrix tracked the application, Napster use rocketed to 4.9 million users in July.

That represents 6 percent of U.S. home PC users who have modems, said Media Metrix, which pays people to install monitoring software on their computers.

It estimates total usage from a panel of about 50,000 people in the United States.

Napster was also used at work by 887,000 people in July, Media Metrix said.

Napster Inc. has been sued by the recording industry for allegedly enabling copyright infringement. The federal government weighed in on the case Friday, saying the service is not protected under a key copyright law, as the San Mateo, Calif., company claims.

Bruce Ryon, head of Media Metrix's New Media Group, said Napster was used by "the full spectrum of PC users, not just the youth with time on their hands and a passion for music."

The Napster program allows users to copy digital music files from the hard drives of other users over the Internet.

Napster Inc. said last week that 28 million people had downloaded its program. It does not reveal its own figures for how many people actually use the software.

Because the program connects to the company's computers over the Internet every time it is run, Napster Inc. can track usage exactly.

__

On the Net:

http://www.napster.com

http://www.mediametrix.com

dom4j-1.6.1/xml/nitf/sample.xml0000644000175000017500000000605410242120006015617 0ustar ebourgebourg Use of Napster Quadruples By PETER SVENSSON AP Business Writer The Associated Press NEW YORK

Despite the uncertain legality of the Napster online music-sharing service, the number of people using it more than quadrupled in just five months, Media Metrix said Monday.

That made Napster the fastest-growing software application ever recorded by the Internet research company.

From 1.1 million home users in the United States in February, the first month Media Metrix tracked the application, Napster use rocketed to 4.9 million users in July.

That represents 6 percent of U.S. home PC users who have modems, said Media Metrix, which pays people to install monitoring software on their computers.

It estimates total usage from a panel of about 50,000 people in the United States.

Napster was also used at work by 887,000 people in July, Media Metrix said.

Napster Inc. has been sued by the recording industry for allegedly enabling copyright infringement. The federal government weighed in on the case Friday, saying the service is not protected under a key copyright law, as the San Mateo, Calif., company claims.

Bruce Ryon, head of Media Metrix's New Media Group, said Napster was used by "the full spectrum of PC users, not just the youth with time on their hands and a passion for music."

The Napster program allows users to copy digital music files from the hard drives of other users over the Internet.

Napster Inc. said last week that 28 million people had downloaded its program. It does not reveal its own figures for how many people actually use the software.

Because the program connects to the company's computers over the Internet every time it is run, Napster Inc. can track usage exactly.

__

On the Net:

http://www.napster.com

http://www.mediametrix.com

dom4j-1.6.1/xml/nitf/ashtml.xsl0000644000175000017500000000400010242120011015615 0ustar ebourgebourg
Related Stock: http://localhost/stock?ts=

dom4j-1.6.1/xml/nitf/nitf.dtd0000644000175000017500000024253210242120002015250 0ustar ebourgebourg dom4j-1.6.1/xml/nitf/invalid.xml0000644000175000017500000000472010242120015015762 0ustar ebourgebourg Use of Napster Quadruples By PETER SVENSSON AP Business Writer The Associated Press NEW YORK

Despite the uncertain legality of the Napster online music-sharing service, the number of people using it more than quadrupled in just five months, Media Metrix said Monday.

That made Napster the fastest-growing software application ever recorded by the Internet research company.

From 1.1 million home users in the United States in February, the first month Media Metrix tracked the application, Napster use rocketed to 4.9 million users in July.

That represents 6 percent of U.S. home PC users who have modems, said Media Metrix, which pays people to install monitoring software on their computers.

It estimates total usage from a panel of about 50,000 people in the United States.

Napster was also used at work by 887,000 people in July, Media Metrix said.

Napster Inc. has been sued by the recording industry for allegedly enabling copyright infringement. The federal government weighed in on the case Friday, saying the service is not protected under a key copyright law, as the San Mateo, Calif., company claims.

Bruce Ryon, head of Media Metrix's New Media Group, said Napster was used by "the full spectrum of PC users, not just the youth with time on their hands and a passion for music."

The Napster program allows users to copy digital music files from the hard drives of other users over the Internet.

Napster Inc. said last week that 28 million people had downloaded its program. It does not reveal its own figures for how many people actually use the software.

Because the program connects to the company's computers over the Internet every time it is run, Napster Inc. can track usage exactly.

__

On the Net:

http://www.napster.com

http://www.mediametrix.com

dom4j-1.6.1/xml/swing/0000755000175000017500000000000012133227266014017 5ustar ebourgebourgdom4j-1.6.1/xml/swing/tableForWeb.xml0000644000175000017500000000047410242120014016720 0ustar ebourgebourg NameClassMapping
dom4j-1.6.1/xml/swing/tableForAtoms.xml0000644000175000017500000000075310242120010017262 0ustar ebourgebourg NameSymbolWeightNumberOxidation States
dom4j-1.6.1/xml/schema/0000755000175000017500000000000012133227266014130 5ustar ebourgebourgdom4j-1.6.1/xml/schema/personal-schema.xml0000644000175000017500000000234010242120024017711 0ustar ebourgebourg Boss Big chief@foo.com Worker One one@foo.com Worker Two two@foo.com Worker Three three@foo.com Worker Four four@foo.com Worker Five five@foo.com dom4j-1.6.1/xml/schema/invalid-schema.xml0000644000175000017500000000241510242117776017543 0ustar ebourgebourg Boss chief@foo.com Worker One one@foo.com Two two@foo.com three@foo.com Worker Four four@foo.com Worker Five five@foo.com dom4j-1.6.1/xml/schema/personal.xml0000644000175000017500000000217010242117776016500 0ustar ebourgebourg Boss Big chief@foo.com Worker One one@foo.com Worker Two two@foo.com Worker Three three@foo.com Worker Four four@foo.com Worker Five five@foo.com dom4j-1.6.1/xml/schema/personal.xsd0000644000175000017500000000437110242120021016454 0ustar ebourgebourg dom4j-1.6.1/xml/schema/personal-dtd.xml0000644000175000017500000000224210242120007017226 0ustar ebourgebourg Boss Big chief@foo.com Worker One one@foo.com Worker Two two@foo.com Worker Three three@foo.com Worker Four four@foo.com Worker Five five@foo.com dom4j-1.6.1/xml/schema/invalid.xml0000644000175000017500000000224510242120000016254 0ustar ebourgebourg Boss chief@foo.com Worker One one@foo.com Two two@foo.com three@foo.com Worker Four four@foo.com Worker Five five@foo.com dom4j-1.6.1/xml/schema/personal.dtd0000644000175000017500000000123510242120021016425 0ustar ebourgebourg dom4j-1.6.1/xml/inline.xml0000644000175000017500000000054410242120016014653 0ustar ebourgebourg ]> God fortsättning på det nya millenniet! dom4j-1.6.1/xml/rabo1ae.xml0000644000175000017500000002510410242120023014704 0ustar ebourgebourg RABO.UTR.OMR.SA1 1 RP00100112 RP00100112 RABO.LDN.LPM.SA1 1 100678954 100678954 RABO.LDN.AEG.SA2 1 AE4269 AE4269 Trade Capture RepoTrade 07 Aug 2001 14:35:03 GMT 2001 Database Timeout 2001 Database Timeout 2 0000 08 Aug 2001 08 Aug 2001 08 Aug 2001 08 Aug 2001 08 Aug 2001 08 Aug 2001 08 Aug 2001 08 Aug 2001 08 Aug 2001 08 Aug 2001 08 Aug 2001 08 Aug 2001 08 Aug 2001 08 Aug 2001 Test GBP P 12345678.90 08 Aug 2001 08 Aug 2001 08 Aug 2001 123450100 GT715110 OA12345678 2001-03-03 ' ' USD 123456.00 ' ' N CRRNT ACTUALS 1.00000000 1.00000000 0.00 ' ' ' ' ' ' 00000.00 ' ' 2001-01-01 10 NLRAT BONDCV NLRAT dom4j-1.6.1/xml/jaxb/0000755000175000017500000000000012133227266013614 5ustar ebourgebourgdom4j-1.6.1/xml/jaxb/primer.xml0000644000175000017500000000201210242120023015605 0ustar ebourgebourg Alice Smith 123 Maple Street Cambridge MA 12345 Robert Smith 8 Oak Avenue Cambridge MA 12345 Lee Grant 123 Maple Street Cambridge MA 12345 Stonewall Jackson 8 Oak Avenue Lexington MA 12345 dom4j-1.6.1/xml/jaxb/primer.xsd0000644000175000017500000000505210242120017015615 0ustar ebourgebourg Purchase order schema for Example.com. Copyright 2000 Example.com. All rights reserved. dom4j-1.6.1/xml/#.xml0000644000175000017500000000001010242120003013477 0ustar ebourgebourgdom4j-1.6.1/xml/axis.xml0000644000175000017500000000036610242120005014341 0ustar ebourgebourg dom4j-1.6.1/xml/relaxng/0000755000175000017500000000000012133227266014330 5ustar ebourgebourgdom4j-1.6.1/xml/relaxng/address.xml0000644000175000017500000000034110242120011016450 0ustar ebourgebourg John Smith js@example.com Fred Bloggs fb@example.net dom4j-1.6.1/xml/relaxng/address.rng0000644000175000017500000000045710242120022016450 0ustar ebourgebourg dom4j-1.6.1/xml/relaxng/address.dtd0000644000175000017500000000016710242120005016434 0ustar ebourgebourg dom4j-1.6.1/xml/relaxng/bad_address.xml0000644000175000017500000000036310242120000017260 0ustar ebourgebourg js@example.com Fred Bloggs Fred Bloggs dom4j-1.6.1/xml/test/0000755000175000017500000000000012133227266013647 5ustar ebourgebourgdom4j-1.6.1/xml/test/junk.xml0000644000175000017500000000005510242120014015316 0ustar ebourgebourghi therehello worlddom4j-1.6.1/xml/test/namespaces.xml0000644000175000017500000000046510242120014016473 0ustar ebourgebourg Hello Hey Hey2 Hey3 dom4j-1.6.1/xml/test/sample.xml0000644000175000017500000000037010242120014015630 0ustar ebourgebourg red blue green dom4j-1.6.1/xml/test/test_schema.xml0000644000175000017500000000061710242120022016651 0ustar ebourgebourg dom4j-1.6.1/xml/test/test_text.xml0000644000175000017500000000014110242117777016414 0ustar ebourgebourg This should work dom4j-1.6.1/xml/test/FranzBeilMain.xml0000644000175000017500000000026710242120006017036 0ustar ebourgebourg
dom4j-1.6.1/xml/test/dosLineFeeds.xml0000644000175000017500000000031310242120007016712 0ustar ebourgebourg
Mary had a little lamb.

Test URL Hello, this is a test. dom4j-1.6.1/xml/test/nestedNamespaces.xml0000644000175000017500000000035410242120017017636 0ustar ebourgebourg works dom4j-1.6.1/xml/test/schema/0000755000175000017500000000000012133227266015107 5ustar ebourgebourgdom4j-1.6.1/xml/test/schema/personal-schema.xml0000644000175000017500000000360310242120021020670 0ustar ebourgebourg Boss Big chief@foo.com Some text... 100 Worker One one@foo.com Some text... 200 Worker Two two@foo.com Some text... 300 Worker Three three@foo.com Some text... 400 Worker Four four@foo.com Some text... 500 Worker Five five@foo.com Some text... 600 dom4j-1.6.1/xml/test/schema/test.xml0000644000175000017500000000251210242120015016567 0ustar ebourgebourg P1Y2M3DT10H30M 1999-05-03 00:00:00 1999-05-31T13:20:00-05:00 1999-05 1999 --12-25 ---15 --10-- true cafebabe cafebabe 123.45 123.45 123 123 -123 -123 12345678901234 12345 1234 123 123 123 123 123 123 123 dom4j-1.6.1/xml/test/schema/personal.xml0000644000175000017500000000343110242117776017460 0ustar ebourgebourg Boss Big chief@foo.com Some text... 100 Worker One one@foo.com Some text... 200 Worker Two two@foo.com Some text... 300 Worker Three three@foo.com Some text... 400 Worker Four four@foo.com Some text... 500 Worker Five five@foo.com Some text... 600 dom4j-1.6.1/xml/test/schema/personal.xsd0000644000175000017500000000436710242120021017440 0ustar ebourgebourg dom4j-1.6.1/xml/test/schema/test.xsd0000644000175000017500000000344510242120011016567 0ustar ebourgebourg dom4j-1.6.1/xml/test/schema/personal_dtd.xml0000644000175000017500000000247610242120024020277 0ustar ebourgebourg Boss Big chief@foo.com 100 Worker One one@foo.com 200 Worker Two two@foo.com 300 Worker Three three@foo.com 400 Worker Four four@foo.com 500 Worker Five five@foo.com 600 dom4j-1.6.1/xml/test/schema/personal-prefix.xsd0000644000175000017500000000414110242120022020722 0ustar ebourgebourg dom4j-1.6.1/xml/test/schema/personal.dtd0000644000175000017500000000123510242120021017404 0ustar ebourgebourg dom4j-1.6.1/xml/test/journal.xsl0000644000175000017500000000112010242120011016016 0ustar ebourgebourg Journal

dom4j-1.6.1/xml/test/test.xml0000644000175000017500000000025410242120023015327 0ustar ebourgebourg ]> &LmInclude; dom4j-1.6.1/xml/test/webwhitespace.xml0000644000175000017500000000171010242120020017175 0ustar ebourgebourg snoop SnoopServlet file ViewFile initial 1000 The initial value for the counter mv *.wm manager director president dom4j-1.6.1/xml/test/DavidHooker.xml0000644000175000017500000000117410242120012016547 0ustar ebourgebourg dom4j-1.6.1/xml/test/FranzBeilImport1.xml0000644000175000017500000000034010242120022017473 0ustar ebourgebourg first text second text third text dom4j-1.6.1/xml/test/soap3.xml0000644000175000017500000000062710242120010015375 0ustar ebourgebourg
5
DEF
dom4j-1.6.1/xml/test/FranzBeilImport3.xml0000644000175000017500000000034410242120017017505 0ustar ebourgebourg seventh text eighth text ninth text dom4j-1.6.1/xml/test/product.xml0000644000175000017500000000073010242120015016030 0ustar ebourgebourg EQUITY_ CF1 11.11 CF2 22.22 CF3 33.33 dom4j-1.6.1/xml/test/toby.xml0000644000175000017500000012055410242120005015333 0ustar ebourgebourg REGADT MCM IFENG 199601061000 ADT A05 A05 199601061000 199601101400 01 199601061000 191919 GENHOSP MARYLOU
123 INDUSTRY WAY ISHPEMING MI 49849 ""
MARYLOU
MASSIE ELLEN MARYLOU
MASSIE ELLEN
O 0148 ADDISON,JAMES 199601101400 199601101400 ST
19 BIOPSY 00 MASSIE JAMES "" "" "" "" BLUE CROSS 171 ZOBERLEIN ISHPEMING M149849 "" 0 BC1 BLUE CROSS 171 ZOBERLEIN ISHPEMING M149849 ""
dom4j-1.6.1/xml/test/mergetext.xml0000644000175000017500000000037010242120016016355 0ustar ebourgebourg test < one >]]> test two test three test four test five test six test seven dom4j-1.6.1/xml/test/defaultNamespace.xml0000644000175000017500000000013210242120012017602 0ustar ebourgebourg Hello dom4j-1.6.1/xml/test/encode.xml0000644000175000017500000000026510242120013015606 0ustar ebourgebourg This & that This < that This > that dom4j-1.6.1/xml/test/badcomment.xml0000644000175000017500000000014310242120023016456 0ustar ebourgebourg dom4j-1.6.1/xml/test/jimBrain.xml0000644000175000017500000000135110242120015016103 0ustar ebourgebourg false simple Server Stuff here http://www.digitalsymbiosis.net jdcasey nothing http://www.digitalsymbiosis.net jdcasey nothing This is a test. This should be the server/db property... Sure. 5 1 dom4j-1.6.1/xml/test/cdata.xml0000644000175000017500000000016410242120022015423 0ustar ebourgebourg dom4j-1.6.1/xml/test/elementByID.xml0000644000175000017500000000030710242120017016513 0ustar ebourgebourg Squeak!

Squeak!

squeak squeak squeak dom4j-1.6.1/xml/test/LuisSchema.xsd0000644000175000017500000003747710242120016016426 0ustar ebourgebourg dom4j-1.6.1/xml/test/journal.xml0000644000175000017500000000055110242120016016024 0ustar ebourgebourg May 19, 2002 Sample text. We should support some markup here. May 19, 2002 10:27 Second batch. dom4j-1.6.1/xml/test/soap2.xml0000644000175000017500000000225210242120011015371 0ustar ebourgebourg en_fr SOAP is quite easy with JSP. dom4j-1.6.1/xml/test/FranzBeilImport2.xml0000644000175000017500000000034010242120021017473 0ustar ebourgebourg fourth text fifth text sixth text dom4j-1.6.1/xml/test/longCDATA.xml0000644000175000017500000000403010242120016016042 0ustar ebourgebourg 3 Message Matt 4;5 If a shareholder ceases to work for Codex Computing for any reason.doc Moramdum of Understanding 814BFD3FDC5843F0B6DC688C99E1C31E dom4j-1.6.1/xml/test/littledoc.xml0000644000175000017500000000040210242117776016353 0ustar ebourgebourg Bwahahahah! Twas a dark, rainy night... dfjsdfjsdf fdsfsdfhdsff gyuf uysgf ds dom4j-1.6.1/xml/test/fields.xml0000644000175000017500000000037510242117776015647 0ustar ebourgebourg dom4j-1.6.1/xml/test/defaultNamespaceIssue.xsd0000644000175000017500000007147610242120011020633 0ustar ebourgebourg A Component within the CC/PP Schema is a class of related properties that describe the capabilities and preferences information. Any description or notes about this device Specifies if the device is a generic device supporting an acceptable content type. The HardwarePlatform component contains properties of the device's Hardware, such as display size, supported character sets, etc. The SoftwarePlatform component contains properties of the device's application environment, operating system, and installed software. The WapCharacteristics component contains properties of the WAP environment supported by the device. The BrowserUA component contains attributes related to the browser user agent running on the device. The NetworkCharacteristics component contains properties describing the network environment including the supported bearers. The PushCharacteristics component contains properties of the device's push capabilities, such as supported content mime types. The number of bits of color or grayscale information per pixel, related to the number of colors or shades of gray the device can display. The number of bits of color or grayscale information per pixel, related to the number of colors or shades of gray the device can display. Name and model number of the device CPU. Indicates whether the device supports the display of images. If the value is "Yes", the property CcppAccept may list the types of images supported. List of character sets supported by the device for text entry. Property's value is a list of character sets, where each item in the list is a character set name, as registered with IANA. Type of keyboard supported by the device, as an indicator of ease of text entry. Model number assigned to the terminal device by the vendor or manufacturer. Number of soft keys available on the device. List of character sets supported by the device for output to the display. Property value is a list of character sets, where each item in the list is a character set name, as registered with IANA. Ratio of pixel width to pixel height. Type of resolution of the pointing accessory supported by the device. The size of the device's screen in units of pixels, composed of the screen width and the screen height. Size of the device's screen in units of characters, composed of the screen width and screen height. The device's standard font should be used to determine this property's value. (Number of characters per row)x(Number of rows). In calculating this attribute use the largest character in the device's default font. Indicates whether the device's standard font is proportional. Indicates whether the device supports sound output through an external speaker, headphone jack, or other sound output mechanism. Indicates whether the device supports alpha-numeric text entry. "Yes" means the device supports entry of both letters and digits. "No" means the device supports only entry of digits. Name of the vendor manufacturing the terminal device. Indicates whether the device supports any form of voice input, including speech recognition. This includes voice- enabled browsers. Indicates the user's preference on whether to accept downloadable software. List of audio input encoders supported by the device. List of content types the device supports. Property value is a list of MIME types, where each item in the list is a content type descriptor as specified by RFC 2045. List of character sets the device supports. Property value is a list of character sets, where each item in the list is a character set name registered with IANA. List of transfer encodings the device supports. Property value is a list of transfer encodings, where each item in the list is a transfer encoding name as specified by RFC 2045 and registered with IANA. List of preferred document languages. If a resource is available in more than one natural language, the server can use this property to determine which version of the resource to send to the device. The first item in the list should be considered the user's first choice, the second the second choice, and so on. Property value is a list of natural languages, where each item in the list is the name of a language as defined by RFC 3066[RFC3066]. List of preferred document languages. If a resource is available in more than one natural language, the server can use this property to determine which version of the resource to send to the device. The first item in the list should be considered the user's first choice, the second the second choice, and so on. Property value is a list of natural languages, where each item in the list is the name of a language as defined by RFC 3066[RFC3066]. Indicates whether the device supports a Java virtual machine. The list of JAVA platforms and profiles installed in the device. Each item in the list is a name token describing compatibility with the name and version of the java platform specification or the name and version of the profile specification name (if profile is included in the device). List of the Java virtual machines installed on the device. Each item in the list is a name token describing the vendor and version of the VM. List of MExE classmarks supported by the device. Value "1" means the MExE device supports WAP, value "2" means that MExE device supports Personal Java and value "3" means that MExE device supports MIDP applications. Class mark specialization. Refers to the first two digits of the version of the MExE Stage 2 spec. Indicates whether the device's supports MExE security domains. "Yes" means that security domains are supported in accordance with MExE specifications identified by the MexeSpec attribute. "No" means that security domains are not supported and the device has only untrusted domain (area). Name of the device's operating system. Vendor of the device's operating system. Vendor of the device's operating system. User agent associated with the current request. Value should match the name of one of the components in the profile. Version of the device-specific software (firmware) to which the device's low-level software conforms. List of video input encoders supported by the device. Pictogram classes supported by the device as defined in "WAP Pictogram specification". Classification of the device based on capabilities as identified in the WAP 1.1 specifications. Current values are "A", "B" and "C". Version of WAP supported. Maximum size of a WML deck that can be downloaded to the device. This may be an estimate of the maximum size if the true maximum size is not known. Value is number of bytes. List of mandatory and optional libraries supported in the device's WMLScript VM. List of WMLScript versions supported by the device. Property value is a list of version numbers, where each item in the list is a version string conforming to Version. List of WML language versions supported by the device. Property value is a list of version numbers, where each item in the list is a version string conforming to Version. List of WTAI network common and network specific libraries supported by the device. Property value is a list of WTA library names, where each item in the list list is a library name as specified by "WAP WTAI" and its addendums. Any future addendums to "WAP WTAI" should be reflected in the values of this property. Version of WTA user agent. Name of the browser user agent associated with the current request. Version of the browser. List of executable content types which the browser supports and which it is willing to accept from the network. The property value is a list of MIME types, where each item in the list is a content type descriptor as specified by RFC 2045. Indicates whether the browser is capable of displaying Version of HyperText Markup Language (HTML) supported by the browser. Indicates whether the browser supports Java applets. Indicates whether the browser supports JavaScript. Version of the JavaScript language supported by the browser. Indicates the user's preference for receiving HTML content that contains frames. Indicates whether the browser is capable of displaying tables. Version of XHTML supported by the browser. List of XHTML modules supported by the browser. Property value is a list of module names, where each item in the list is the name of an XHTML module as defined by the W3C document "Modularization of XHTML", Section 4. List items are separated by white space. Note that the referenced document is a work in progress. Any subsequent changes to the module naming conventions should be reflected in the values of this property. Supported Bluetooth version. The bearer on which the current session was opened. List of types of security or encryption mechanisms supported by the device. List of bearers supported by the device. List of content types the device supports, which can be carried inside the message/http entity body when OTA-HTTP is used. Property value is a list of MIME types, where each item in the list is a content type descriptor as specified by RFC 2045. List of character sets the device supports. Property value is a list of character sets, where each item in the list is a character set name registered with IANA. List of transfer encodings the device supports. Property value is a list of transfer encodings, where each item in the list is a transfer encoding name as specified by RFC 2045 and registered with IANA. List of preferred document languages. If a resource is available in more than one natural language, the server can use this property to determine which version of the resource to send to the device. The first item in the list should be considered the user's first choice, the second the second choice, and so on. Property value is a list of natural languages, where each item in the list is the name of a language as defined by RFC 3066[RFC3066]. List of applications the device supports, where each item in the list is an application-id on absoluteURI format as specified in [PushMsg]. A wildcard ("*") may be used to indicate support for any application. Maximum size of a push message that the device can handle. Value is number of bytes. Maximum number of outstanding push requests that the device can handle. dom4j-1.6.1/xml/test/xpath/0000755000175000017500000000000012133227266014773 5ustar ebourgebourgdom4j-1.6.1/xml/test/xpath/tests.xml0000644000175000017500000003400210242120011016631 0ustar ebourgebourg This should work http://foo.com/bar?a=123&b=456&d=d9d9d 2 2 a.2 a.1 a.4 a.5 web-app web-app web-app web-app web-app web-app web-app web-app web-app web-app web-app web-app web-app web-app web-app web-app web-app web-app web-app http://c.moreover.com/click/here.pl?x13563273 http://c.moreover.com/click/here.pl?x13563273 http://c.moreover.com/click/here.pl?x13563273 http://c.moreover.com/click/here.pl?x13563273 http://c.moreover.com/click/here.pl?x13563273 http://c.moreover.com/click/here.pl?x13563273 196417 325 Much Ado about Nothing 4 21 5 35 75 2 1 6 Hello Hey Hey3 Hey3 Hey3 Hello Hey Hey3 Hey3 dom4j-1.6.1/xml/contents.xml0000644000175000017500000000510610242120025015231 0ustar ebourgebourg Java and XML Introduction What Is It? How Do I Use It? Why Should I Use It? What's Next? Creating XML An XML Document The Header The Content What's Next? Parsing XML Getting Prepared SAX Readers Content Handlers Error Handlers A Better Way to Load a Parser "Gotcha!" What's Next? Web Publishing Frameworks Selecting a Framework Installation Using a Publishing Framework XSP Cocoon 2.0 and Beyond What's Next? dom4j-1.6.1/xml/soap.xml0000644000175000017500000000073710242120014014341 0ustar ebourgebourg en_fr SOAP is quite easy with JSP & dom4j! dom4j-1.6.1/xml/xmlspec.xml0000644000175000017500000047524710242120015015067 0ustar ebourgebourg
Extensible Markup Language (XML) 1.0 REC-xml-19980210 W3C Recommendation 10February1998 http://www.w3.org/TR/1998/REC-xml-19980210 http://www.w3.org/TR/1998/REC-xml-19980210.xml http://www.w3.org/TR/1998/REC-xml-19980210.html http://www.w3.org/TR/1998/REC-xml-19980210.pdf http://www.w3.org/TR/1998/REC-xml-19980210.ps http://www.w3.org/TR/REC-xml http://www.w3.org/TR/PR-xml-971208 Tim Bray Textuality and Netscape tbray@textuality.com Jean Paoli Microsoft jeanpa@microsoft.com C. M. Sperberg-McQueen University of Illinois at Chicago cmsmcq@uic.edu

The Extensible Markup Language (XML) is a subset of SGML that is completely described in this document. Its goal is to enable generic SGML to be served, received, and processed on the Web in the way that is now possible with HTML. XML has been designed for ease of implementation and for interoperability with both SGML and HTML.

This document has been reviewed by W3C Members and other interested parties and has been endorsed by the Director as a W3C Recommendation. It is a stable document and may be used as reference material or cited as a normative reference from another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web.

This document specifies a syntax created by subsetting an existing, widely used international text processing standard (Standard Generalized Markup Language, ISO 8879:1986(E) as amended and corrected) for use on the World Wide Web. It is a product of the W3C XML Activity, details of which can be found at http://www.w3.org/XML. A list of current W3C Recommendations and other technical documents can be found at http://www.w3.org/TR.

This specification uses the term URI, which is defined by , a work in progress expected to update and .

The list of known errors in this specification is available at http://www.w3.org/XML/xml-19980210-errata.

Please report errors in this document to xml-editor@w3.org.

Chicago, Vancouver, Mountain View, et al.: World-Wide Web Consortium, XML Working Group, 1996, 1997.

Created in electronic form.

English Extended Backus-Naur Form (formal grammar) 1997-12-03 : CMSMcQ : yet further changes 1997-12-02 : TB : further changes (see TB to XML WG, 2 December 1997) 1997-12-02 : CMSMcQ : deal with as many corrections and comments from the proofreaders as possible: entify hard-coded document date in pubdate element, change expansion of entity WebSGML, update status description as per Dan Connolly (am not sure about refernece to Berners-Lee et al.), add 'The' to abstract as per WG decision, move Relationship to Existing Standards to back matter and combine with References, re-order back matter so normative appendices come first, re-tag back matter so informative appendices are tagged informdiv1, remove XXX XXX from list of 'normative' specs in prose, move some references from Other References to Normative References, add RFC 1738, 1808, and 2141 to Other References (they are not normative since we do not require the processor to enforce any rules based on them), add reference to 'Fielding draft' (Berners-Lee et al.), move notation section to end of body, drop URIchar non-terminal and use SkipLit instead, lose stray reference to defunct nonterminal 'markupdecls', move reference to Aho et al. into appendix (Tim's right), add prose note saying that hash marks and fragment identifiers are NOT part of the URI formally speaking, and are NOT legal in system identifiers (processor 'may' signal an error). Work through: Tim Bray reacting to James Clark, Tim Bray on his own, Eve Maler, NOT DONE YET: change binary / text to unparsed / parsed. handle James's suggestion about < in attriubte values uppercase hex characters, namechar list, 1997-12-01 : JB : add some column-width parameters 1997-12-01 : CMSMcQ : begin round of changes to incorporate recent WG decisions and other corrections: binding sources of character encoding info (27 Aug / 3 Sept), correct wording of Faust quotation (restore dropped line), drop SDD from EncodingDecl, change text at version number 1.0, drop misleading (wrong!) sentence about ignorables and extenders, modify definition of PCData to make bar on msc grammatical, change grammar's handling of internal subset (drop non-terminal markupdecls), change definition of includeSect to allow conditional sections, add integral-declaration constraint on internal subset, drop misleading / dangerous sentence about relationship of entities with system storage objects, change table body tag to htbody as per EM change to DTD, add rule about space normalization in public identifiers, add description of how to generate our name-space rules from Unicode character database (needs further work!). 1997-10-08 : TB : Removed %-constructs again, new rules for PE appearance. 1997-10-01 : TB : Case-sensitive markup; cleaned up element-type defs, lotsa little edits for style 1997-09-25 : TB : Change to elm's new DTD, with substantial detail cleanup as a side-effect 1997-07-24 : CMSMcQ : correct error (lost *) in definition of ignoreSectContents (thanks to Makoto Murata) Allow all empty elements to have end-tags, consistent with SGML TC (as per JJC). 1997-07-23 : CMSMcQ : pre-emptive strike on pending corrections: introduce the term 'empty-element tag', note that all empty elements may use it, and elements declared EMPTY must use it. Add WFC requiring encoding decl to come first in an entity. Redefine notations to point to PIs as well as binary entities. Change autodetection table by removing bytes 3 and 4 from examples with Byte Order Mark. Add content model as a term and clarify that it applies to both mixed and element content. 1997-06-30 : CMSMcQ : change date, some cosmetic changes, changes to productions for choice, seq, Mixed, NotationType, Enumeration. Follow James Clark's suggestion and prohibit conditional sections in internal subset. TO DO: simplify production for ignored sections as a result, since we don't need to worry about parsers which don't expand PErefs finding a conditional section. 1997-06-29 : TB : various edits 1997-06-29 : CMSMcQ : further changes: Suppress old FINAL EDIT comments and some dead material. Revise occurrences of % in grammar to exploit Henry Thompson's pun, especially markupdecl and attdef. Remove RMD requirement relating to element content (?). 1997-06-28 : CMSMcQ : Various changes for 1 July draft: Add text for draconian error handling (introduce the term Fatal Error). RE deleta est (changing wording from original announcement to restrict the requirement to validating parsers). Tag definition of validating processor and link to it. Add colon as name character. Change def of %operator. Change standard definitions of lt, gt, amp. Strip leading zeros from #x00nn forms. 1997-04-02 : CMSMcQ : final corrections of editorial errors found in last night's proofreading. Reverse course once more on well-formed: Webster's Second hyphenates it, and that's enough for me. 1997-04-01 : CMSMcQ : corrections from JJC, EM, HT, and self 1997-03-31 : Tim Bray : many changes 1997-03-29 : CMSMcQ : some Henry Thompson (on entity handling), some Charles Goldfarb, some ERB decisions (PE handling in miscellaneous declarations. Changed Ident element to accept def attribute. Allow normalization of Unicode characters. move def of systemliteral into section on literals. 1997-03-28 : CMSMcQ : make as many corrections as possible, from Terry Allen, Norbert Mikula, James Clark, Jon Bosak, Henry Thompson, Paul Grosso, and self. Among other things: give in on "well formed" (Terry is right), tentatively rename QuotedCData as AttValue and Literal as EntityValue to be more informative, since attribute values are the only place QuotedCData was used, and vice versa for entity text and Literal. (I'd call it Entity Text, but 8879 uses that name for both internal and external entities.) 1997-03-26 : CMSMcQ : resynch the two forks of this draft, reapply my changes dated 03-20 and 03-21. Normalize old 'may not' to 'must not' except in the one case where it meant 'may or may not'. 1997-03-21 : TB : massive changes on plane flight from Chicago to Vancouver 1997-03-21 : CMSMcQ : correct as many reported errors as possible. 1997-03-20 : CMSMcQ : correct typos listed in CMSMcQ hand copy of spec. 1997-03-20 : CMSMcQ : cosmetic changes preparatory to revision for WWW conference April 1997: restore some of the internal entity references (e.g. to docdate, etc.), change character xA0 to &nbsp; and define nbsp as &#160;, and refill a lot of paragraphs for legibility. 1996-11-12 : CMSMcQ : revise using Tim's edits: Add list type of NUMBERED and change most lists either to BULLETS or to NUMBERED. Suppress QuotedNames, Names (not used). Correct trivial-grammar doc type decl. Rename 'marked section' as 'CDATA section' passim. Also edits from James Clark: Define the set of characters from which [^abc] subtracts. Charref should use just [0-9] not Digit. Location info needs cleaner treatment: remove? (ERB question). One example of a PI has wrong pic. Clarify discussion of encoding names. Encoding failure should lead to unspecified results; don't prescribe error recovery. Don't require exposure of entity boundaries. Ignore white space in element content. Reserve entity names of the form u-NNNN. Clarify relative URLs. And some of my own: Correct productions for content model: model cannot consist of a name, so "elements ::= cp" is no good. 1996-11-11 : CMSMcQ : revise for style. Add new rhs to entity declaration, for parameter entities. 1996-11-10 : CMSMcQ : revise for style. Fix / complete section on names, characters. Add sections on parameter entities, conditional sections. Still to do: Add compatibility note on deterministic content models. Finish stylistic revision. 1996-10-31 : TB : Add Entity Handling section 1996-10-30 : TB : Clean up term & termdef. Slip in ERB decision re EMPTY. 1996-10-28 : TB : Change DTD. Implement some of Michael's suggestions. Change comments back to //. Introduce language for XML namespace reservation. Add section on white-space handling. Lots more cleanup. 1996-10-24 : CMSMcQ : quick tweaks, implement some ERB decisions. Characters are not integers. Comments are /* */ not //. Add bibliographic refs to 10646, HyTime, Unicode. Rename old Cdata as MsData since it's only seen in marked sections. Call them attribute-value pairs not name-value pairs, except once. Internal subset is optional, needs '?'. Implied attributes should be signaled to the app, not have values supplied by processor. 1996-10-16 : TB : track down & excise all DSD references; introduce some EBNF for entity declarations. 1996-10-?? : TB : consistency check, fix up scraps so they all parse, get formatter working, correct a few productions. 1996-10-10/11 : CMSMcQ : various maintenance, stylistic, and organizational changes: Replace a few literals with xmlpio and pic entities, to make them consistent and ensure we can change pic reliably when the ERB votes. Drop paragraph on recognizers from notation section. Add match, exact match to terminology. Move old 2.2 XML Processors and Apps into intro. Mention comments, PIs, and marked sections in discussion of delimiter escaping. Streamline discussion of doctype decl syntax. Drop old section of 'PI syntax' for doctype decl, and add section on partial-DTD summary PIs to end of Logical Structures section. Revise DSD syntax section to use Tim's subset-in-a-PI mechanism. 1996-10-10 : TB : eliminate name recognizers (and more?) 1996-10-09 : CMSMcQ : revise for style, consistency through 2.3 (Characters) 1996-10-09 : CMSMcQ : re-unite everything for convenience, at least temporarily, and revise quickly 1996-10-08 : TB : first major homogenization pass 1996-10-08 : TB : turn "current" attribute on div type into CDATA 1996-10-02 : TB : remould into skeleton + entities 1996-09-30 : CMSMcQ : add a few more sections prior to exchange with Tim. 1996-09-20 : CMSMcQ : finish transcribing notes. 1996-09-19 : CMSMcQ : begin transcribing notes for draft. 1996-09-13 : CMSMcQ : made outline from notes of 09-06, do some housekeeping
Introduction

Extensible Markup Language, abbreviated XML, describes a class of data objects called XML documents and partially describes the behavior of computer programs which process them. XML is an application profile or restricted form of SGML, the Standard Generalized Markup Language . By construction, XML documents are conforming SGML documents.

XML documents are made up of storage units called entities, which contain either parsed or unparsed data. Parsed data is made up of characters, some of which form character data, and some of which form markup. Markup encodes a description of the document's storage layout and logical structure. XML provides a mechanism to impose constraints on the storage layout and logical structure.

A software module called an XML processor is used to read XML documents and provide access to their content and structure. It is assumed that an XML processor is doing its work on behalf of another module, called the application. This specification describes the required behavior of an XML processor in terms of how it must read XML data and the information it must provide to the application.

Origin and Goals

XML was developed by an XML Working Group (originally known as the SGML Editorial Review Board) formed under the auspices of the World Wide Web Consortium (W3C) in 1996. It was chaired by Jon Bosak of Sun Microsystems with the active participation of an XML Special Interest Group (previously known as the SGML Working Group) also organized by the W3C. The membership of the XML Working Group is given in an appendix. Dan Connolly served as the WG's contact with the W3C.

The design goals for XML are:

XML shall be straightforwardly usable over the Internet.

XML shall support a wide variety of applications.

XML shall be compatible with SGML.

It shall be easy to write programs which process XML documents.

The number of optional features in XML is to be kept to the absolute minimum, ideally zero.

XML documents should be human-legible and reasonably clear.

The XML design should be prepared quickly.

The design of XML shall be formal and concise.

XML documents shall be easy to create.

Terseness in XML markup is of minimal importance.

This specification, together with associated standards (Unicode and ISO/IEC 10646 for characters, Internet RFC 1766 for language identification tags, ISO 639 for language name codes, and ISO 3166 for country name codes), provides all the information necessary to understand XML Version 1.0 and construct computer programs to process it.

This version of the XML specification may be distributed freely, as long as all text and legal notices remain intact.

Terminology

The terminology used to describe XML documents is defined in the body of this specification. The terms defined in the following list are used in building those definitions and in describing the actions of an XML processor:

Conforming documents and XML processors are permitted to but need not behave as described.

Conforming documents and XML processors are required to behave as described; otherwise they are in error.

A violation of the rules of this specification; results are undefined. Conforming software may detect and report an error and may recover from it.

An error which a conforming XML processor must detect and report to the application. After encountering a fatal error, the processor may continue processing the data to search for further errors and may report such errors to the application. In order to support correction of errors, the processor may make unprocessed data from the document (with intermingled character data and markup) available to the application. Once a fatal error is detected, however, the processor must not continue normal processing (i.e., it must not continue to pass character data and information about the document's logical structure to the application in the normal way).

Conforming software may or must (depending on the modal verb in the sentence) behave as described; if it does, it must provide users a means to enable or disable the behavior described.

A rule which applies to all valid XML documents. Violations of validity constraints are errors; they must, at user option, be reported by validating XML processors.

A rule which applies to all well-formed XML documents. Violations of well-formedness constraints are fatal errors.

(Of strings or names:) Two strings or names being compared must be identical. Characters with multiple possible representations in ISO/IEC 10646 (e.g. characters with both precomposed and base+diacritic forms) match only if they have the same representation in both strings. At user option, processors may normalize such characters to some canonical form. No case folding is performed. (Of strings and rules in the grammar:) A string matches a grammatical production if it belongs to the language generated by that production. (Of content and content models:) An element matches its declaration when it conforms in the fashion described in the constraint .

A feature of XML included solely to ensure that XML remains compatible with SGML.

A non-binding recommendation included to increase the chances that XML documents can be processed by the existing installed base of SGML processors which predate the WebSGML Adaptations Annex to ISO 8879.

Documents

A data object is an XML document if it is well-formed, as defined in this specification. A well-formed XML document may in addition be valid if it meets certain further constraints.

Each XML document has both a logical and a physical structure. Physically, the document is composed of units called entities. An entity may refer to other entities to cause their inclusion in the document. A document begins in a "root" or document entity. Logically, the document is composed of declarations, elements, comments, character references, and processing instructions, all of which are indicated in the document by explicit markup. The logical and physical structures must nest properly, as described in .

Well-Formed XML Documents

A textual object is a well-formed XML document if:

Taken as a whole, it matches the production labeled document.

It meets all the well-formedness constraints given in this specification.

Each of the parsed entities which is referenced directly or indirectly within the document is well-formed.

Document document prolog element Misc*

Matching the document production implies that:

It contains one or more elements.

There is exactly one element, called the root, or document element, no part of which appears in the content of any other element. For all other elements, if the start-tag is in the content of another element, the end-tag is in the content of the same element. More simply stated, the elements, delimited by start- and end-tags, nest properly within each other.

As a consequence of this, for each non-root element C in the document, there is one other element P in the document such that C is in the content of P, but is not in the content of any other element that is in the content of P. P is referred to as the parent of C, and C as a child of P.

Characters

A parsed entity contains text, a sequence of characters, which may represent markup or character data. A character is an atomic unit of text as specified by ISO/IEC 10646 . Legal characters are tab, carriage return, line feed, and the legal graphic characters of Unicode and ISO/IEC 10646. The use of "compatibility characters", as defined in section 6.8 of , is discouraged. Character Range Char #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.

The mechanism for encoding character code points into bit patterns may vary from entity to entity. All XML processors must accept the UTF-8 and UTF-16 encodings of 10646; the mechanisms for signaling which of the two is in use, or for bringing other encodings into play, are discussed later, in .

Common Syntactic Constructs

This section defines some symbols used widely in the grammar.

S (white space) consists of one or more space (#x20) characters, carriage returns, line feeds, or tabs. White Space S (#x20 | #x9 | #xD | #xA)+

Characters are classified for convenience as letters, digits, or other characters. Letters consist of an alphabetic or syllabic base character possibly followed by one or more combining characters, or of an ideographic character. Full definitions of the specific characters in each class are given in .

A Name is a token beginning with a letter or one of a few punctuation characters, and continuing with letters, digits, hyphens, underscores, colons, or full stops, together known as name characters. Names beginning with the string "xml", or any string which would match (('X'|'x') ('M'|'m') ('L'|'l')), are reserved for standardization in this or future versions of this specification.

The colon character within XML names is reserved for experimentation with name spaces. Its meaning is expected to be standardized at some future point, at which point those documents using the colon for experimental purposes may need to be updated. (There is no guarantee that any name-space mechanism adopted for XML will in fact use the colon as a name-space delimiter.) In practice, this means that authors should not use the colon in XML names except as part of name-space experiments, but that XML processors should accept the colon as a name character.

An Nmtoken (name token) is any mixture of name characters. Names and Tokens NameChar Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender Name (Letter | '_' | ':') (NameChar)* Names Name (S Name)* Nmtoken (NameChar)+ Nmtokens Nmtoken (S Nmtoken)*

Literal data is any quoted string not containing the quotation mark used as a delimiter for that string. Literals are used for specifying the content of internal entities (EntityValue), the values of attributes (AttValue), and external identifiers (SystemLiteral). Note that a SystemLiteral can be parsed without scanning for markup. Literals EntityValue '"' ([^%&"] | PEReference | Reference)* '"' |  "'" ([^%&'] | PEReference | Reference)* "'" AttValue '"' ([^<&"] | Reference)* '"' |  "'" ([^<&'] | Reference)* "'" SystemLiteral ('"' [^"]* '"') | ("'" [^']* "'") PubidLiteral '"' PubidChar* '"' | "'" (PubidChar - "'")* "'" PubidChar #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%]

Character Data and Markup

Text consists of intermingled character data and markup. Markup takes the form of start-tags, end-tags, empty-element tags, entity references, character references, comments, CDATA section delimiters, document type declarations, and processing instructions.

All text that is not markup constitutes the character data of the document.

The ampersand character (&) and the left angle bracket (<) may appear in their literal form only when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. They are also legal within the literal entity value of an internal entity declaration; see . If they are needed elsewhere, they must be escaped using either numeric character references or the strings "&amp;" and "&lt;" respectively. The right angle bracket (>) may be represented using the string "&gt;", and must, for compatibility, be escaped using "&gt;" or a character reference when it appears in the string "]]>" in content, when that string is not marking the end of a CDATA section.

In the content of elements, character data is any string of characters which does not contain the start-delimiter of any markup. In a CDATA section, character data is any string of characters not including the CDATA-section-close delimiter, "]]>".

To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (') may be represented as "&apos;", and the double-quote character (") as "&quot;". Character Data CharData [^<&]* - ([^<&]* ']]>' [^<&]*)

Comments

Comments may appear anywhere in a document outside other markup; in addition, they may appear within the document type declaration at places allowed by the grammar. They are not part of the document's character data; an XML processor may, but need not, make it possible for an application to retrieve the text of comments. For compatibility, the string "--" (double-hyphen) must not occur within comments. Comments Comment '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'

An example of a comment: <!-- declarations for <head> & <body> -->

Processing Instructions

Processing instructions (PIs) allow documents to contain instructions for applications. Processing Instructions PI '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>' PITarget Name - (('X' | 'x') ('M' | 'm') ('L' | 'l')) PIs are not part of the document's character data, but must be passed through to the application. The PI begins with a target (PITarget) used to identify the application to which the instruction is directed. The target names "XML", "xml", and so on are reserved for standardization in this or future versions of this specification. The XML Notation mechanism may be used for formal declaration of PI targets.

CDATA Sections

CDATA sections may occur anywhere character data may occur; they are used to escape blocks of text containing characters which would otherwise be recognized as markup. CDATA sections begin with the string "<![CDATA[" and end with the string "]]>": CDATA Sections CDSect CDStart CData CDEnd CDStart '<![CDATA[' CData (Char* - (Char* ']]>' Char*)) CDEnd ']]>' Within a CDATA section, only the CDEnd string is recognized as markup, so that left angle brackets and ampersands may occur in their literal form; they need not (and cannot) be escaped using "&lt;" and "&amp;". CDATA sections cannot nest.

An example of a CDATA section, in which "<greeting>" and "</greeting>" are recognized as character data, not markup: <![CDATA[<greeting>Hello, world!</greeting>]]>

Prolog and Document Type Declaration

XML documents may, and should, begin with an XML declaration which specifies the version of XML being used. For example, the following is a complete XML document, well-formed but not valid: Hello, world! ]]> and so is this: Hello, world! ]]>

The version number "1.0" should be used to indicate conformance to this version of this specification; it is an error for a document to use the value "1.0" if it does not conform to this version of this specification. It is the intent of the XML working group to give later versions of this specification numbers other than "1.0", but this intent does not indicate a commitment to produce any future versions of XML, nor if any are produced, to use any particular numbering scheme. Since future versions are not ruled out, this construct is provided as a means to allow the possibility of automatic version recognition, should it become necessary. Processors may signal an error if they receive documents labeled with versions they do not support.

The function of the markup in an XML document is to describe its storage and logical structure and to associate attribute-value pairs with its logical structures. XML provides a mechanism, the document type declaration, to define constraints on the logical structure and to support the use of predefined storage units. An XML document is valid if it has an associated document type declaration and if the document complies with the constraints expressed in it.

The document type declaration must appear before the first element in the document. Prolog prolog XMLDecl? Misc* (doctypedecl Misc*)? XMLDecl '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>' VersionInfo S 'version' Eq (' VersionNum ' | " VersionNum ") Eq S? '=' S? VersionNum ([a-zA-Z0-9_.:] | '-')+ Misc Comment | PI | S

The XML document type declaration contains or points to markup declarations that provide a grammar for a class of documents. This grammar is known as a document type definition, or DTD. The document type declaration can point to an external subset (a special kind of external entity) containing markup declarations, or can contain the markup declarations directly in an internal subset, or can do both. The DTD for a document consists of both subsets taken together.

A markup declaration is an element type declaration, an attribute-list declaration, an entity declaration, or a notation declaration. These declarations may be contained in whole or in part within parameter entities, as described in the well-formedness and validity constraints below. For fuller information, see .

Document Type Definition doctypedecl '<!DOCTYPE' S Name (S ExternalID)? S? ('[' (markupdecl | PEReference | S)* ']' S?)? '>' markupdecl elementdecl | AttlistDecl | EntityDecl | NotationDecl | PI | Comment

The markup declarations may be made up in whole or in part of the replacement text of parameter entities. The productions later in this specification for individual nonterminals (elementdecl, AttlistDecl, and so on) describe the declarations after all the parameter entities have been included.

Root Element Type

The Name in the document type declaration must match the element type of the root element.

Proper Declaration/PE Nesting

Parameter-entity replacement text must be properly nested with markup declarations. That is to say, if either the first character or the last character of a markup declaration (markupdecl above) is contained in the replacement text for a parameter-entity reference, both must be contained in the same replacement text.

PEs in Internal Subset

In the internal DTD subset, parameter-entity references can occur only where markup declarations can occur, not within markup declarations. (This does not apply to references that occur in external parameter entities or to the external subset.)

Like the internal subset, the external subset and any external parameter entities referred to in the DTD must consist of a series of complete markup declarations of the types allowed by the non-terminal symbol markupdecl, interspersed with white space or parameter-entity references. However, portions of the contents of the external subset or of external parameter entities may conditionally be ignored by using the conditional section construct; this is not allowed in the internal subset. External Subset extSubset TextDecl? extSubsetDecl extSubsetDecl ( markupdecl | conditionalSect | PEReference | S )*

The external subset and external parameter entities also differ from the internal subset in that in them, parameter-entity references are permitted within markup declarations, not only between markup declarations.

An example of an XML document with a document type declaration: Hello, world! ]]> The system identifier "hello.dtd" gives the URI of a DTD for the document.

The declarations can also be given locally, as in this example: ]> Hello, world! ]]> If both the external and internal subsets are used, the internal subset is considered to occur before the external subset. This has the effect that entity and attribute-list declarations in the internal subset take precedence over those in the external subset.

Standalone Document Declaration

Markup declarations can affect the content of the document, as passed from an XML processor to an application; examples are attribute defaults and entity declarations. The standalone document declaration, which may appear as a component of the XML declaration, signals whether or not there are such declarations which appear external to the document entity. Standalone Document Declaration SDDecl S 'standalone' Eq (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no') '"'))

In a standalone document declaration, the value "yes" indicates that there are no markup declarations external to the document entity (either in the DTD external subset, or in an external parameter entity referenced from the internal subset) which affect the information passed from the XML processor to the application. The value "no" indicates that there are or may be such external markup declarations. Note that the standalone document declaration only denotes the presence of external declarations; the presence, in a document, of references to external entities, when those entities are internally declared, does not change its standalone status.

If there are no external markup declarations, the standalone document declaration has no meaning. If there are external markup declarations but there is no standalone document declaration, the value "no" is assumed.

Any XML document for which standalone="no" holds can be converted algorithmically to a standalone document, which may be desirable for some network delivery applications.

Standalone Document Declaration

The standalone document declaration must have the value "no" if any external markup declarations contain declarations of:

attributes with default values, if elements to which these attributes apply appear in the document without specifications of values for these attributes, or

entities (other than amp, lt, gt, apos, quot), if references to those entities appear in the document, or

attributes with values subject to normalization, where the attribute appears in the document with a value which will change as a result of normalization, or

element types with element content, if white space occurs directly within any instance of those types.

An example XML declaration with a standalone document declaration:<?xml version="1.0" standalone='yes'?>

White Space Handling

In editing XML documents, it is often convenient to use "white space" (spaces, tabs, and blank lines, denoted by the nonterminal S in this specification) to set apart the markup for greater readability. Such white space is typically not intended for inclusion in the delivered version of the document. On the other hand, "significant" white space that should be preserved in the delivered version is common, for example in poetry and source code.

An XML processor must always pass all characters in a document that are not markup through to the application. A validating XML processor must also inform the application which of these characters constitute white space appearing in element content.

A special attribute named xml:space may be attached to an element to signal an intention that in that element, white space should be preserved by applications. In valid documents, this attribute, like any other, must be declared if it is used. When declared, it must be given as an enumerated type whose only possible values are "default" and "preserve". For example:]]>

The value "default" signals that applications' default white-space processing modes are acceptable for this element; the value "preserve" indicates the intent that applications preserve all the white space. This declared intent is considered to apply to all elements within the content of the element where it is specified, unless overriden with another instance of the xml:space attribute.

The root element of any document is considered to have signaled no intentions as regards application space handling, unless it provides a value for this attribute or the attribute is declared with a default value.

End-of-Line Handling

XML parsed entities are often stored in computer files which, for editing convenience, are organized into lines. These lines are typically separated by some combination of the characters carriage-return (#xD) and line-feed (#xA).

To simplify the tasks of applications, wherever an external parsed entity or the literal entity value of an internal parsed entity contains either the literal two-character sequence "#xD#xA" or a standalone literal #xD, an XML processor must pass to the application the single character #xA. (This behavior can conveniently be produced by normalizing all line breaks to #xA on input, before parsing.)

Language Identification

In document processing, it is often useful to identify the natural or formal language in which the content is written. A special attribute named xml:lang may be inserted in documents to specify the language used in the contents and attribute values of any element in an XML document. In valid documents, this attribute, like any other, must be declared if it is used. The values of the attribute are language identifiers as defined by , "Tags for the Identification of Languages": Language Identification LanguageID Langcode ('-' Subcode)* Langcode ISO639Code | IanaCode | UserCode ISO639Code ([a-z] | [A-Z]) ([a-z] | [A-Z]) IanaCode ('i' | 'I') '-' ([a-z] | [A-Z])+ UserCode ('x' | 'X') '-' ([a-z] | [A-Z])+ Subcode ([a-z] | [A-Z])+ The Langcode may be any of the following:

a two-letter language code as defined by , "Codes for the representation of names of languages"

a language identifier registered with the Internet Assigned Numbers Authority ; these begin with the prefix "i-" (or "I-")

a language identifier assigned by the user, or agreed on between parties in private use; these must begin with the prefix "x-" or "X-" in order to ensure that they do not conflict with names later standardized or registered with IANA

There may be any number of Subcode segments; if the first subcode segment exists and the Subcode consists of two letters, then it must be a country code from , "Codes for the representation of names of countries." If the first subcode consists of more than two letters, it must be a subcode for the language in question registered with IANA, unless the Langcode begins with the prefix "x-" or "X-".

It is customary to give the language code in lower case, and the country code (if any) in upper case. Note that these values, unlike other names in XML documents, are case insensitive.

For example: The quick brown fox jumps over the lazy dog.

What colour is it?

What color is it?

Habe nun, ach! Philosophie, Juristerei, und Medizin und leider auch Theologie durchaus studiert mit heiem Bemh'n. ]]>

The intent declared with xml:lang is considered to apply to all attributes and content of the element where it is specified, unless overridden with an instance of xml:lang on another element within that content.

A simple declaration for xml:lang might take the form xml:lang NMTOKEN #IMPLIED but specific default values may also be given, if appropriate. In a collection of French poems for English students, with glosses and notes in English, the xml:lang attribute might be declared this way: ]]>

Logical Structures

Each XML document contains one or more elements, the boundaries of which are either delimited by start-tags and end-tags, or, for empty elements, by an empty-element tag. Each element has a type, identified by name, sometimes called its "generic identifier" (GI), and may have a set of attribute specifications. Each attribute specification has a name and a value.

Element element EmptyElemTag | STag content ETag

This specification does not constrain the semantics, use, or (beyond syntax) names of the element types and attributes, except that names beginning with a match to (('X'|'x')('M'|'m')('L'|'l')) are reserved for standardization in this or future versions of this specification.

Element Type Match

The Name in an element's end-tag must match the element type in the start-tag.

Element Valid

An element is valid if there is a declaration matching elementdecl where the Name matches the element type, and one of the following holds:

The declaration matches EMPTY and the element has no content.

The declaration matches children and the sequence of child elements belongs to the language generated by the regular expression in the content model, with optional white space (characters matching the nonterminal S) between each pair of child elements.

The declaration matches Mixed and the content consists of character data and child elements whose types match names in the content model.

The declaration matches ANY, and the types of any child elements have been declared.

Start-Tags, End-Tags, and Empty-Element Tags

The beginning of every non-empty XML element is marked by a start-tag. Start-tag STag '<' Name (S Attribute)* S? '>' Attribute Name Eq AttValue The Name in the start- and end-tags gives the element's type. The Name-AttValue pairs are referred to as the attribute specifications of the element, with the Name in each pair referred to as the attribute name and the content of the AttValue (the text between the ' or " delimiters) as the attribute value.

Unique Att Spec

No attribute name may appear more than once in the same start-tag or empty-element tag.

Attribute Value Type

The attribute must have been declared; the value must be of the type declared for it. (For attribute types, see .)

No External Entity References

Attribute values cannot contain direct or indirect entity references to external entities.

No < in Attribute Values

The replacement text of any entity referred to directly or indirectly in an attribute value (other than "&lt;") must not contain a <.

An example of a start-tag: <termdef id="dt-dog" term="dog">

The end of every element that begins with a start-tag must be marked by an end-tag containing a name that echoes the element's type as given in the start-tag: End-tag ETag '</' Name S? '>'

An example of an end-tag:</termdef>

The text between the start-tag and end-tag is called the element's content: Content of Elements content (element | CharData | Reference | CDSect | PI | Comment)*

If an element is empty, it must be represented either by a start-tag immediately followed by an end-tag or by an empty-element tag. An empty-element tag takes a special form: Tags for Empty Elements EmptyElemTag '<' Name (S Attribute)* S? '/>'

Empty-element tags may be used for any element which has no content, whether or not it is declared using the keyword EMPTY. For interoperability, the empty-element tag must be used, and can only be used, for elements which are declared EMPTY.

Examples of empty elements: <IMG align="left" src="http://www.w3.org/Icons/WWW/w3c_home" /> <br></br> <br/>

Element Type Declarations

The element structure of an XML document may, for validation purposes, be constrained using element type and attribute-list declarations. An element type declaration constrains the element's content.

Element type declarations often constrain which element types can appear as children of the element. At user option, an XML processor may issue a warning when a declaration mentions an element type for which no declaration is provided, but this is not an error.

An element type declaration takes the form: Element Type Declaration elementdecl '<!ELEMENT' S Name S contentspec S? '>' contentspec 'EMPTY' | 'ANY' | Mixed | children where the Name gives the element type being declared.

Unique Element Type Declaration

No element type may be declared more than once.

Examples of element type declarations: <!ELEMENT br EMPTY> <!ELEMENT p (#PCDATA|emph)* > <!ELEMENT %name.para; %content.para; > <!ELEMENT container ANY>

Element Content

An element type has element content when elements of that type must contain only child elements (no character data), optionally separated by white space (characters matching the nonterminal S). In this case, the constraint includes a content model, a simple grammar governing the allowed types of the child elements and the order in which they are allowed to appear. The grammar is built on content particles (cps), which consist of names, choice lists of content particles, or sequence lists of content particles: Element-content Models children (choice | seq) ('?' | '*' | '+')? cp (Name | choice | seq) ('?' | '*' | '+')? choice '(' S? cp ( S? '|' S? cp )* S? ')' seq '(' S? cp ( S? ',' S? cp )* S? ')' where each Name is the type of an element which may appear as a child. Any content particle in a choice list may appear in the element content at the location where the choice list appears in the grammar; content particles occurring in a sequence list must each appear in the element content in the order given in the list. The optional character following a name or list governs whether the element or the content particles in the list may occur one or more (+), zero or more (*), or zero or one times (?). The absence of such an operator means that the element or content particle must appear exactly once. This syntax and meaning are identical to those used in the productions in this specification.

The content of an element matches a content model if and only if it is possible to trace out a path through the content model, obeying the sequence, choice, and repetition operators and matching each element in the content against an element type in the content model. For compatibility, it is an error if an element in the document can match more than one occurrence of an element type in the content model. For more information, see .

Proper Group/PE Nesting

Parameter-entity replacement text must be properly nested with parenthetized groups. That is to say, if either of the opening or closing parentheses in a choice, seq, or Mixed construct is contained in the replacement text for a parameter entity, both must be contained in the same replacement text.

For interoperability, if a parameter-entity reference appears in a choice, seq, or Mixed construct, its replacement text should not be empty, and neither the first nor last non-blank character of the replacement text should be a connector (| or ,).

Examples of element-content models: <!ELEMENT spec (front, body, back?)> <!ELEMENT div1 (head, (p | list | note)*, div2*)> <!ELEMENT dictionary-body (%div.mix; | %dict.mix;)*>

Mixed Content

An element type has mixed content when elements of that type may contain character data, optionally interspersed with child elements. In this case, the types of the child elements may be constrained, but not their order or their number of occurrences: Mixed-content Declaration Mixed '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*' | '(' S? '#PCDATA' S? ')' where the Names give the types of elements that may appear as children.

No Duplicate Types

The same name must not appear more than once in a single mixed-content declaration.

Examples of mixed content declarations: <!ELEMENT p (#PCDATA|a|ul|b|i|em)*> <!ELEMENT p (#PCDATA | %font; | %phrase; | %special; | %form;)* > <!ELEMENT b (#PCDATA)>

Attribute-List Declarations

Attributes are used to associate name-value pairs with elements. Attribute specifications may appear only within start-tags and empty-element tags; thus, the productions used to recognize them appear in . Attribute-list declarations may be used:

To define the set of attributes pertaining to a given element type.

To establish type constraints for these attributes.

To provide default values for attributes.

Attribute-list declarations specify the name, data type, and default value (if any) of each attribute associated with a given element type: Attribute-list Declaration AttlistDecl '<!ATTLIST' S Name AttDef* S? '>' AttDef S Name S AttType S DefaultDecl The Name in the AttlistDecl rule is the type of an element. At user option, an XML processor may issue a warning if attributes are declared for an element type not itself declared, but this is not an error. The Name in the AttDef rule is the name of the attribute.

When more than one AttlistDecl is provided for a given element type, the contents of all those provided are merged. When more than one definition is provided for the same attribute of a given element type, the first declaration is binding and later declarations are ignored. For interoperability, writers of DTDs may choose to provide at most one attribute-list declaration for a given element type, at most one attribute definition for a given attribute name, and at least one attribute definition in each attribute-list declaration. For interoperability, an XML processor may at user option issue a warning when more than one attribute-list declaration is provided for a given element type, or more than one attribute definition is provided for a given attribute, but this is not an error.

Attribute Types

XML attribute types are of three kinds: a string type, a set of tokenized types, and enumerated types. The string type may take any literal string as a value; the tokenized types have varying lexical and semantic constraints, as noted: Attribute Types AttType StringType | TokenizedType | EnumeratedType StringType 'CDATA' TokenizedType 'ID' | 'IDREF' | 'IDREFS' | 'ENTITY' | 'ENTITIES' | 'NMTOKEN' | 'NMTOKENS'

ID

Values of type ID must match the Name production. A name must not appear more than once in an XML document as a value of this type; i.e., ID values must uniquely identify the elements which bear them.

One ID per Element Type

No element type may have more than one ID attribute specified.

ID Attribute Default

An ID attribute must have a declared default of #IMPLIED or #REQUIRED.

IDREF

Values of type IDREF must match the Name production, and values of type IDREFS must match Names; each Name must match the value of an ID attribute on some element in the XML document; i.e. IDREF values must match the value of some ID attribute.

Entity Name

Values of type ENTITY must match the Name production, values of type ENTITIES must match Names; each Name must match the name of an unparsed entity declared in the DTD.

Name Token

Values of type NMTOKEN must match the Nmtoken production; values of type NMTOKENS must match Nmtokens.

Enumerated attributes can take one of a list of values provided in the declaration. There are two kinds of enumerated types: Enumerated Attribute Types EnumeratedType NotationType | Enumeration NotationType 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')' Enumeration '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')' A NOTATION attribute identifies a notation, declared in the DTD with associated system and/or public identifiers, to be used in interpreting the element to which the attribute is attached.

Notation Attributes

Values of this type must match one of the notation names included in the declaration; all notation names in the declaration must be declared.

Enumeration

Values of this type must match one of the Nmtoken tokens in the declaration.

For interoperability, the same Nmtoken should not occur more than once in the enumerated attribute types of a single element type.

Attribute Defaults

An attribute declaration provides information on whether the attribute's presence is required, and if not, how an XML processor should react if a declared attribute is absent in a document. Attribute Defaults DefaultDecl '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)

In an attribute declaration, #REQUIRED means that the attribute must always be provided, #IMPLIED that no default value is provided. If the declaration is neither #REQUIRED nor #IMPLIED, then the AttValue value contains the declared default value; the #FIXED keyword states that the attribute must always have the default value. If a default value is declared, when an XML processor encounters an omitted attribute, it is to behave as though the attribute were present with the declared default value.

Required Attribute

If the default declaration is the keyword #REQUIRED, then the attribute must be specified for all elements of the type in the attribute-list declaration.

Attribute Default Legal

The declared default value must meet the lexical constraints of the declared attribute type.

Fixed Attribute Default

If an attribute has a default value declared with the #FIXED keyword, instances of that attribute must match the default value.

Examples of attribute-list declarations: <!ATTLIST termdef id ID #REQUIRED name CDATA #IMPLIED> <!ATTLIST list type (bullets|ordered|glossary) "ordered"> <!ATTLIST form method CDATA #FIXED "POST">

Attribute-Value Normalization

Before the value of an attribute is passed to the application or checked for validity, the XML processor must normalize it as follows:

a character reference is processed by appending the referenced character to the attribute value

an entity reference is processed by recursively processing the replacement text of the entity

a whitespace character (#x20, #xD, #xA, #x9) is processed by appending #x20 to the normalized value, except that only a single #x20 is appended for a "#xD#xA" sequence that is part of an external parsed entity or the literal entity value of an internal parsed entity

other characters are processed by appending them to the normalized value

If the declared value is not CDATA, then the XML processor must further process the normalized attribute value by discarding any leading and trailing space (#x20) characters, and by replacing sequences of space (#x20) characters by a single space (#x20) character.

All attributes for which no declaration has been read should be treated by a non-validating parser as if declared CDATA.

Conditional Sections

Conditional sections are portions of the document type declaration external subset which are included in, or excluded from, the logical structure of the DTD based on the keyword which governs them. Conditional Section conditionalSect includeSect | ignoreSect includeSect '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>' ignoreSect '<![' S? 'IGNORE' S? '[' ignoreSectContents* ']]>' ignoreSectContents Ignore ('<![' ignoreSectContents ']]>' Ignore)* Ignore Char* - (Char* ('<![' | ']]>') Char*)

Like the internal and external DTD subsets, a conditional section may contain one or more complete declarations, comments, processing instructions, or nested conditional sections, intermingled with white space.

If the keyword of the conditional section is INCLUDE, then the contents of the conditional section are part of the DTD. If the keyword of the conditional section is IGNORE, then the contents of the conditional section are not logically part of the DTD. Note that for reliable parsing, the contents of even ignored conditional sections must be read in order to detect nested conditional sections and ensure that the end of the outermost (ignored) conditional section is properly detected. If a conditional section with a keyword of INCLUDE occurs within a larger conditional section with a keyword of IGNORE, both the outer and the inner conditional sections are ignored.

If the keyword of the conditional section is a parameter-entity reference, the parameter entity must be replaced by its content before the processor decides whether to include or ignore the conditional section.

An example: <!ENTITY % draft 'INCLUDE' > <!ENTITY % final 'IGNORE' > <![%draft;[ <!ELEMENT book (comments*, title, body, supplements?)> ]]> <![%final;[ <!ELEMENT book (title, body, supplements?)> ]]>

Physical Structures

An XML document may consist of one or many storage units. These are called entities; they all have content and are all (except for the document entity, see below, and the external DTD subset) identified by name. Each XML document has one entity called the document entity, which serves as the starting point for the XML processor and may contain the whole document.

Entities may be either parsed or unparsed. A parsed entity's contents are referred to as its replacement text; this text is considered an integral part of the document.

An unparsed entity is a resource whose contents may or may not be text, and if text, may not be XML. Each unparsed entity has an associated notation, identified by name. Beyond a requirement that an XML processor make the identifiers for the entity and notation available to the application, XML places no constraints on the contents of unparsed entities.

Parsed entities are invoked by name using entity references; unparsed entities by name, given in the value of ENTITY or ENTITIES attributes.

General entities are entities for use within the document content. In this specification, general entities are sometimes referred to with the unqualified term entity when this leads to no ambiguity. Parameter entities are parsed entities for use within the DTD. These two types of entities use different forms of reference and are recognized in different contexts. Furthermore, they occupy different namespaces; a parameter entity and a general entity with the same name are two distinct entities.

Character and Entity References

A character reference refers to a specific character in the ISO/IEC 10646 character set, for example one not directly accessible from available input devices. Character Reference CharRef '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';' Legal Character

Characters referred to using character references must match the production for Char.

If the character reference begins with "&#x", the digits and letters up to the terminating ; provide a hexadecimal representation of the character's code point in ISO/IEC 10646. If it begins just with "&#", the digits up to the terminating ; provide a decimal representation of the character's code point.

An entity reference refers to the content of a named entity. References to parsed general entities use ampersand (&) and semicolon (;) as delimiters. Parameter-entity references use percent-sign (%) and semicolon (;) as delimiters.

Entity Reference Reference EntityRef | CharRef EntityRef '&' Name ';' PEReference '%' Name ';' Entity Declared

In a document without any DTD, a document with only an internal DTD subset which contains no parameter entity references, or a document with "standalone='yes'", the Name given in the entity reference must match that in an entity declaration, except that well-formed documents need not declare any of the following entities: amp, lt, gt, apos, quot. The declaration of a parameter entity must precede any reference to it. Similarly, the declaration of a general entity must precede any reference to it which appears in a default value in an attribute-list declaration.

Note that if entities are declared in the external subset or in external parameter entities, a non-validating processor is not obligated to read and process their declarations; for such documents, the rule that an entity must be declared is a well-formedness constraint only if standalone='yes'.

Entity Declared

In a document with an external subset or external parameter entities with "standalone='no'", the Name given in the entity reference must match that in an entity declaration. For interoperability, valid documents should declare the entities amp, lt, gt, apos, quot, in the form specified in . The declaration of a parameter entity must precede any reference to it. Similarly, the declaration of a general entity must precede any reference to it which appears in a default value in an attribute-list declaration.

Parsed Entity

An entity reference must not contain the name of an unparsed entity. Unparsed entities may be referred to only in attribute values declared to be of type ENTITY or ENTITIES.

No Recursion

A parsed entity must not contain a recursive reference to itself, either directly or indirectly.

In DTD

Parameter-entity references may only appear in the DTD.

Examples of character and entity references: Type <key>less-than</key> (&#x3C;) to save options. This document was prepared on &docdate; and is classified &security-level;.

Example of a parameter-entity reference: %ISOLat2;]]>

Entity Declarations

Entities are declared thus: Entity Declaration EntityDecl GEDecl | PEDecl GEDecl '<!ENTITY' S Name S EntityDef S? '>' PEDecl '<!ENTITY' S '%' S Name S PEDef S? '>' EntityDef EntityValue | (ExternalID NDataDecl?) PEDef EntityValue | ExternalID The Name identifies the entity in an entity reference or, in the case of an unparsed entity, in the value of an ENTITY or ENTITIES attribute. If the same entity is declared more than once, the first declaration encountered is binding; at user option, an XML processor may issue a warning if entities are declared multiple times.

Internal Entities

If the entity definition is an EntityValue, the defined entity is called an internal entity. There is no separate physical storage object, and the content of the entity is given in the declaration. Note that some processing of entity and character references in the literal entity value may be required to produce the correct replacement text: see .

An internal entity is a parsed entity.

Example of an internal entity declaration: <!ENTITY Pub-Status "This is a pre-release of the specification.">

External Entities

If the entity is not internal, it is an external entity, declared as follows: External Entity Declaration ExternalID 'SYSTEM' S SystemLiteral | 'PUBLIC' S PubidLiteral S SystemLiteral NDataDecl S 'NDATA' S Name If the NDataDecl is present, this is a general unparsed entity; otherwise it is a parsed entity.

Notation Declared

The Name must match the declared name of a notation.

The SystemLiteral is called the entity's system identifier. It is a URI, which may be used to retrieve the entity. Note that the hash mark (#) and fragment identifier frequently used with URIs are not, formally, part of the URI itself; an XML processor may signal an error if a fragment identifier is given as part of a system identifier. Unless otherwise provided by information outside the scope of this specification (e.g. a special XML element type defined by a particular DTD, or a processing instruction defined by a particular application specification), relative URIs are relative to the location of the resource within which the entity declaration occurs. A URI might thus be relative to the document entity, to the entity containing the external DTD subset, or to some other external parameter entity.

An XML processor should handle a non-ASCII character in a URI by representing the character in UTF-8 as one or more bytes, and then escaping these bytes with the URI escaping mechanism (i.e., by converting each byte to %HH, where HH is the hexadecimal notation of the byte value).

In addition to a system identifier, an external identifier may include a public identifier. An XML processor attempting to retrieve the entity's content may use the public identifier to try to generate an alternative URI. If the processor is unable to do so, it must use the URI specified in the system literal. Before a match is attempted, all strings of white space in the public identifier must be normalized to single space characters (#x20), and leading and trailing white space must be removed.

Examples of external entity declarations: <!ENTITY open-hatch SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml"> <!ENTITY open-hatch PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" "http://www.textuality.com/boilerplate/OpenHatch.xml"> <!ENTITY hatch-pic SYSTEM "../grafix/OpenHatch.gif" NDATA gif >

Parsed Entities The Text Declaration

External parsed entities may each begin with a text declaration. Text Declaration TextDecl '<?xml' VersionInfo? EncodingDecl S? '?>'

The text declaration must be provided literally, not by reference to a parsed entity. No text declaration may appear at any position other than the beginning of an external parsed entity.

Well-Formed Parsed Entities

The document entity is well-formed if it matches the production labeled document. An external general parsed entity is well-formed if it matches the production labeled extParsedEnt. An external parameter entity is well-formed if it matches the production labeled extPE. Well-Formed External Parsed Entity extParsedEnt TextDecl? content extPE TextDecl? extSubsetDecl An internal general parsed entity is well-formed if its replacement text matches the production labeled content. All internal parameter entities are well-formed by definition.

A consequence of well-formedness in entities is that the logical and physical structures in an XML document are properly nested; no start-tag, end-tag, empty-element tag, element, comment, processing instruction, character reference, or entity reference can begin in one entity and end in another.

Character Encoding in Entities

Each external parsed entity in an XML document may use a different encoding for its characters. All XML processors must be able to read entities in either UTF-8 or UTF-16.

Entities encoded in UTF-16 must begin with the Byte Order Mark described by ISO/IEC 10646 Annex E and Unicode Appendix B (the ZERO WIDTH NO-BREAK SPACE character, #xFEFF). This is an encoding signature, not part of either the markup or the character data of the XML document. XML processors must be able to use this character to differentiate between UTF-8 and UTF-16 encoded documents.

Although an XML processor is required to read only entities in the UTF-8 and UTF-16 encodings, it is recognized that other encodings are used around the world, and it may be desired for XML processors to read entities that use them. Parsed entities which are stored in an encoding other than UTF-8 or UTF-16 must begin with a text declaration containing an encoding declaration: Encoding Declaration EncodingDecl S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" ) EncName [A-Za-z] ([A-Za-z0-9._] | '-')* Encoding name contains only Latin characters In the document entity, the encoding declaration is part of the XML declaration. The EncName is the name of the encoding used.

In an encoding declaration, the values "UTF-8", "UTF-16", "ISO-10646-UCS-2", and "ISO-10646-UCS-4" should be used for the various encodings and transformations of Unicode / ISO/IEC 10646, the values "ISO-8859-1", "ISO-8859-2", ... "ISO-8859-9" should be used for the parts of ISO 8859, and the values "ISO-2022-JP", "Shift_JIS", and "EUC-JP" should be used for the various encoded forms of JIS X-0208-1997. XML processors may recognize other encodings; it is recommended that character encodings registered (as charsets) with the Internet Assigned Numbers Authority , other than those just listed, should be referred to using their registered names. Note that these registered names are defined to be case-insensitive, so processors wishing to match against them should do so in a case-insensitive way.

In the absence of information provided by an external transport protocol (e.g. HTTP or MIME), it is an error for an entity including an encoding declaration to be presented to the XML processor in an encoding other than that named in the declaration, for an encoding declaration to occur other than at the beginning of an external entity, or for an entity which begins with neither a Byte Order Mark nor an encoding declaration to use an encoding other than UTF-8. Note that since ASCII is a subset of UTF-8, ordinary ASCII entities do not strictly need an encoding declaration.

It is a fatal error when an XML processor encounters an entity with an encoding that it is unable to process.

Examples of encoding declarations: <?xml encoding='UTF-8'?> <?xml encoding='EUC-JP'?>

XML Processor Treatment of Entities and References

The table below summarizes the contexts in which character references, entity references, and invocations of unparsed entities might appear and the required behavior of an XML processor in each case. The labels in the leftmost column describe the recognition context:

as a reference anywhere after the start-tag and before the end-tag of an element; corresponds to the nonterminal content.

as a reference within either the value of an attribute in a start-tag, or a default value in an attribute declaration; corresponds to the nonterminal AttValue.

as a Name, not a reference, appearing either as the value of an attribute which has been declared as type ENTITY, or as one of the space-separated tokens in the value of an attribute which has been declared as type ENTITIES.

as a reference within a parameter or internal entity's literal entity value in the entity's declaration; corresponds to the nonterminal EntityValue.

as a reference within either the internal or external subsets of the DTD, but outside of an EntityValue or AttValue.

Entity Type Character Parameter Internal General External Parsed General Unparsed Reference in Content Not recognized Included Included if validating Forbidden Included Reference in Attribute Value Not recognized Included in literal Forbidden Forbidden Included Occurs as Attribute Value Not recognized Forbidden Forbidden Notify Not recognized Reference in EntityValue Included in literal Bypassed Bypassed Forbidden Included Reference in DTD Included as PE Forbidden Forbidden Forbidden Forbidden Not Recognized

Outside the DTD, the % character has no special significance; thus, what would be parameter entity references in the DTD are not recognized as markup in content. Similarly, the names of unparsed entities are not recognized except when they appear in the value of an appropriately declared attribute.

Included

An entity is included when its replacement text is retrieved and processed, in place of the reference itself, as though it were part of the document at the location the reference was recognized. The replacement text may contain both character data and (except for parameter entities) markup, which must be recognized in the usual way, except that the replacement text of entities used to escape markup delimiters (the entities amp, lt, gt, apos, quot) is always treated as data. (The string "AT&amp;T;" expands to "AT&T;" and the remaining ampersand is not recognized as an entity-reference delimiter.) A character reference is included when the indicated character is processed in place of the reference itself.

Included If Validating

When an XML processor recognizes a reference to a parsed entity, in order to validate the document, the processor must include its replacement text. If the entity is external, and the processor is not attempting to validate the XML document, the processor may, but need not, include the entity's replacement text. If a non-validating parser does not include the replacement text, it must inform the application that it recognized, but did not read, the entity.

This rule is based on the recognition that the automatic inclusion provided by the SGML and XML entity mechanism, primarily designed to support modularity in authoring, is not necessarily appropriate for other applications, in particular document browsing. Browsers, for example, when encountering an external parsed entity reference, might choose to provide a visual indication of the entity's presence and retrieve it for display only on demand.

Forbidden

The following are forbidden, and constitute fatal errors:

the appearance of a reference to an unparsed entity.

the appearance of any character or general-entity reference in the DTD except within an EntityValue or AttValue.

a reference to an external entity in an attribute value.

Included in Literal

When an entity reference appears in an attribute value, or a parameter entity reference appears in a literal entity value, its replacement text is processed in place of the reference itself as though it were part of the document at the location the reference was recognized, except that a single or double quote character in the replacement text is always treated as a normal data character and will not terminate the literal. For example, this is well-formed: ]]> while this is not: <!ENTITY EndAttr "27'" > <element attribute='a-&EndAttr;>

Notify

When the name of an unparsed entity appears as a token in the value of an attribute of declared type ENTITY or ENTITIES, a validating processor must inform the application of the system and public (if any) identifiers for both the entity and its associated notation.

Bypassed

When a general entity reference appears in the EntityValue in an entity declaration, it is bypassed and left as is.

Included as PE

Just as with external parsed entities, parameter entities need only be included if validating. When a parameter-entity reference is recognized in the DTD and included, its replacement text is enlarged by the attachment of one leading and one following space (#x20) character; the intent is to constrain the replacement text of parameter entities to contain an integral number of grammatical tokens in the DTD.

Construction of Internal Entity Replacement Text

In discussing the treatment of internal entities, it is useful to distinguish two forms of the entity's value. The literal entity value is the quoted string actually present in the entity declaration, corresponding to the non-terminal EntityValue. The replacement text is the content of the entity, after replacement of character references and parameter-entity references.

The literal entity value as given in an internal entity declaration (EntityValue) may contain character, parameter-entity, and general-entity references. Such references must be contained entirely within the literal entity value. The actual replacement text that is included as described above must contain the replacement text of any parameter entities referred to, and must contain the character referred to, in place of any character references in the literal entity value; however, general-entity references must be left as-is, unexpanded. For example, given the following declarations: ]]> then the replacement text for the entity "book" is: La Peste: Albert Camus, © 1947 Éditions Gallimard. &rights; The general-entity reference "&rights;" would be expanded should the reference "&book;" appear in the document's content or an attribute value.

These simple rules may have complex interactions; for a detailed discussion of a difficult example, see .

Predefined Entities

Entity and character references can both be used to escape the left angle bracket, ampersand, and other delimiters. A set of general entities (amp, lt, gt, apos, quot) is specified for this purpose. Numeric character references may also be used; they are expanded immediately when recognized and must be treated as character data, so the numeric character references "&#60;" and "&#38;" may be used to escape < and & when they occur in character data.

All XML processors must recognize these entities whether they are declared or not. For interoperability, valid XML documents should declare these entities, like any others, before using them. If the entities in question are declared, they must be declared as internal entities whose replacement text is the single character being escaped or a character reference to that character, as shown below. ]]> Note that the < and & characters in the declarations of "lt" and "amp" are doubly escaped to meet the requirement that entity replacement be well-formed.

Notation Declarations

Notations identify by name the format of unparsed entities, the format of elements which bear a notation attribute, or the application to which a processing instruction is addressed.

Notation declarations provide a name for the notation, for use in entity and attribute-list declarations and in attribute specifications, and an external identifier for the notation which may allow an XML processor or its client application to locate a helper application capable of processing data in the given notation. Notation Declarations NotationDecl '<!NOTATION' S Name S (ExternalID | PublicID) S? '>' PublicID 'PUBLIC' S PubidLiteral

XML processors must provide applications with the name and external identifier(s) of any notation declared and referred to in an attribute value, attribute definition, or entity declaration. They may additionally resolve the external identifier into the system identifier, file name, or other information needed to allow the application to call a processor for data in the notation described. (It is not an error, however, for XML documents to declare and refer to notations for which notation-specific applications are not available on the system where the XML processor or application is running.)

Document Entity

The document entity serves as the root of the entity tree and a starting-point for an XML processor. This specification does not specify how the document entity is to be located by an XML processor; unlike other entities, the document entity has no name and might well appear on a processor input stream without any identification at all.

Conformance Validating and Non-Validating Processors

Conforming XML processors fall into two classes: validating and non-validating.

Validating and non-validating processors alike must report violations of this specification's well-formedness constraints in the content of the document entity and any other parsed entities that they read.

Validating processors must report violations of the constraints expressed by the declarations in the DTD, and failures to fulfill the validity constraints given in this specification. To accomplish this, validating XML processors must read and process the entire DTD and all external parsed entities referenced in the document.

Non-validating processors are required to check only the document entity, including the entire internal DTD subset, for well-formedness. While they are not required to check the document for validity, they are required to process all the declarations they read in the internal DTD subset and in any parameter entity that they read, up to the first reference to a parameter entity that they do not read; that is to say, they must use the information in those declarations to normalize attribute values, include the replacement text of internal entities, and supply default attribute values. They must not process entity declarations or attribute-list declarations encountered after a reference to a parameter entity that is not read, since the entity may have contained overriding declarations.

Using XML Processors

The behavior of a validating XML processor is highly predictable; it must read every piece of a document and report all well-formedness and validity violations. Less is required of a non-validating processor; it need not read any part of the document other than the document entity. This has two effects that may be important to users of XML processors:

Certain well-formedness errors, specifically those that require reading external entities, may not be detected by a non-validating processor. Examples include the constraints entitled Entity Declared, Parsed Entity, and No Recursion, as well as some of the cases described as forbidden in .

The information passed from the processor to the application may vary, depending on whether the processor reads parameter and external entities. For example, a non-validating processor may not normalize attribute values, include the replacement text of internal entities, or supply default attribute values, where doing so depends on having read declarations in external or parameter entities.

For maximum reliability in interoperating between different XML processors, applications which use non-validating processors should not rely on any behaviors not required of such processors. Applications which require facilities such as the use of default attributes or internal entities which are declared in external entities should use validating XML processors.

Notation

The formal grammar of XML is given in this specification using a simple Extended Backus-Naur Form (EBNF) notation. Each rule in the grammar defines one symbol, in the form symbol ::= expression

Symbols are written with an initial capital letter if they are defined by a regular expression, or with an initial lower case letter otherwise. Literal strings are quoted.

Within the expression on the right-hand side of a rule, the following expressions are used to match strings of one or more characters:

where N is a hexadecimal integer, the expression matches the character in ISO/IEC 10646 whose canonical (UCS-4) code value, when interpreted as an unsigned binary number, has the value indicated. The number of leading zeros in the #xN form is insignificant; the number of leading zeros in the corresponding code value is governed by the character encoding in use and is not significant for XML.

matches any character with a value in the range(s) indicated (inclusive).

matches any character with a value outside the range indicated.

matches any character with a value not among the characters given.

matches a literal string matching that given inside the double quotes.

matches a literal string matching that given inside the single quotes.

These symbols may be combined to match more complex patterns as follows, where A and B represent simple expressions:

expression is treated as a unit and may be combined as described in this list.

matches A or nothing; optional A.

matches A followed by B.

matches A or B but not both.

matches any string that matches A but does not match B.

matches one or more occurrences of A.

matches zero or more occurrences of A.

Other notations used in the productions are:

comment.

well-formedness constraint; this identifies by name a constraint on well-formed documents associated with a production.

validity constraint; this identifies by name a constraint on valid documents associated with a production.

References Normative References (Internet Assigned Numbers Authority) Official Names for Character Sets, ed. Keld Simonsen et al. See ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets. IETF (Internet Engineering Task Force). RFC 1766: Tags for the Identification of Languages, ed. H. Alvestrand. 1995. (International Organization for Standardization). ISO 639:1988 (E). Code for the representation of names of languages. [Geneva]: International Organization for Standardization, 1988. (International Organization for Standardization). ISO 3166-1:1997 (E). Codes for the representation of names of countries and their subdivisions -- Part 1: Country codes [Geneva]: International Organization for Standardization, 1997. ISO (International Organization for Standardization). ISO/IEC 10646-1993 (E). Information technology -- Universal Multiple-Octet Coded Character Set (UCS) -- Part 1: Architecture and Basic Multilingual Plane. [Geneva]: International Organization for Standardization, 1993 (plus amendments AM 1 through AM 7). The Unicode Consortium. The Unicode Standard, Version 2.0. Reading, Mass.: Addison-Wesley Developers Press, 1996. Other References Aho, Alfred V., Ravi Sethi, and Jeffrey D. Ullman. Compilers: Principles, Techniques, and Tools. Reading: Addison-Wesley, 1986, rpt. corr. 1988. Berners-Lee, T., R. Fielding, and L. Masinter. Uniform Resource Identifiers (URI): Generic Syntax and Semantics. 1997. (Work in progress; see updates to RFC1738.) Brggemann-Klein, Anne. Regular Expressions into Finite Automata. Extended abstract in I. Simon, Hrsg., LATIN 1992, S. 97-98. Springer-Verlag, Berlin 1992. Full Version in Theoretical Computer Science 120: 197-213, 1993. Brggemann-Klein, Anne, and Derick Wood. Deterministic Regular Languages. Universitt Freiburg, Institut fr Informatik, Bericht 38, Oktober 1991. James Clark. Comparison of SGML and XML. See http://www.w3.org/TR/NOTE-sgml-xml-971215. IETF (Internet Engineering Task Force). RFC 1738: Uniform Resource Locators (URL), ed. T. Berners-Lee, L. Masinter, M. McCahill. 1994. IETF (Internet Engineering Task Force). RFC 1808: Relative Uniform Resource Locators, ed. R. Fielding. 1995. IETF (Internet Engineering Task Force). RFC 2141: URN Syntax, ed. R. Moats. 1997. ISO (International Organization for Standardization). ISO 8879:1986(E). Information processing -- Text and Office Systems -- Standard Generalized Markup Language (SGML). First edition -- 1986-10-15. [Geneva]: International Organization for Standardization, 1986. ISO (International Organization for Standardization). ISO/IEC 10744-1992 (E). Information technology -- Hypermedia/Time-based Structuring Language (HyTime). [Geneva]: International Organization for Standardization, 1992. Extended Facilities Annexe. [Geneva]: International Organization for Standardization, 1996. Character Classes

Following the characteristics defined in the Unicode standard, characters are classed as base characters (among others, these contain the alphabetic characters of the Latin alphabet, without diacritics), ideographic characters, and combining characters (among others, this class contains most diacritics); these classes combine to form the class of letters. Digits and extenders are also distinguished. Characters Letter BaseChar | Ideographic BaseChar [#x0041-#x005A] | [#x0061-#x007A] | [#x00C0-#x00D6] | [#x00D8-#x00F6] | [#x00F8-#x00FF] | [#x0100-#x0131] | [#x0134-#x013E] | [#x0141-#x0148] | [#x014A-#x017E] | [#x0180-#x01C3] | [#x01CD-#x01F0] | [#x01F4-#x01F5] | [#x01FA-#x0217] | [#x0250-#x02A8] | [#x02BB-#x02C1] | #x0386 | [#x0388-#x038A] | #x038C | [#x038E-#x03A1] | [#x03A3-#x03CE] | [#x03D0-#x03D6] | #x03DA | #x03DC | #x03DE | #x03E0 | [#x03E2-#x03F3] | [#x0401-#x040C] | [#x040E-#x044F] | [#x0451-#x045C] | [#x045E-#x0481] | [#x0490-#x04C4] | [#x04C7-#x04C8] | [#x04CB-#x04CC] | [#x04D0-#x04EB] | [#x04EE-#x04F5] | [#x04F8-#x04F9] | [#x0531-#x0556] | #x0559 | [#x0561-#x0586] | [#x05D0-#x05EA] | [#x05F0-#x05F2] | [#x0621-#x063A] | [#x0641-#x064A] | [#x0671-#x06B7] | [#x06BA-#x06BE] | [#x06C0-#x06CE] | [#x06D0-#x06D3] | #x06D5 | [#x06E5-#x06E6] | [#x0905-#x0939] | #x093D | [#x0958-#x0961] | [#x0985-#x098C] | [#x098F-#x0990] | [#x0993-#x09A8] | [#x09AA-#x09B0] | #x09B2 | [#x09B6-#x09B9] | [#x09DC-#x09DD] | [#x09DF-#x09E1] | [#x09F0-#x09F1] | [#x0A05-#x0A0A] | [#x0A0F-#x0A10] | [#x0A13-#x0A28] | [#x0A2A-#x0A30] | [#x0A32-#x0A33] | [#x0A35-#x0A36] | [#x0A38-#x0A39] | [#x0A59-#x0A5C] | #x0A5E | [#x0A72-#x0A74] | [#x0A85-#x0A8B] | #x0A8D | [#x0A8F-#x0A91] | [#x0A93-#x0AA8] | [#x0AAA-#x0AB0] | [#x0AB2-#x0AB3] | [#x0AB5-#x0AB9] | #x0ABD | #x0AE0 | [#x0B05-#x0B0C] | [#x0B0F-#x0B10] | [#x0B13-#x0B28] | [#x0B2A-#x0B30] | [#x0B32-#x0B33] | [#x0B36-#x0B39] | #x0B3D | [#x0B5C-#x0B5D] | [#x0B5F-#x0B61] | [#x0B85-#x0B8A] | [#x0B8E-#x0B90] | [#x0B92-#x0B95] | [#x0B99-#x0B9A] | #x0B9C | [#x0B9E-#x0B9F] | [#x0BA3-#x0BA4] | [#x0BA8-#x0BAA] | [#x0BAE-#x0BB5] | [#x0BB7-#x0BB9] | [#x0C05-#x0C0C] | [#x0C0E-#x0C10] | [#x0C12-#x0C28] | [#x0C2A-#x0C33] | [#x0C35-#x0C39] | [#x0C60-#x0C61] | [#x0C85-#x0C8C] | [#x0C8E-#x0C90] | [#x0C92-#x0CA8] | [#x0CAA-#x0CB3] | [#x0CB5-#x0CB9] | #x0CDE | [#x0CE0-#x0CE1] | [#x0D05-#x0D0C] | [#x0D0E-#x0D10] | [#x0D12-#x0D28] | [#x0D2A-#x0D39] | [#x0D60-#x0D61] | [#x0E01-#x0E2E] | #x0E30 | [#x0E32-#x0E33] | [#x0E40-#x0E45] | [#x0E81-#x0E82] | #x0E84 | [#x0E87-#x0E88] | #x0E8A | #x0E8D | [#x0E94-#x0E97] | [#x0E99-#x0E9F] | [#x0EA1-#x0EA3] | #x0EA5 | #x0EA7 | [#x0EAA-#x0EAB] | [#x0EAD-#x0EAE] | #x0EB0 | [#x0EB2-#x0EB3] | #x0EBD | [#x0EC0-#x0EC4] | [#x0F40-#x0F47] | [#x0F49-#x0F69] | [#x10A0-#x10C5] | [#x10D0-#x10F6] | #x1100 | [#x1102-#x1103] | [#x1105-#x1107] | #x1109 | [#x110B-#x110C] | [#x110E-#x1112] | #x113C | #x113E | #x1140 | #x114C | #x114E | #x1150 | [#x1154-#x1155] | #x1159 | [#x115F-#x1161] | #x1163 | #x1165 | #x1167 | #x1169 | [#x116D-#x116E] | [#x1172-#x1173] | #x1175 | #x119E | #x11A8 | #x11AB | [#x11AE-#x11AF] | [#x11B7-#x11B8] | #x11BA | [#x11BC-#x11C2] | #x11EB | #x11F0 | #x11F9 | [#x1E00-#x1E9B] | [#x1EA0-#x1EF9] | [#x1F00-#x1F15] | [#x1F18-#x1F1D] | [#x1F20-#x1F45] | [#x1F48-#x1F4D] | [#x1F50-#x1F57] | #x1F59 | #x1F5B | #x1F5D | [#x1F5F-#x1F7D] | [#x1F80-#x1FB4] | [#x1FB6-#x1FBC] | #x1FBE | [#x1FC2-#x1FC4] | [#x1FC6-#x1FCC] | [#x1FD0-#x1FD3] | [#x1FD6-#x1FDB] | [#x1FE0-#x1FEC] | [#x1FF2-#x1FF4] | [#x1FF6-#x1FFC] | #x2126 | [#x212A-#x212B] | #x212E | [#x2180-#x2182] | [#x3041-#x3094] | [#x30A1-#x30FA] | [#x3105-#x312C] | [#xAC00-#xD7A3] Ideographic [#x4E00-#x9FA5] | #x3007 | [#x3021-#x3029] CombiningChar [#x0300-#x0345] | [#x0360-#x0361] | [#x0483-#x0486] | [#x0591-#x05A1] | [#x05A3-#x05B9] | [#x05BB-#x05BD] | #x05BF | [#x05C1-#x05C2] | #x05C4 | [#x064B-#x0652] | #x0670 | [#x06D6-#x06DC] | [#x06DD-#x06DF] | [#x06E0-#x06E4] | [#x06E7-#x06E8] | [#x06EA-#x06ED] | [#x0901-#x0903] | #x093C | [#x093E-#x094C] | #x094D | [#x0951-#x0954] | [#x0962-#x0963] | [#x0981-#x0983] | #x09BC | #x09BE | #x09BF | [#x09C0-#x09C4] | [#x09C7-#x09C8] | [#x09CB-#x09CD] | #x09D7 | [#x09E2-#x09E3] | #x0A02 | #x0A3C | #x0A3E | #x0A3F | [#x0A40-#x0A42] | [#x0A47-#x0A48] | [#x0A4B-#x0A4D] | [#x0A70-#x0A71] | [#x0A81-#x0A83] | #x0ABC | [#x0ABE-#x0AC5] | [#x0AC7-#x0AC9] | [#x0ACB-#x0ACD] | [#x0B01-#x0B03] | #x0B3C | [#x0B3E-#x0B43] | [#x0B47-#x0B48] | [#x0B4B-#x0B4D] | [#x0B56-#x0B57] | [#x0B82-#x0B83] | [#x0BBE-#x0BC2] | [#x0BC6-#x0BC8] | [#x0BCA-#x0BCD] | #x0BD7 | [#x0C01-#x0C03] | [#x0C3E-#x0C44] | [#x0C46-#x0C48] | [#x0C4A-#x0C4D] | [#x0C55-#x0C56] | [#x0C82-#x0C83] | [#x0CBE-#x0CC4] | [#x0CC6-#x0CC8] | [#x0CCA-#x0CCD] | [#x0CD5-#x0CD6] | [#x0D02-#x0D03] | [#x0D3E-#x0D43] | [#x0D46-#x0D48] | [#x0D4A-#x0D4D] | #x0D57 | #x0E31 | [#x0E34-#x0E3A] | [#x0E47-#x0E4E] | #x0EB1 | [#x0EB4-#x0EB9] | [#x0EBB-#x0EBC] | [#x0EC8-#x0ECD] | [#x0F18-#x0F19] | #x0F35 | #x0F37 | #x0F39 | #x0F3E | #x0F3F | [#x0F71-#x0F84] | [#x0F86-#x0F8B] | [#x0F90-#x0F95] | #x0F97 | [#x0F99-#x0FAD] | [#x0FB1-#x0FB7] | #x0FB9 | [#x20D0-#x20DC] | #x20E1 | [#x302A-#x302F] | #x3099 | #x309A Digit [#x0030-#x0039] | [#x0660-#x0669] | [#x06F0-#x06F9] | [#x0966-#x096F] | [#x09E6-#x09EF] | [#x0A66-#x0A6F] | [#x0AE6-#x0AEF] | [#x0B66-#x0B6F] | [#x0BE7-#x0BEF] | [#x0C66-#x0C6F] | [#x0CE6-#x0CEF] | [#x0D66-#x0D6F] | [#x0E50-#x0E59] | [#x0ED0-#x0ED9] | [#x0F20-#x0F29] Extender #x00B7 | #x02D0 | #x02D1 | #x0387 | #x0640 | #x0E46 | #x0EC6 | #x3005 | [#x3031-#x3035] | [#x309D-#x309E] | [#x30FC-#x30FE]

The character classes defined here can be derived from the Unicode character database as follows:

Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.

Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.

Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.

Characters which have a font or compatibility decomposition (i.e. those with a "compatibility formatting tag" in field 5 of the database -- marked by field 5 beginning with a "<") are not allowed.

The following characters are treated as name-start characters rather than name characters, because the property file classifies them as Alphabetic: [#x02BB-#x02C1], #x0559, #x06E5, #x06E6.

Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).

Character #x00B7 is classified as an extender, because the property list so identifies it.

Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.

Characters ':' and '_' are allowed as name-start characters.

Characters '-' and '.' are allowed as name characters.

XML and SGML

XML is designed to be a subset of SGML, in that every valid XML document should also be a conformant SGML document. For a detailed comparison of the additional restrictions that XML places on documents beyond those of SGML, see .

Expansion of Entity and Character References

This appendix contains some examples illustrating the sequence of entity- and character-reference recognition and expansion, as specified in .

If the DTD contains the declaration An ampersand (&#38;) may be escaped numerically (&#38;#38;) or with a general entity (&amp;).

" > ]]> then the XML processor will recognize the character references when it parses the entity declaration, and resolve them before storing the following string as the value of the entity "example": An ampersand (&) may be escaped numerically (&#38;) or with a general entity (&amp;).

]]>
A reference in the document to "&example;" will cause the text to be reparsed, at which time the start- and end-tags of the "p" element will be recognized and the three references will be recognized and expanded, resulting in a "p" element with the following content (all data, no delimiters or markup):

A more complex example will illustrate the rules and their effects fully. In the following example, the line numbers are solely for reference. 2 4 5 ' > 6 %xx; 7 ]> 8 This sample shows a &tricky; method. ]]> This produces the following:

in line 4, the reference to character 37 is expanded immediately, and the parameter entity "xx" is stored in the symbol table with the value "%zz;". Since the replacement text is not rescanned, the reference to parameter entity "zz" is not recognized. (And it would be an error if it were, since "zz" is not yet declared.)

in line 5, the character reference "&#60;" is expanded immediately and the parameter entity "zz" is stored with the replacement text "<!ENTITY tricky "error-prone" >", which is a well-formed entity declaration.

in line 6, the reference to "xx" is recognized, and the replacement text of "xx" (namely "%zz;") is parsed. The reference to "zz" is recognized in its turn, and its replacement text ("<!ENTITY tricky "error-prone" >") is parsed. The general entity "tricky" has now been declared, with the replacement text "error-prone".

in line 8, the reference to the general entity "tricky" is recognized, and it is expanded, so the full content of the "test" element is the self-describing (and ungrammatical) string This sample shows a error-prone method.

Deterministic Content Models

For compatibility, it is required that content models in element type declarations be deterministic.

SGML requires deterministic content models (it calls them "unambiguous"); XML processors built using SGML systems may flag non-deterministic content models as errors.

For example, the content model ((b, c) | (b, d)) is non-deterministic, because given an initial b the parser cannot know which b in the model is being matched without looking ahead to see which element follows the b. In this case, the two references to b can be collapsed into a single reference, making the model read (b, (c | d)). An initial b now clearly matches only a single name in the content model. The parser doesn't need to look ahead to see what follows; either c or d would be accepted.

More formally: a finite state automaton may be constructed from the content model using the standard algorithms, e.g. algorithm 3.5 in section 3.9 of Aho, Sethi, and Ullman . In many such algorithms, a follow set is constructed for each position in the regular expression (i.e., each leaf node in the syntax tree for the regular expression); if any position has a follow set in which more than one following position is labeled with the same element type name, then the content model is in error and may be reported as an error.

Algorithms exist which allow many but not all non-deterministic content models to be reduced automatically to equivalent deterministic models; see Brggemann-Klein 1991 .

Autodetection of Character Encodings

The XML encoding declaration functions as an internal label on each entity, indicating which character encoding is in use. Before an XML processor can read the internal label, however, it apparently has to know what character encoding is in use--which is what the internal label is trying to indicate. In the general case, this is a hopeless situation. It is not entirely hopeless in XML, however, because XML limits the general case in two ways: each implementation is assumed to support only a finite set of character encodings, and the XML encoding declaration is restricted in position and content in order to make it feasible to autodetect the character encoding in use in each entity in normal cases. Also, in many cases other sources of information are available in addition to the XML data stream itself. Two cases may be distinguished, depending on whether the XML entity is presented to the processor without, or with, any accompanying (external) information. We consider the first case first.

Because each XML entity not in UTF-8 or UTF-16 format must begin with an XML encoding declaration, in which the first characters must be '<?xml', any conforming processor can detect, after two to four octets of input, which of the following cases apply. In reading this list, it may help to know that in UCS-4, '<' is "#x0000003C" and '?' is "#x0000003F", and the Byte Order Mark required of UTF-16 data streams is "#xFEFF".

00 00 00 3C: UCS-4, big-endian machine (1234 order)

3C 00 00 00: UCS-4, little-endian machine (4321 order)

00 00 3C 00: UCS-4, unusual octet order (2143)

00 3C 00 00: UCS-4, unusual octet order (3412)

FE FF: UTF-16, big-endian

FF FE: UTF-16, little-endian

00 3C 00 3F: UTF-16, big-endian, no Byte Order Mark (and thus, strictly speaking, in error)

3C 00 3F 00: UTF-16, little-endian, no Byte Order Mark (and thus, strictly speaking, in error)

3C 3F 78 6D: UTF-8, ISO 646, ASCII, some part of ISO 8859, Shift-JIS, EUC, or any other 7-bit, 8-bit, or mixed-width encoding which ensures that the characters of ASCII have their normal positions, width, and values; the actual encoding declaration must be read to detect which of these applies, but since all of these encodings use the same bit patterns for the ASCII characters, the encoding declaration itself may be read reliably

4C 6F A7 94: EBCDIC (in some flavor; the full encoding declaration must be read to tell which code page is in use)

other: UTF-8 without an encoding declaration, or else the data stream is corrupt, fragmentary, or enclosed in a wrapper of some kind

This level of autodetection is enough to read the XML encoding declaration and parse the character-encoding identifier, which is still necessary to distinguish the individual members of each family of encodings (e.g. to tell UTF-8 from 8859, and the parts of 8859 from each other, or to distinguish the specific EBCDIC code page in use, and so on).

Because the contents of the encoding declaration are restricted to ASCII characters, a processor can reliably read the entire encoding declaration as soon as it has detected which family of encodings is in use. Since in practice, all widely used character encodings fall into one of the categories above, the XML encoding declaration allows reasonably reliable in-band labeling of character encodings, even when external sources of information at the operating-system or transport-protocol level are unreliable.

Once the processor has detected the character encoding in use, it can act appropriately, whether by invoking a separate input routine for each case, or by calling the proper conversion function on each character of input.

Like any self-labeling system, the XML encoding declaration will not work if any software changes the entity's character set or encoding without updating the encoding declaration. Implementors of character-encoding routines should be careful to ensure the accuracy of the internal and external information used to label the entity.

The second possible case occurs when the XML entity is accompanied by encoding information, as in some file systems and some network protocols. When multiple sources of information are available, their relative priority and the preferred method of handling conflict should be specified as part of the higher-level protocol used to deliver XML. Rules for the relative priority of the internal label and the MIME-type label in an external header, for example, should be part of the RFC document defining the text/xml and application/xml MIME types. In the interests of interoperability, however, the following rules are recommended.

If an XML entity is in a file, the Byte-Order Mark and encoding-declaration PI are used (if present) to determine the character encoding. All other heuristics and sources of information are solely for error recovery.

If an XML entity is delivered with a MIME type of text/xml, then the charset parameter on the MIME type determines the character encoding method; all other heuristics and sources of information are solely for error recovery.

If an XML entity is delivered with a MIME type of application/xml, then the Byte-Order Mark and encoding-declaration PI are used (if present) to determine the character encoding. All other heuristics and sources of information are solely for error recovery.

These rules apply only in the absence of protocol-level documentation; in particular, when the MIME types text/xml and application/xml are defined, the recommendations of the relevant RFC will supersede these rules.

W3C XML Working Group

This specification was prepared and approved for publication by the W3C XML Working Group (WG). WG approval of this specification does not necessarily imply that all WG members voted for its approval. The current and former members of the XML WG are:

Jon Bosak, SunChair James ClarkTechnical Lead Tim Bray, Textuality and NetscapeXML Co-editor Jean Paoli, MicrosoftXML Co-editor C. M. Sperberg-McQueen, U. of Ill.XML Co-editor Dan Connolly, W3CW3C Liaison Paula Angerstein, Texcel Steve DeRose, INSO Dave Hollander, HP Eliot Kimber, ISOGEN Eve Maler, ArborText Tom Magliery, NCSA Murray Maloney, Muzmo and Grif Makoto Murata, Fuji Xerox Information Systems Joel Nava, Adobe Conleth O'Connell, Vignette Peter Sharpe, SoftQuad John Tigue, DataChannel
dom4j-1.6.1/xml/web.xml0000644000175000017500000000152510242117776014175 0ustar ebourgebourg snoop SnoopServlet file ViewFile initial 1000 The initial value for the counter snoop /foo/snoop manager director president dom4j-1.6.1/xml/xhtml/0000755000175000017500000000000012133227266014024 5ustar ebourgebourgdom4j-1.6.1/xml/xhtml/xhtml-special.ent0000644000175000017500000001031610242120004017264 0ustar ebourgebourg dom4j-1.6.1/xml/xhtml/xhtml-lat1.ent0000644000175000017500000002762510242120006016522 0ustar ebourgebourg dom4j-1.6.1/xml/xhtml/xhtml1-strict.dtd0000644000175000017500000006657610242120015017247 0ustar ebourgebourg %HTMLlat1; %HTMLsymbol; %HTMLspecial; dom4j-1.6.1/xml/xhtml/xhtml-basic.xml0000644000175000017500000014004110242120006016740 0ustar ebourgebourg XHTML Basic

W3C

XHTML™ Basic

W3C Recommendation 19 December 2000

This version:
http://www.w3.org/TR/2000/REC-xhtml-basic-20001219
(Plain text version, PostScript version, PDF version, ZIP archive, or Gzip'd TAR archive)
Latest version:
http://www.w3.org/TR/xhtml-basic
Previous version:
http://www.w3.org/TR/2000/PR-xhtml-basic-20001103
Editors:
Mark Baker, Sun Microsystems
Masayasu Ishikawa, W3C
Shinichi Matsui, Panasonic
Peter Stark, Ericsson
Ted Wugofski, Openwave Systems
Toshihiko Yamakami, ACCESS Co., Ltd.

Copyright © 1999-2000 W3C® (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.

Abstract

The XHTML Basic document type includes the minimal set of modules required to be an XHTML host language document type, and in addition it includes images, forms, basic tables, and object support. It is designed for Web clients that do not support the full set of XHTML features; for example, Web clients such as mobile phones, PDAs, pagers, and settop boxes. The document type is rich enough for content authoring.

XHTML Basic is designed as a common base that may be extended. For example, an event module that is more generic than the traditional HTML 4 event system could be added or it could be extended by additional modules from XHTML Modularization such as the Scripting Module. The goal of XHTML Basic is to serve as a common language supported by various kinds of user agents.

The document type definition is implemented using XHTML modules as defined in "Modularization of XHTML" [XHTMLMOD].

Status of this Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. The latest status of this document series is maintained at the W3C.

This document has been reviewed by W3C Members and other interested parties and has been endorsed by the Director as a W3C Recommendation. It is a stable document and may be used as reference material or cited as a normative reference from another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web.

This document has been produced by the W3C HTML Working Group (members only) as part of the W3C HTML Activity. It integrates feedback from the WAP Forum and members of the W3C Mobile Access Interest Group (members only). This document will be used by the W3C HTML Working Group and the W3C Mobile Access Interest Group to find a common ground for future markup languages aimed at content for small information appliances.

"Modularization of XHTML" [XHTMLMOD] defines the XHTML modules used in the XHTML Basic document type. At the time of this publication, the Candidate Recommendation review period for "Modularization of XHTML" has closed. Based on that review, the W3C HTML Working Group believes that the definition of modules used in XHTML Basic is stable, and the Working Group does not expect to make changes to "Modularization of XHTML" that would be incompatible with XHTML Basic.

Public discussion of HTML takes place on www-html@w3.org (archive). To subscribe send an email to www-html-request@w3.org with the word subscribe in the subject line.

Please report errors in this document to www-html-editor@w3.org (archive). The list of known errors in this document is available at http://www.w3.org/2000/12/REC-xhtml-basic-20001219-errata.

The English version of this specification is the only normative version. Information about translations of this document is available at http://www.w3.org/MarkUp/translations.

A list of current W3C Recommendations and other technical documents can be found at http://www.w3.org/TR.

Table of Contents

  • 1. Introduction
    • 1.1. XHTML for Small Information Appliances
    • 1.2. Background and Requirements
    • 1.3. Design Rationale
  • 2. Conformance
    • 2.1. Document Conformance
    • 2.2. User Agent Conformance
  • 3. The XHTML Basic Document Type
  • 4. How to Use XHTML Basic
  • 5. Acknowledgements
  • A. References
    • A.1. Normative References
    • A.2. Informative References
  • B. XHTML Basic Document Type Definition
    • B.1. SGML Open Catalog Entry for XHTML Basic
    • B.2. XHTML Basic Driver
    • B.3. XHTML Basic Customizations

1. Introduction

1.1. XHTML for Small Information Appliances

HTML 4 is a powerful language for authoring Web content, but its design does not take into consideration issues pertinent to small devices, including the implementation cost (in power, memory, etc.) of the full feature set. Consumer devices with limited resources cannot generally afford to implement the full feature set of HTML 4. Requiring a full-fledged computer for access to the World Wide Web excludes a large portion of the population from consumer device access of online information and services.

Because there are many ways to subset HTML, there are many almost identical subsets defined by organizations and companies. Without a common base set of features, developing applications for a wide range of Web clients is difficult.

The motivation for XHTML Basic is to provide an XHTML document type that can be shared across communities (e.g. desktop, TV, and mobile phones), and that is rich enough to be used for simple content authoring. New community-wide document types can be defined by extending XHTML Basic in such a way that XHTML Basic documents are in the set of valid documents of the new document type. Thus an XHTML Basic document can be presented on the maximum number of Web clients.

The document type definition for XHTML Basic is implemented based on the XHTML modules defined in Modularization of XHTML [XHTMLMOD].

1.2. Background and Requirements

Information appliances are targeted for particular uses. They support the features they need for the functions they are designed to fulfill. The following are examples of different information appliances:

  • Mobile phones
  • Televisions
  • PDAs
  • Vending machines
  • Pagers
  • Car navigation systems
  • Mobile game machines
  • Digital book readers
  • Smart watches

Existing subsets and variants of HTML for these clients include Compact HTML [CHTML], the Wireless Markup Language [WML], and the "HTML 4.0 Guidelines for Mobile Access" [GUIDELINES]. The common features found in these document types include:

  • Basic text (including headings, paragraphs, and lists)
  • Hyperlinks and links to related documents
  • Basic forms
  • Basic tables
  • Images
  • Meta information

This set of HTML features has been the starting point for the design of XHTML Basic. Since many content developers are familiar with these HTML features, they comprise a useful host language that may be combined with markup modules from other languages according to the methods described in "Modularization of XHTML" [XHTMLMOD]. For example, XHTML Basic may be extended with an event module that is more generic than the traditional HTML 4 event system or it could be extended by additional modules from XHTML Modularization such as the Scripting Module.

It is not the intention of XHTML Basic to limit the functionality of future languages. But since the features in HTML 4 (frames, advanced tables, a fixed set of attribute event handlers, etc.) were developed for a desktop computer type of client, they have proved to be inappropriate for many non-desktop devices. XHTML Basic will be extended and built upon. Extending XHTML from a common and basic set of features, instead of almost identical subsets or the too-large set of functions in HTML 4, will be good for interoperability on the Web, as well as for scalability.

Compared to the rich functionality of HTML 4, XHTML Basic may look like one step back, but in fact, it is two steps forward for clients that do not need what is in HTML 4 and for content developers who get one XHTML subset instead of many.

1.3. Design Rationale

This section explains why certain HTML features are not part of XHTML Basic.

1.3.1. Style Sheets

The style element is not supported. External style sheets are recommended. The link element can be used to include external style sheets. The div and span elements and the class attribute are supported to hook style information onto the structure. Separation between structure and presentation allows user agents to download the style sheets if they support style sheets; user agents that do not support style sheets can ignore the external stylesheet. The media attribute can be used to select the appropriate style sheets. See the section on "Media types" in the HTML 4.01 specification ([HTML4], section 14.2.4) for more details.

1.3.2. Script and Events

The script and noscript elements are not supported. Usually small devices have limited memory and CPU power. Execution of script programs may not be supported. Contents should be readable even if scripts are not executed.

Event handler attributes used to invoke script programs are not supported. Events are device dependent. An incoming-call event is unlikely to happen in a television. A generic event handling mechanism would be more appropriate than hardwiring the event names in the document type definition.

1.3.3. Presentation

Many simple Web clients cannot display fonts other than monospace. Bi-directional text, bold faced font, and other text extension elements are not supported.

It is recommended that style sheets be used to create a presentation that is appropriate for the device.

1.3.4. Forms

Basic XHTML forms ([XHTMLMOD], section 5.5.1) are supported. Since only devices with a local file system can take advantage of file and image input types in forms, they are not included in the basic forms. Also, content developers should keep in mind that users may not be able to input many characters from some devices (e.g. from a mobile phone).

1.3.5. Tables

Basic XHTML tables ([XHTMLMOD], section 5.6.1) are supported, but tables can be difficult to display on small devices. It is recommended that content developers follow the Web Content Accessibility Guidelines 1.0 for creating accessible tables ([WCAG10], Guideline 5). Note that in the Basic Tables Module, nesting of tables is prohibited.

1.3.6. Frames

Frames are not supported. Frames depend on a screen interface and may not be applicable to some small appliances like phones, pagers, and watches.

2. Conformance

This section is normative.

2.1. Document Conformance

A Conforming XHTML Basic document is a document that requires only the facilities described as mandatory in this specification. Such a document must meet all of the following criteria:

  1. The document must conform to the constraints expressed in Appendix B.
  2. The root element of the document must be <html>.
  3. The name of the default namespace on the root element must be the XHTML namespace name, http://www.w3.org/1999/xhtml.
  4. There must be a DOCTYPE declaration in the document prior to the root element. If present, the public identifier included in the DOCTYPE declaration must reference the DTD found in Appendix B using its Formal Public Identifier. The system identifier may be modified appropriately.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.0//EN"
        "http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd">
    
  5. The DTD subset must not be used to override any parameter entities in the DTD.

2.2. User Agent Conformance

The user agent must conform to the "User Agent Conformance" section of the XHTML 1.0 specification ([XHTML1], section 3.2).

3. The XHTML Basic Document Type

This section is normative.

The XHTML Basic document type is defined as a set of XHTML modules. All XHTML modules are defined in the "Modularization of XHTML" specification [XHTMLMOD].

XHTML Basic consists of the following XHTML modules:

Structure Module*
body, head, html, title
Text Module*
abbr, acronym, address, blockquote, br, cite, code, dfn, div, em, h1, h2, h3, h4, h5, h6, kbd, p, pre, q, samp, span, strong, var
Hypertext Module*
a
List Module*
dl, dt, dd, ol, ul, li
Basic Forms Module
form, input, label, select, option, textarea
Basic Tables Module
caption, table, td, th, tr
Image Module
img
Object Module
object, param
Metainformation Module
meta
Link Module
link
Base Module
base

(*) = This module is a required XHTML Host Language module.

An XML 1.0 DTD is available in Appendix B.

NOTE: Since the HTML event handler attributes are not included in XHTML Basic, form controls outside forms may not function as expected by the user.

4. How to Use XHTML Basic

Although XHTML Basic can be used as it is - a simple XHTML language with text, links, and images - the intention of its simple design is for use as a host language. A host language can contain a mix of vocabularies all rolled into one document type. It is natural that XHTML is the host language, since that is what most Web developers are used to.

When markup from other languages is added to XHTML Basic, the resulting document type will be an extension of XHTML Basic. Content developers can develop for XHTML Basic or take advantage of the extensions. The goal of XHTML Basic is to serve as a common language supported by various kinds of user agents.

5. Acknowledgements

This specification was prepared by the W3C HTML Working Group. The members were:

  • Steven Pemberton, CWI (HTML Working Group Chair)
  • Robert Adams, Intel (until November 2000)
  • Murray Altheim, Sun Microsystems
  • Takuya Asada, W3C (until October 2000)
  • Daniel Austin, Mozquito Technologies
  • Mark Baker, Sun Microsystems
  • Wayne Carr, Intel
  • Tantek Çelik, Microsoft
  • Andrew W. Donoho, IBM
  • Herman Elenbaas, Philips Electronics
  • Beth Epperson, Netscape/AOL
  • Masayasu Ishikawa, W3C (HTML Activity Lead)
  • Shin'ichi Matsui, Panasonic
  • Shane McCarron, Applied Testing and Technology
  • Ann Navarro, WebGeek, Inc.
  • Dave Raggett, W3C/Openwave Systems
  • Sebastian Schnitzenbaumer, Mozquito Technologies (until September 2000)
  • Peter Stark, Ericsson
  • Michel Suignard, Microsoft
  • Markku Vartiainen, Openwave Systems
  • Jeremy Wadsworth, Quark Inc.
  • Malte Wedel, Mozquito Technologies
  • Linda Welsh, Intel
  • Ted Wugofski, Openwave Systems

Thanks to Gary Adams (Sun Microsystems), Jonny Axelsson (Metastasis design), Peter Chen (Philips), Dan Connolly (W3C), John Cowan (Reuters), Martin J. Dürst (W3C), Johan Hjelm (Ericsson), Ian Jacobs (W3C), Susan Lesch (W3C), Louis Theran (Nokia), Quinton Zondervan (Lotus), members of the W3C Mobile Access Interest Group, the W3C Synchronized Multimedia Working Group, the W3C WAI Protocols and Formats Working Group, and the WAP Forum, for contributing, reviewing and commenting on this document.

A. References

A.1. Normative References

[HTML4]
"HTML 4.01 Specification", W3C Recommendation, D. Raggett, A. Le Hors, I. Jacobs, eds., 24 December 1999. Available at: http://www.w3.org/TR/1999/REC-html401-19991224
The latest version is available at: http://www.w3.org/TR/html4
[XHTML1]
"XHTML 1.0: The Extensible HyperText Markup Language - A Reformulation of HTML 4 in XML 1.0", W3C Recommendation, Steven Pemberton et al., 26 January 2000. Available at: http://www.w3.org/TR/2000/REC-xhtml1-20000126
The latest version is available at: http://www.w3.org/TR/xhtml1
[XHTMLMOD]
"Modularization of XHTML", W3C Candidate Recommendation, R. Adams, M. Altheim, F. Boumphrey, S. Dooley, S. McCarron, S. Schnitzenbaumer, T. Wugofski, eds., 20 October 2000. Available at: http://www.w3.org/TR/2000/CR-xhtml-modularization-20001020
The latest version is available at: http://www.w3.org/TR/xhtml-modularization
[XML]
"Extensible Markup Language (XML) 1.0 (Second Edition)", W3C Recommendation, T. Bray, J. Paoli, C. M. Sperberg-McQueen, E. Maler, eds., 6 October 2000. Available at: http://www.w3.org/TR/2000/REC-xml-20001006
The latest version is available at: http://www.w3.org/TR/REC-xml

A.2. Informative References

[CHTML]
"Compact HTML for Small Information Appliances", W3C Note, T. Kamada, 9 February 1998. Available at: http://www.w3.org/TR/1998/NOTE-compactHTML-19980209
[GUIDELINES]
"HTML 4.0 Guidelines for Mobile Access, W3C Note, T. Kamada, T. Asada, M. Ishikawa, S. Matsui, eds., 15 March 1999. Available at: http://www.w3.org/TR/1999/NOTE-html40-mobile-19990315
The latest version is available at: http://www.w3.org/TR/NOTE-html40-mobile
[WCAG10]
"Web Content Accessibility Guidelines 1.0", W3C Recommendation, W. Chisholm, G. Vanderheiden, I. Jacobs, eds., 5 May 1999. Available at: http://www.w3.org/TR/1999/WAI-WEBCONTENT-19990505
The latest version is available at: http://www.w3.org/TR/WCAG10
[WML]
"Wireless Markup Language Specification", WAP Forum Ltd. Available from http://www.wapforum.org/what/technical.htm

B. XHTML Basic Document Type Definition

This appendix is normative.

B.1. SGML Open Catalog Entry for XHTML Basic

This section contains the SGML Open Catalog-format definition of the XHTML Basic FPI.

-- .......................................................................... --
-- File catalog  ............................................................ --

--  XHTML Basic Catalog Data File

    Revision:  $Id: xhtml-basic.xml,v 1.2 2002/05/20 08:14:17 jstrachan Exp $ SMI

    See "Entity Management", SGML Open Technical Resolution 9401 for detailed
    information on supplying and using catalog data. This document is available
    from OASIS at URL:

        <http://www.oasis-open.org/html/tr9401.html>
--

-- .......................................................................... --
-- SGML declaration associated with XML  .................................... --

OVERRIDE YES

SGMLDECL "xml1.dcl"

-- :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: --

-- XHTML Basic DTD modular driver file  ..................................... --

PUBLIC "-//W3C//DTD XHTML Basic 1.0//EN"                       "xhtml-basic10.dtd"

-- XHTML Basic framework module ............................................. --

PUBLIC "-//W3C//ENTITIES XHTML Basic 1.0 Document Model 1.0//EN"  "xhtml-basic10-model-1.mod"


-- End of catalog data  ..................................................... --
-- .......................................................................... --

B.2. XHTML Basic Driver

This section contains the driver for the XHTML Basic document type implementation as an XML DTD. It relies upon XHTML module implementations defined in [XHTMLMOD].

<!-- XHTML Basic 1.0 DTD  ...................................................... -->
<!-- file: xhtml-basic10.dtd -->

<!-- XHTML Basic 1.0 DTD

     This is XHTML Basic, a proper subset of XHTML.

     The Extensible HyperText Markup Language (XHTML)
     Copyright 1998-2000 World Wide Web Consortium
        (Massachusetts Institute of Technology, Institut National de
         Recherche en Informatique et en Automatique, Keio University).
         All Rights Reserved.

     Permission to use, copy, modify and distribute the XHTML Basic DTD
     and its accompanying documentation for any purpose and without fee is
     hereby granted in perpetuity, provided that the above copyright notice
     and this paragraph appear in all copies.  The copyright holders make
     no representation about the suitability of the DTD for any purpose.

     It is provided "as is" without expressed or implied warranty.

        Editors:    Murray M. Altheim <mailto:altheim@eng.sun.com>
                    Peter Stark       <mailto:Peter.Stark@ecs.ericsson.se>
        Revision:   $Id: xhtml-basic.xml,v 1.2 2002/05/20 08:14:17 jstrachan Exp $ SMI

-->
<!-- This is the driver file for version 1.0 of the XHTML Basic DTD.

     This DTD is identified by the PUBLIC and SYSTEM identifiers:

     PUBLIC: "-//W3C//DTD XHTML Basic 1.0//EN"
     SYSTEM: "http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd"
-->
<!ENTITY % XHTML.version  "-//W3C//DTD XHTML Basic 1.0//EN" >

<!-- Use this URI to identify the default namespace:

         "http://www.w3.org/1999/xhtml"

     See the Qualified Names module for information
     on the use of namespace prefixes in the DTD.
-->
<!ENTITY % NS.prefixed "IGNORE" >
<!ENTITY % XHTML.prefix  "" >

<!-- Reserved for use with the XLink namespace:
-->
<!ENTITY % XLINK.xmlns "" >
<!ENTITY % XLINK.xmlns.attrib "" >

<!-- For example, if you are using XHTML Basic 1.0 directly, use
     the FPI in the DOCTYPE declaration, with the xmlns attribute
     on the document element to identify the default namespace:

         <?xml version="1.0"?>
         <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.0//EN"
             "http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd" >
         <html xmlns="http://www.w3.org/1999/xhtml"
               xml:lang="en" >
         ...
         </html>
-->

<!-- reserved for future use with document profiles -->
<!ENTITY % XHTML.profile  "" >

<!-- Bidirectional Text features
     This feature-test entity is used to declare elements
     and attributes used for bidirectional text support.
-->
<!ENTITY % XHTML.bidi  "IGNORE" >

<?doc type="doctype" role="title" { XHTML Basic 1.0 } ?>

<!-- :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -->

<!ENTITY % xhtml-events.module   "IGNORE" >
<!ENTITY % xhtml-bdo.module      "%XHTML.bidi;" >

<!ENTITY % xhtml-model.mod
     PUBLIC "-//W3C//ENTITIES XHTML Basic 1.0 Document Model 1.0//EN"
            "xhtml-basic10-model-1.mod" >

<!ENTITY % xhtml-framework.mod
     PUBLIC "-//W3C//ENTITIES XHTML Modular Framework 1.0//EN"
            "xhtml-framework-1.mod" >
%xhtml-framework.mod;

<!ENTITY % pre.content
     "( #PCDATA
      | %InlStruct.class;
      %InlPhras.class;
      %Anchor.class;
      %Inline.extra; )*"
>

<!ENTITY % xhtml-text.mod
     PUBLIC "-//W3C//ELEMENTS XHTML Text 1.0//EN"
            "xhtml-text-1.mod" >
%xhtml-text.mod;

<!ENTITY % xhtml-hypertext.mod
     PUBLIC "-//W3C//ELEMENTS XHTML Hypertext 1.0//EN"
            "xhtml-hypertext-1.mod" >
%xhtml-hypertext.mod;

<!ENTITY % xhtml-list.mod
     PUBLIC "-//W3C//ELEMENTS XHTML Lists 1.0//EN"
            "xhtml-list-1.mod" >
%xhtml-list.mod;

<!-- ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -->

<!-- Image Module  ............................................... -->
<!ENTITY % xhtml-image.module "INCLUDE" >
<![%xhtml-image.module;[
<!ENTITY % xhtml-image.mod
     PUBLIC "-//W3C//ELEMENTS XHTML Images 1.0//EN"
            "xhtml-image-1.mod" >
%xhtml-image.mod;]]>

<!-- Tables Module ............................................... -->
<!ENTITY % xhtml-table.module "INCLUDE" >
<![%xhtml-table.module;[
<!ENTITY % xhtml-table.mod
     PUBLIC "-//W3C//ELEMENTS XHTML Basic Tables 1.0//EN"
            "xhtml-basic-table-1.mod" >
%xhtml-table.mod;]]>

<!-- Forms Module  ............................................... -->
<!ENTITY % xhtml-form.module "INCLUDE" >
<![%xhtml-form.module;[
<!ENTITY % xhtml-form.mod
     PUBLIC "-//W3C//ELEMENTS XHTML Basic Forms 1.0//EN"
            "xhtml-basic-form-1.mod" >
%xhtml-form.mod;]]>

<!-- Link Element Module  ........................................ -->
<!ENTITY % xhtml-link.module "INCLUDE" >
<![%xhtml-link.module;[
<!ENTITY % xhtml-link.mod
     PUBLIC "-//W3C//ELEMENTS XHTML Link Element 1.0//EN"
            "xhtml-link-1.mod" >
%xhtml-link.mod;]]>

<!-- Document Metainformation Module  ............................ -->
<!ENTITY % xhtml-meta.module "INCLUDE" >
<![%xhtml-meta.module;[
<!ENTITY % xhtml-meta.mod
     PUBLIC "-//W3C//ELEMENTS XHTML Metainformation 1.0//EN"
            "xhtml-meta-1.mod" >
%xhtml-meta.mod;]]>

<!-- Base Element Module  ........................................ -->
<!ENTITY % xhtml-base.module "INCLUDE" >
<![%xhtml-base.module;[
<!ENTITY % xhtml-base.mod
     PUBLIC "-//W3C//ELEMENTS XHTML Base Element 1.0//EN"
            "xhtml-base-1.mod" >
%xhtml-base.mod;]]>

<!-- Param Element Module  ....................................... -->
<!ENTITY % xhtml-param.module "INCLUDE" >
<![%xhtml-param.module;[
<!ENTITY % xhtml-param.mod
     PUBLIC "-//W3C//ELEMENTS XHTML Param Element 1.0//EN"
            "xhtml-param-1.mod" >
%xhtml-param.mod;]]>

<!-- Embedded Object Module  ..................................... -->
<!ENTITY % xhtml-object.module "INCLUDE" >
<![%xhtml-object.module;[
<!ENTITY % xhtml-object.mod
     PUBLIC "-//W3C//ELEMENTS XHTML Embedded Object 1.0//EN"
            "xhtml-object-1.mod" >
%xhtml-object.mod;]]>

<!ENTITY % xhtml-struct.mod
     PUBLIC "-//W3C//ELEMENTS XHTML Document Structure 1.0//EN"
            "xhtml-struct-1.mod" >
%xhtml-struct.mod;

<!-- end of XHTML Basic 1.0 DTD  ........................................... -->

B.3. XHTML Basic Customizations

An XHTML Family Document Type (such as XHTML Basic) must define the content model that it uses. This is done through a separate content model module that is instantiated by the XHTML Modular Framework. The content model module and the XHTML Basic Driver (above) work together to customize the module implementations to the document type's specific requirements. The content model module for XHTML Basic is defined below:

<!-- ....................................................................... -->
<!-- XHTML Basic 1.0 Document Model Module  .................................... -->
<!-- file: xhtml-basic10-model-1.mod

     This is XHTML Basic, a proper subset of XHTML.
     Copyright 1998-2000 W3C (MIT, INRIA, Keio), All Rights Reserved.
     Revision: $Id: xhtml-basic.xml,v 1.2 2002/05/20 08:14:17 jstrachan Exp $ SMI

     This DTD module is identified by the PUBLIC and SYSTEM identifiers:

       PUBLIC "-//W3C//ENTITIES XHTML Basic 1.0 Document Model 1.0//EN"
       SYSTEM "http://www.w3.org/TR/xhtml-basic/xhtml-basic10-model-1.mod"

     Revisions:
     (none)
     ....................................................................... -->

<!-- XHTML Basic Document Model

     This module describes the groupings of elements that make up
     common content models for XHTML elements.
-->

<!-- Optional Elements in head  .............. -->

<!ENTITY % HeadOpts.mix
     "( %meta.qname; | %link.qname; | %object.qname; )*" >

<!-- Miscellaneous Elements  ................. -->

<!ENTITY % Misc.class "" >

<!-- Inline Elements  ........................ -->

<!ENTITY % InlStruct.class "%br.qname; | %span.qname;" >

<!ENTITY % InlPhras.class
     "| %em.qname; | %strong.qname; | %dfn.qname; | %code.qname;
      | %samp.qname; | %kbd.qname; | %var.qname; | %cite.qname;
      | %abbr.qname; | %acronym.qname; | %q.qname;" >

<!ENTITY % InlPres.class "" >

<!ENTITY % I18n.class "" >

<!ENTITY % Anchor.class "| %a.qname;" >

<!ENTITY % InlSpecial.class "| %img.qname; | %object.qname;" >

<!ENTITY % InlForm.class
     "| %input.qname; | %select.qname; | %textarea.qname;
      | %label.qname;"
>

<!ENTITY % Inline.extra "" >

<!ENTITY % Inline.class
     "%InlStruct.class;
      %InlPhras.class;
      %Anchor.class;
      %InlSpecial.class;
      %InlForm.class;
      %Inline.extra;"
>

<!ENTITY % InlNoAnchor.class
     "%InlStruct.class;
      %InlPhras.class;
      %InlSpecial.class;
      %InlForm.class;
      %Inline.extra;"
>

<!ENTITY % InlNoAnchor.mix
     "%InlNoAnchor.class;
      %Misc.class;"
>

<!ENTITY % Inline.mix
     "%Inline.class;
      %Misc.class;"
>

<!-- Block Elements  ......................... -->

<!ENTITY % Heading.class
     "%h1.qname; | %h2.qname; | %h3.qname;
      | %h4.qname; | %h5.qname; | %h6.qname;"
>
<!ENTITY % List.class  "%ul.qname; | %ol.qname; | %dl.qname;" >

<!ENTITY % Table.class "| %table.qname;" >

<!ENTITY % Form.class  "| %form.qname;" >

<!ENTITY % BlkStruct.class "%p.qname; | %div.qname;" >

<!ENTITY % BlkPhras.class
     "| %pre.qname; | %blockquote.qname; | %address.qname;"
>

<!ENTITY % BlkPres.class "" >

<!ENTITY % BlkSpecial.class
     "%Table.class;
      %Form.class;"
>

<!ENTITY % Block.extra "" >

<!ENTITY % Block.class
     "%BlkStruct.class;
      %BlkPhras.class;
      %BlkSpecial.class;
      %Block.extra;"
>

<!ENTITY % Block.mix
     "%Heading.class;
      | %List.class;
      | %Block.class;
      %Misc.class;"
>

<!-- All Content Elements  ................... -->

<!-- declares all content except tables
-->
<!ENTITY % FlowNoTable.mix
     "%Heading.class;
      | %List.class;
      | %BlkStruct.class;
      %BlkPhras.class;
      %Form.class;
      %Block.extra;
      | %Inline.class;
      %Misc.class;"
>

<!ENTITY % Flow.mix
     "%Heading.class;
      | %List.class;
      | %Block.class;
      | %Inline.class;
      %Misc.class;"
>

<!-- end of xhtml-basic10-model-1.mod -->
dom4j-1.6.1/xml/xhtml/xhtml-symbol.ent0000644000175000017500000003442310242120005017157 0ustar ebourgebourg dom4j-1.6.1/xml/cookbook.xml0000644000175000017500000010446310242120007015210 0ustar ebourgebourg DOM4J Cookbook TobiasRademacher 0.0.3 01-06-20 tradem Complemted doc for alpha release 0.0.2 01-06-06 tradem Added "Secret of DocumentBuilder" and "Serialization" 0.0.1 01-06-02 tradem Created the document June 2001 This document provides a practical instruction to dom4j. It guides you through by using a lot of examples and is based on dom4j v0.5 Foreword Introducing dom4j Most readers already knowing that dom4j is a object model representing an XML Tree in memory. dom4j offers a easy-to-use API that provides a powerfull set of functions to process, manipulate or navigate with that XML tree. The Designers of dom4j concentrate on a interface-bases pattern-centric architecture in order to provide a resuable high configurable object model. You are able to create your own tree builder's by relying on the existing infrastructure and extending them. Thus simplictiy in resuablity comes with a little bit more effort by understandig the architecture in depth. This document will guide you through dom4j's freatures in a pratical way. It uses a lot of explained examples to achive that. The document is also desinged as a reference so that you don't have to read the entire document right now. The document concentrate on daily work with dom4j and is therefore called cookbook. Readers that needs detailed instruction about Java and XML (JaXP - Java XML processing) should have a look at A quick tour through Java XML Processing using DOM4J. Creation of a XML Object Model using DOM4J Normally it all starts with a set of xml-files or a single xml file that you want to process, manipulate or naviagte through to extract some values necessary in your application. Most Java Open-Source project using XML for deploying or substiute their property fieles in order to get easy readable property data.
Reading XML data Who does dom4j helps you to get the data store in XML? dom4j comes with a set of Builder Classes that parses the xml data and creating a tree like object structure in memory. You can mainpulate or nativate throug that image now. Following example shows how you can read your data using dom4j API. import java.io.File; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; public class DeployFileLoaderSample { /** DOM4J object model representation of a xml document. Note: We use the interface(!) not its implementation */ private Document doc; /** * Loads a document from a file. * * @throw a org.dom4j.DocumentException occurs whenever the buildprocess fails. */ public void parseWithSAX(File aFile) throws DocumentException { SAXReader xmlReader = new SAXReader(); this.doc = xmlReader.read(aFile); } } The above example code should clarify the use of org.dom4j.io.SAXReader to build a complete dom4j-Tree from a given file. The io package of dom4j contains a set of clases for creating and serzializing XML memory images. As read() method is a overloaded method you are able to pass different kind of object that represents a source. java.net.URL - represents a Uniform Ressource Loader or a Uniform Ressource Identifier encasulate in a URL instance java.io.InputStream - a open input stream that transports xml data java.io.Reader - more compartable puls the abiltiy of setting the encoding scheme org.sax.InputSource - a single input source for a XML entity. java.lang.String - a SystemId is a String that contains a URI e.g. a URL to a XML file So we decide to add more flexiblity to our DeployFileLoaderSample and add new method. import java.io.File; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; public class DeployFileLoaderSample { /** DOM4J object model representation of a xml document. Note: We use the interface(!) not its implementation */ private Document doc; /** * Loads a document from a file. * * @param aFile the data source * @throw a org.dom4j.DocumentExcepiton occurs whenever the buildprocess fails. */ public void parseWithSAX(File aFile) throws DocumentException { SAXReader xmlReader = new SAXReader(); this.doc = xmlReader.read(aFile); } /** * Loads a document from a file. * * @param aURL the data source * @throw a org.dom4j.DocumentExcepiton occurs whenever the buildprocess fails. */ public void parseWithSAX(URL aURL) throws DocumentException { SAXReader xmlReader = new SAXReader(); this.doc = xmlReader.read(aURL); } } Using Reflection API provides the most flexbility for handling all kinds of org.dom4j.io.SAXReader Sources, but that and even a check with instanceof needs a good exception management while you suspend and a lot of xml driven application will not need this flexiblity.
Integrating orginal XML APIs We have talked about reading a document with SAX now. dom4j offers also some classes for integration of the two original XML processing APIs - SAX and DOM. org.dom4j.SAXContentHandler implements some SAX interfaces. Thus you are able to use them to create a specific SAX-based Reader class. The DOMReader class allows you to recycle a exsiting DOM tree. This could be usefull if you already used DOM and want to replace it step by step with dom4j or if you just needs some of DOM's behaviors and want to save memory ressources by transforming it in a dom4j Model. Your are able to transform a DOM Docuemnt, a DOM Node branch and single element. import org.sax.Document; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.DOMReader; public class DOMIntegratorSample { private Document doc; public void buildDOM4JTree(org.sax.Document saxDoc) { DOMReader xmlReader = new DOMReader(); this.doc = xmlReader.read(saxDoc); } }
The secret of DocumentFactory Right now we have talked a lot of reading exisiting XML information e.g. form files, URL's or even Streams. Sometimes it's necessary to generate a XML document from scratch within a running Java Application. The class org.dom4j.DocumentFactory defines a set of factory methods in order to create empty documents, document types, elements, attributes, unparsed character data (CDATA), a namespace, instance regarding XPath, a Nodefilter and some other usefull instances. Thus makes the DocumentFactory class to a central class whenever you have to create one of theses instances by yourself.
import org.dom4j.DocumentFactory; import org.dom4j.Document; import org.dom4j.Element; public class DeployFileCreator { private Document doc; public void generateDoc(String aRootElement) { Element root = DocumentFacotry.getInstance().createElement(aRootElement); this.doc = DocumentFactory.getInstance().createDocument(root); } } The listing shows how two generate a new Document from scratch. The method generateDoc takes a String instance of argument. The string value contains the name of the root element of the new document. As you can see org.dom4j.DocumentFactory is a singleton that is accessable via getInstance() as most java singeltons are. After we obtained the instance we can DocumentFacotrie's methods. They follow the createXXX() naming convention, so if you want to create a Attribute you would call createAttribute() instead. If your class uses DocumentFactory a lot you should add it as a member variable and initiate it via getInstance in your constructor. import org.dom4j.DocumentFactory; import org.dom4j.Document; import org.dom4j.Element; public class GranuatedDeployFileCreator { private DocumentFactory factory; private Document doc; public GranuatedDeployFileCreator() { this.factory = DocumentFactory.getInstance(); } public void generateDoc(String aRootElement) { Element root = this.factory.createElement(aRootElement); this.doc = this.factory.createDocument(root); } } As mentioned earlier dom4j is a interface based API. This means that DocumentFacotry and the Reader classes in io package always returning this interfaces. So you are forced to uses interfaces to work with the object model. Collection API and W3C's DOM itselfs are another APIs that uses this approach. Why that is such a wide spread desing is described here and as well here.
Serialization Once you have parsed or created a document you want to serialized it to disk or into a plain (or encrypted) stream. dom4j provides a set of classes to serialize your DOM4J tree in four ways: XML HTML DOM SAX Events
Serializing to XML org.dom4j.io.XMLWriter is a easy-to-use and easy-to-understand class used to serialize a dom4j Tree to a plain XML. You are able to write these XML tree with either a java.io.OutputStream or a java.io.Writer. This can be configured with the overloaded constructor. Writer's can be installed after inistiation also. Let's have a look at a example. import java.io.OutputStream; import org.dom4j.Document; import org.dom4j.io.XMLWriter; public class DeployFileCreator { private Document doc; public void serilizetoXML(OutputStream out, String aEncodingScheme) throws Exception { XMLWriter writer = new XMLWriter(); writer.setWriter(writer.createWriter(out,aEncodingScheme); writer.write(this.doc); writer.close; } } We used writers createWriter method to wrap a given OutputStream with the appropriate encoding. You should use a Writer rather than a OutputStream, because you are able to control the encoding of your XML application. Since write()-Method is overloaded you are able to write all Object of which DOM4J consits.
Influencing the output format There are two way to influence the output format: org.dom4j.io.OutputFormater and org.dom4j.io.XMLWriter. Both provide methods for formatting the output e.g setting of indent or new line. import java.io.OutputStream; import org.dom4j.Document; import org.dom4j.io.XMLWriter; import org.dom4j.io.OutputFormat; public class DeployFileCreator { private Document doc; public void serilizetoXML(OutputStream out, String aEncodingScheme) throws Exception { XMLWriter writer = new XMLWriter(OutputFormat.getPrettyPrinting()); writer.setWriter(writer.createWriter(out,aEncodingScheme); writer.write(this.doc); writer.close; } } XMLWriter has a default OutputFormat, but that is onyl a unconfigured instance of OutputFormat, so whenever you want to get a good readable output you should configure it. Whereas OutputFormat gains you more control and information about the applied format XMLWriter has confortable methods that provide nearly the same functionability. Another interesting feature of OutputFormat the ability of setting the encoding. It is a good idiom to use OutputFormat for setting the encoding. The close() method is necessary to close the underlying Writer. So if you consider to use a OutputStream you should use flush() insead. import java.io.OutputStream; import org.dom4j.Document; import org.dom4j.io.XMLWriter; import org.dom4j.io.OutputFormat; public class DeployFileCreator { private Document doc; private OutputFormat outFormat; public DeployFileCreator() { this.outFormat = OuputFormat.getPrettyPrinting(); } public DeployFileCreator(OutputFormat outFormat) { this.outFormat = outFormat; } public void serilizeToXML(OutputStream out) throws Exception { XMLWriter writer = new XMLWriter(outFormat); writer.setWriter(writer.createWriter(out,outFormat.getEncoding); writer.write(this.doc); writer.close; } public void serilizeToXML(OutputStream out, String encoding) throws Exception { this.outFormat.setEncoding(encoding); this.serzializeToXML(out); } } The seriazliation methods in our little example will now set encoding using OutputFormater. If you use the parameterless construtor and the seriazliation method takes only an java.io.OutputStream UTF8 is used for encoding. If you need a simple output on screen for debbuing or testing you can omit setting of a Writer or an OutputStream completly because dom4j.org.io.XMLWriter standard Stream is System.out.
Printing HTML HTMLWriter takes a dom4j tree and formats it to a stream as HTML. This formatter is similar to XMLWriter but outputs the text of CDATA and Entity sections rather than the serialised format as in XML and also supports certain element which have no corresponding close tag such as for >BR< and >P< import java.io.OutputStream; import org.dom4j.Document; import org.dom4j.io.HTMLWriter; import org.dom4j.io.OutputFormat; public class DeployFileCreator { private Document doc; private OutputFormat outFormat; public DeployFileCreator() { this.outFormat = OuputFormat.getPrettyPrinting(); } public DeployFileCreator(OutputFormat outFormat) { this.outFormat = outFormat; } public void serilizeToHTML(OutputStream out) throws Exception { HTMLWriter writer = new HTMLWriter(outFormat); writer.setWriter(writer.createWriter(out,outFormat.getEncoding); writer.write(this.doc); writer.close; } }
Building a DOM-Tree Sometimes it's necessary to transform your dom4j tree into an DOM tree, because you are currently refactoring your application. dom4j is very convient for step-to-step substitution of older XML API's like dom or even SAX (see Generating SAX Events). Let's move to an example: import org.w3c.dom.Document; import org.dom4j.Document; import org.dom4j.io.DOMWriter; public class DeployFileLoaderSample { private org.dom4j.Document doc; public org.w3c.dom.Document transformtoDOM() { DOMWriter writer = new DOMWriter(); return writer.createDomDocument(this.doc); } }
Generating SAX Events When you want to resolve a existing document into sax events in order to process the by origin classes dom4j provides org.dom4j.SAXWriter. import org.xml.ConentHandler; import org.dom4j.Document; import org.dom4j.io.SAXWriter; public class DeployFileLoaderSample { private org.dom4j.Document doc; public void transformtoSAX(ContentHandler ctxHandler) { SAXWriter writer = new SAXWriter(); writer.setContentHandler(ctxHandler); writer.write(doc); } } Using SAXWriter is fairly easy as you can see. You can resolve also org.dom.Element which means that you are able to process a single element branch with SAX.
Navigation in DOM4J dom4j offers powerfully methods for navigating through a document. These methods are: Sun Implementation of GOF's Iterator Pattern in Collection API (java.util.Iterator and java.util.ListIterator) Index based navigation with List.get() In-Build XPath support In-Build GOF Visitor Pattern
Using Iterator Most Java developers have already used java.util.Iterator or it's ancestor java.util.Enumeration. Both classe are ziemlich involed into the Collection API and used to visit the elements of a collection. The Iterator is appylied usually with a while loop and Iterator methods hasNext() and next() item. Right now Collection API dont support Generic Type (like C++ Templates), but there's already a Early Access Implemention avaialbe. We talked a lot of Iterator for now let's move to an living example of it in dom4j.
import java.util.Iterator; import org.dom4j.Document; import org.dom4j.Element; public class DeployFileLoaderSample { private org.dom4j.Document doc; private org.dom4j.Element root; public void iterateRootChildren() { root = this.doc.getRootElement(); Iterator elementIterator = root.elementIterator(); while(elementIterator.hasNext()){ System.out.println(((Element)elementIterator.next()).getName()); } } } The above exapmle might be a little bit confusing if you are not close to Collection API. Casting is necessary when you want to acess the object. Sometimes casting can be dangerous because of a java.lang.ClassCastException. dom4j normally uses a clean object model that such a exception never occurs. There's another interesting approach in API may be usefull. import java.util.Iterator; import org.dom4j.Document; import org.dom4j.Element; public class DeployFileLoaderSample { private org.dom4j.Document doc; private org.dom4j.Element root; public void iterateRootChildren(String aFilterElementName) { root = this.doc.getRootElement(); Iterator elementIterator = root.elementIterator(aFilterElementName); while(elementIterator.hasNext()){ System.out.println(((Element)elementIterator.next()).getName()); } } } Now the the method iterates on such Elements that have the same name as the parameterized String only. This can be used as a kind of filter applied on to of Collection API's Iterator.
Index based Nativation Sometimes it's nessary to access an Element directly by it's index. The following example is a modification of our Iterator example explaining index addressing in dom4j. import java.util.List; import org.dom4j.Document; import org.dom4j.Element; public class DeployFileLoaderSample { private org.dom4j.Document doc; private org.dom4j.Element root; public void iterateRootChildren() { root = this.doc.getRootElement(); List elements = root.elements; for(int i=0; i < list.size()-1; i++) { System.out.println(((Element)elements.get(i)).getName()); } } } Remember that this form of Navigation is unsafe. You have to deal with IndexOutOfBoundsException and should choose this form of Navigation only when fast direct acess is necessary.
The elegant XPath Implementation XPath is is one of the most usefull features of dom4j. You can use it to retrieval element brances from any location your currently are. A good XPath Refercence can be found in Micheal Kay's XSLT book XSLTReference.
import java.util.Iterator; import org.dom4j.Document; import org.dom4j.Element; public class DeployFileLoaderSample { private org.dom4j.Document doc; private org.dom4j.Element root; public void browseRootChildren() { Iterator xpathResult = this.doc.selectNodes("/*").iterator(); while(xpathPathResult.hasNext(){ System.out.println(((Element)elementIterator.next()).getName()); } } As selectNodes returns a List we can apply Iterator or any other Operation avaliable on java.util.List. It's also able to select a singel node when you use a fully qualified XPath.
Using Visitor Pattern The visitor pattern has a recrusive behavior and acts like SAX in the way that partical traversal is not possible. This means the complete document or the complete element branch will be visited. You should consider wisely when you want to use Visitor pattern, but then it offers a powerfull and elegant way of navigation. This document doesn't explain Vistor Pattern in deepth, GoF covers more information.
import java.util.Iterator; import org.dom4j.Visitor; import org.dom4j.VisitorSupport; import org.dom4j.Document; import org.dom4j.Element; public class StyleDocumentSample { As you can see we used a anonymous inner class to override the VisitorSupport callback apdapter method visit(Element element), wherase accept starts the inbuild vistor implemention. Please keep in mind that the complete element branch is visited.
Mainpulation with DOM4J Acessing XML content statically is not very amazing. Thus dom4j offers serval methods for manipulation a documents content.
What <classname>org.dom4j.Document</classname> provides A org.dom4j.Document allows you to configure and retreive the root element. You are also able to set the DOCTYPE or a SAX based EntityResolver. An empty Document should be created via org.dom4j.DocumentFactory.
Working with <classname>org.dom4j.Element</classname> org.dom4j.Element is a powerfull interface providing lots of methods for manipulation an Element. public void changeElementName(String aName) { this.element.setName(aName); } public void changeElementText(String aText) { this.element.setText(aText); }
Qualified Names A XML Element should have a qualified name. A qualified name consits normally of a Namespace and a local name. It's recommend to use org.dom4j.DocumentFactory to create Qualifed Names that are provided by org.dom4j.QName instances. import org.dom4j.Element; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.QName; public class DeployFileCreator { protected Document deployDoc; protected Element root; public void DeployFileCreator() { QName rootName = DocumentFactory.getInstance().createQName("preferences", "", "http://java.sun.com/dtd/preferences.dtd"); this.root = DocumentFactory.getInstance().createElement(rootName); this.deployDoc = DocumentFactory.getInstance().createDocument(this.root); } }
Inserting elements Somethimes it's necssary to insert an element somewhere in a existing XML Tree. As dom4j is based on Collection API this causes no problems. The following exapmle shows how it could be done. public void insertElementAt(Element newElement, int index) { Element parent = this.element.getParent(); List list = parent.content(); list.add(index, newElement); } public void testInsertElementAt() { //insert an clone of current element after the current element Element newElement = this.element.clone(); this.insertElementAt(newElement, this.root.indexOf(this.element)+1); // insert an clone of current element before the current element this.insertElementAt(newElement, this.root.indexOf(this.element)); } Studying the Collection API should lead to more solutions for similar problem and you will notify that dom4j fits well in the Collection Framework and both completing each other in order to processing xml document in a comfortable way.
Cloning - Who many sheeps do you need? Elements can be cloned as well. Usually cloning is supported in Java with clone() method that is derived from Object, but a cloneable Object have to implement interface Clonable. Java support shallow copying by simply returning this for standard. dom4j supporting deep cloning because shallow copies would not make sence in context of an XML object model. This means that cloning can take a while because the complete tree branch or event the document will be cloned. Now we have a short look how dom4j coling mechanism is used. import org.dom4j.Document; import org.dom4j.Element; public class DeployFileCreator { private Element cloneElement(String name) { return this.root.element(name).clone(); } private Element cloneDetachElement(String name) { return this.root.createCopy(name); } public class TestElement extends junit.framework.TestCase { public void testCloning() throws junit.framwork.AssertionFailedException { assert("Test cloning with clone() failed!", this.creator.cloneElement("Key") != null); assert("Test cloning with createCopy() failed!", this.creator.cloneDetachElement() != null); } } } The difference between createCopy(...) and clone() is that first is a polymorphic method that created a decoupled deep copy whereas returns a returns a deep copy of the current document or element itself. Cloning might be usefull when you want to build a element pool. Such a pool should be desinged carefully keeping OutOfMemoryException in mind. You could alternativly consider to use Reference API Pawlan98 or other the aproach here JavaWorldTip76
Using dom4j for XSLT With eXtensible Stylesheet Language XML got's a powerfull method of transforming itself into other formats. Developing Exportfilter's for dataformats are normally a hard job and so for XML XSL simpliefs that work. The aronym XSLT means the process of transformation, that is usally done by an XSL compliant Processor. XSL covers following subjects: XSL Style Sheet XSL Processor for XSLT FOP Processor for FOP An XML source Since JaXP 1.1 TraX is the common API for proceeding a XSL Stylesheet inside Java. You start with a TransformerFactory and dealing with Result and Source. A Source contains the source xml file that should be transformed. Result's containted the the result of transformation. dom4j offers org.dom4j.io.DocumentResult and org.dom4j.io.DocumenSource for compatiblity to TrAX. Whereas org.dom4j.io.DocumentResult contains a org.dom4j.Document as result tree, DocumentSource takes dom4j Documents and pepare them for transformation. Both classes are build on top of TraX own SAX classes. This is much more perfomant as a DOM adaptation. The following example explains the use of XSLT with TraX and dom4j. import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import org.dom4j.Document; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; public class TemplateGeneratorSample { public Source styleSheet; public Document schema; public Transformer transformer; public DocumentResult result; public class TemplateGenerator(Document aSchema, Source aStyleSheet) { this.styleSheet = aStyleSheet; this.schema = aSchema; this.result = new DocumentResult(); this.transformer = TransformerFactory.newTransformer(new StreamSource(this.styleSheet.getSystemId())); this.start(); } public void start() { this.transformer.transform(this.schema, this.result); } public Document getTemplate() { return this.result.getDocument(); } } Imagine that you use XSLT to process a XML Schema in order to generate a empty template xml file accoring the schema contraints. The above sample should how easy the Java code is when you use dom4j and it's TraX support. If you use TemplateGenerator a lot you should consider the application of singleton pattern, but for this example I avoided this for simplicity. More information about TraX is provided here. Schema-Support Further Reading Books XSLTReference MichaelKay 2001 Worx Press, Inc. 1-861-005067 Worx Press XSLT Programmer's Reference 2'nd Edition Programmer To Programmer Worx Press GoF95 ErichGamma RichardHelm RalphJohnson JohnVlissides 1995 Addison Wesley Pub, Co. 0-201-633-612 Worx Press XSLT Programmer's Reference 2'nd Edition Articles Pawlan98 MonicaPawlan 1998 http://developer.java.sun.com/javatips/jw-tips76.html Reference Objects and Garbage Collection JavaTip76 DaveMiller http://www.javaworld.com/javaworld/javatips/jw-javatip76.html An alternative to the deep copying technique
dom4j-1.6.1/xml/cdata.xml0000644000175000017500000000014210242120006014442 0ustar ebourgebourg test < one >]]> test two dom4j-1.6.1/xml/fibo.xml0000644000175000017500000000215610242120006014314 0ustar ebourgebourg 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 dom4j-1.6.1/xml/moreover/0000755000175000017500000000000012133227266014526 5ustar ebourgebourgdom4j-1.6.1/xml/moreover/sample.xml0000644000175000017500000002751110242120007016517 0ustar ebourgebourg
http://c.moreover.com/click/here.pl?x13563273 e-Commerce Operators Present Version 1.0 of the XML Standard StockAccess text moreover... http://www.stockaccess.com/index.html Dec 24 2000 6:28AM
http://c.moreover.com/click/here.pl?x13560995 W3C Publishes XML Protocol Requirements Document Xml text moreover... http://www.xml.com/ Dec 24 2000 12:22AM
http://c.moreover.com/click/here.pl?x13553521 Prowler: Open Source XML-Based Content Management Framework Xml text moreover... http://www.xml.com/ Dec 23 2000 2:05PM
http://c.moreover.com/click/here.pl?x13549013 The Middleware Company Debuts Public Training Courses in Ejb, J2ee And Xml Java Industry Connection text moreover... http://industry.java.sun.com/javanews/more/hotnews/ Dec 23 2000 12:15PM
http://c.moreover.com/click/here.pl?x13544467 Revised Working Draft for the W3C XML Information Set Xml text moreover... http://www.xml.com/ Dec 23 2000 5:50AM
http://c.moreover.com/click/here.pl?x13534836 XML: Its The Great Peacemaker ZDNet text moreover... http://www.zdnet.com/intweek/ Dec 22 2000 9:05PM
http://c.moreover.com/click/here.pl?x13533485 Project eL - The XML Leningrad Codex Markup Project Xml text moreover... http://www.xml.com/ Dec 22 2000 8:34PM
http://c.moreover.com/click/here.pl?x13533488 XML Linking Language (XLink) and XML Base Specifications Issued as W3C Proposed Recommenda Xml text moreover... http://www.xml.com/ Dec 22 2000 8:34PM
http://c.moreover.com/click/here.pl?x13533492 W3C Releases XHTML Basic Specification as a W3C Recommendation Xml text moreover... http://www.xml.com/ Dec 22 2000 8:34PM
http://c.moreover.com/click/here.pl?x13521827 Java, Xml And Oracle9i(TM) Make A Great Team Java Industry Connection text moreover... http://industry.java.sun.com/javanews/more/hotnews/ Dec 22 2000 3:21PM
http://c.moreover.com/click/here.pl?x13511233 Competing initiatives to vie for security standard ZDNet text moreover... http://www.zdnet.com/eweek/filters/news/ Dec 22 2000 10:54AM
http://c.moreover.com/click/here.pl?x13492397 Oracle Provides Developers with Great Xml Reading This Holiday Season Java Industry Connection text moreover... http://industry.java.sun.com/javanews/more/hotnews/ Dec 21 2000 8:08PM
http://c.moreover.com/click/here.pl?x13491292 XML as the great peacemaker - Extensible Markup Language Accomplished The Seemingly Impossible This Year: It B Hospitality Net text moreover... http://www.hospitalitynet.org/news/list.htm?c=2000 Dec 21 2000 7:45PM
http://c.moreover.com/click/here.pl?x13484758 XML as the great peacemaker CNET text moreover... http://news.cnet.com/news/0-1003.html?tag=st.ne.1002.dir.1003 Dec 21 2000 4:41PM
http://c.moreover.com/click/here.pl?x13480896 COOP Switzerland Selects Mercator as Integration Platform Stockhouse Canada text moreover... http://www.stockhouse.ca/news/ Dec 21 2000 1:55PM
http://c.moreover.com/click/here.pl?x13471023 Competing XML Specs Move Toward a Union Internet World text moreover... http://www.internetworld.com/ Dec 21 2000 11:14AM
http://c.moreover.com/click/here.pl?x13452280 Next-generation XHTML stripped down for handhelds CNET text moreover... http://news.cnet.com/news/0-1005.html?tag=st.ne.1002.dir.1005 Dec 20 2000 9:11PM
http://c.moreover.com/click/here.pl?x13451789 Xml Powers Oracle9i(TM) Dynamic Services Java Industry Connection text moreover... http://industry.java.sun.com/javanews/more/hotnews/ Dec 20 2000 9:05PM
http://c.moreover.com/click/here.pl?x13442097 XML DOM reference guide ASPWire text moreover... http://aspwire.com/ Dec 20 2000 6:26PM
http://c.moreover.com/click/here.pl?x13424117 Repeat/Xqsite And Bowstreet Team to Deliver Integrated Xml Solutions Java Industry Connection text moreover... http://industry.java.sun.com/javanews/more/hotnews/ Dec 20 2000 9:04AM
dom4j-1.6.1/xml/moreover/moreovernews.dtd0000644000175000017500000000105410242120015017735 0ustar ebourgebourg dom4j-1.6.1/xml/much_ado.xml0000644000175000017500000061245510242120007015166 0ustar ebourgebourg Much Ado about Nothing

Text placed in the public domain by Moby Lexical Tools, 1992.

SGML markup by Jon Bosak, 1992-1994.

XML version by Jon Bosak, 1996-1998.

This work may be freely copied and distributed worldwide.

Dramatis Personae DON PEDRO, prince of Arragon. DON JOHN, his bastard brother. CLAUDIO, a young lord of Florence. BENEDICK, a young lord of Padua. LEONATO, governor of Messina. ANTONIO, his brother. BALTHASAR, attendant on Don Pedro. CONRADE BORACHIO followers of Don John. FRIAR FRANCIS DOGBERRY, a constable. VERGES, a headborough. A Sexton. A Boy. HERO, daughter to Leonato. BEATRICE, niece to Leonato. MARGARET URSULA gentlewomen attending on Hero. Messengers, Watch, Attendants, &c. SCENE Messina. MUCH ADO ABOUT NOTHING ACT I SCENE I. Before LEONATO'S house. Enter LEONATO, HERO, and BEATRICE, with a Messenger LEONATO I learn in this letter that Don Peter of Arragon comes this night to Messina. Messenger He is very near by this: he was not three leagues off when I left him. LEONATO How many gentlemen have you lost in this action? Messenger But few of any sort, and none of name. LEONATO A victory is twice itself when the achiever brings home full numbers. I find here that Don Peter hath bestowed much honour on a young Florentine called Claudio. Messenger Much deserved on his part and equally remembered by Don Pedro: he hath borne himself beyond the promise of his age, doing, in the figure of a lamb, the feats of a lion: he hath indeed better bettered expectation than you must expect of me to tell you how. LEONATO He hath an uncle here in Messina will be very much glad of it. Messenger I have already delivered him letters, and there appears much joy in him; even so much that joy could not show itself modest enough without a badge of bitterness. LEONATO Did he break out into tears? Messenger In great measure. LEONATO A kind overflow of kindness: there are no faces truer than those that are so washed. How much better is it to weep at joy than to joy at weeping! BEATRICE I pray you, is Signior Mountanto returned from the wars or no? Messenger I know none of that name, lady: there was none such in the army of any sort. LEONATO What is he that you ask for, niece? HERO My cousin means Signior Benedick of Padua. Messenger O, he's returned; and as pleasant as ever he was. BEATRICE He set up his bills here in Messina and challenged Cupid at the flight; and my uncle's fool, reading the challenge, subscribed for Cupid, and challenged him at the bird-bolt. I pray you, how many hath he killed and eaten in these wars? But how many hath he killed? for indeed I promised to eat all of his killing. LEONATO Faith, niece, you tax Signior Benedick too much; but he'll be meet with you, I doubt it not. Messenger He hath done good service, lady, in these wars. BEATRICE You had musty victual, and he hath holp to eat it: he is a very valiant trencherman; he hath an excellent stomach. Messenger And a good soldier too, lady. BEATRICE And a good soldier to a lady: but what is he to a lord? Messenger A lord to a lord, a man to a man; stuffed with all honourable virtues. BEATRICE It is so, indeed; he is no less than a stuffed man: but for the stuffing,--well, we are all mortal. LEONATO You must not, sir, mistake my niece. There is a kind of merry war betwixt Signior Benedick and her: they never meet but there's a skirmish of wit between them. BEATRICE Alas! he gets nothing by that. In our last conflict four of his five wits went halting off, and now is the whole man governed with one: so that if he have wit enough to keep himself warm, let him bear it for a difference between himself and his horse; for it is all the wealth that he hath left, to be known a reasonable creature. Who is his companion now? He hath every month a new sworn brother. Messenger Is't possible? BEATRICE Very easily possible: he wears his faith but as the fashion of his hat; it ever changes with the next block. Messenger I see, lady, the gentleman is not in your books. BEATRICE No; an he were, I would burn my study. But, I pray you, who is his companion? Is there no young squarer now that will make a voyage with him to the devil? Messenger He is most in the company of the right noble Claudio. BEATRICE O Lord, he will hang upon him like a disease: he is sooner caught than the pestilence, and the taker runs presently mad. God help the noble Claudio! if he have caught the Benedick, it will cost him a thousand pound ere a' be cured. Messenger I will hold friends with you, lady. BEATRICE Do, good friend. LEONATO You will never run mad, niece. BEATRICE No, not till a hot January. Messenger Don Pedro is approached. Enter DON PEDRO, DON JOHN, CLAUDIO, BENEDICK, and BALTHASAR DON PEDRO Good Signior Leonato, you are come to meet your trouble: the fashion of the world is to avoid cost, and you encounter it. LEONATO Never came trouble to my house in the likeness of your grace: for trouble being gone, comfort should remain; but when you depart from me, sorrow abides and happiness takes his leave. DON PEDRO You embrace your charge too willingly. I think this is your daughter. LEONATO Her mother hath many times told me so. BENEDICK Were you in doubt, sir, that you asked her? LEONATO Signior Benedick, no; for then were you a child. DON PEDRO You have it full, Benedick: we may guess by this what you are, being a man. Truly, the lady fathers herself. Be happy, lady; for you are like an honourable father. BENEDICK If Signior Leonato be her father, she would not have his head on her shoulders for all Messina, as like him as she is. BEATRICE I wonder that you will still be talking, Signior Benedick: nobody marks you. BENEDICK What, my dear Lady Disdain! are you yet living? BEATRICE Is it possible disdain should die while she hath such meet food to feed it as Signior Benedick? Courtesy itself must convert to disdain, if you come in her presence. BENEDICK Then is courtesy a turncoat. But it is certain I am loved of all ladies, only you excepted: and I would I could find in my heart that I had not a hard heart; for, truly, I love none. BEATRICE A dear happiness to women: they would else have been troubled with a pernicious suitor. I thank God and my cold blood, I am of your humour for that: I had rather hear my dog bark at a crow than a man swear he loves me. BENEDICK God keep your ladyship still in that mind! so some gentleman or other shall 'scape a predestinate scratched face. BEATRICE Scratching could not make it worse, an 'twere such a face as yours were. BENEDICK Well, you are a rare parrot-teacher. BEATRICE A bird of my tongue is better than a beast of yours. BENEDICK I would my horse had the speed of your tongue, and so good a continuer. But keep your way, i' God's name; I have done. BEATRICE You always end with a jade's trick: I know you of old. DON PEDRO That is the sum of all, Leonato. Signior Claudio and Signior Benedick, my dear friend Leonato hath invited you all. I tell him we shall stay here at the least a month; and he heartily prays some occasion may detain us longer. I dare swear he is no hypocrite, but prays from his heart. LEONATO If you swear, my lord, you shall not be forsworn. To DON JOHN Let me bid you welcome, my lord: being reconciled to the prince your brother, I owe you all duty. DON JOHN I thank you: I am not of many words, but I thank you. LEONATO Please it your grace lead on? DON PEDRO Your hand, Leonato; we will go together. Exeunt all except BENEDICK and CLAUDIO CLAUDIO Benedick, didst thou note the daughter of Signior Leonato? BENEDICK I noted her not; but I looked on her. CLAUDIO Is she not a modest young lady? BENEDICK Do you question me, as an honest man should do, for my simple true judgment; or would you have me speak after my custom, as being a professed tyrant to their sex? CLAUDIO No; I pray thee speak in sober judgment. BENEDICK Why, i' faith, methinks she's too low for a high praise, too brown for a fair praise and too little for a great praise: only this commendation I can afford her, that were she other than she is, she were unhandsome; and being no other but as she is, I do not like her. CLAUDIO Thou thinkest I am in sport: I pray thee tell me truly how thou likest her. BENEDICK Would you buy her, that you inquire after her? CLAUDIO Can the world buy such a jewel? BENEDICK Yea, and a case to put it into. But speak you this with a sad brow? or do you play the flouting Jack, to tell us Cupid is a good hare-finder and Vulcan a rare carpenter? Come, in what key shall a man take you, to go in the song? CLAUDIO In mine eye she is the sweetest lady that ever I looked on. BENEDICK I can see yet without spectacles and I see no such matter: there's her cousin, an she were not possessed with a fury, exceeds her as much in beauty as the first of May doth the last of December. But I hope you have no intent to turn husband, have you? CLAUDIO I would scarce trust myself, though I had sworn the contrary, if Hero would be my wife. BENEDICK Is't come to this? In faith, hath not the world one man but he will wear his cap with suspicion? Shall I never see a bachelor of three-score again? Go to, i' faith; an thou wilt needs thrust thy neck into a yoke, wear the print of it and sigh away Sundays. Look Don Pedro is returned to seek you. Re-enter DON PEDRO DON PEDRO What secret hath held you here, that you followed not to Leonato's? BENEDICK I would your grace would constrain me to tell. DON PEDRO I charge thee on thy allegiance. BENEDICK You hear, Count Claudio: I can be secret as a dumb man; I would have you think so; but, on my allegiance, mark you this, on my allegiance. He is in love. With who? now that is your grace's part. Mark how short his answer is;--With Hero, Leonato's short daughter. CLAUDIO If this were so, so were it uttered. BENEDICK Like the old tale, my lord: 'it is not so, nor 'twas not so, but, indeed, God forbid it should be so.' CLAUDIO If my passion change not shortly, God forbid it should be otherwise. DON PEDRO Amen, if you love her; for the lady is very well worthy. CLAUDIO You speak this to fetch me in, my lord. DON PEDRO By my troth, I speak my thought. CLAUDIO And, in faith, my lord, I spoke mine. BENEDICK And, by my two faiths and troths, my lord, I spoke mine. CLAUDIO That I love her, I feel. DON PEDRO That she is worthy, I know. BENEDICK That I neither feel how she should be loved nor know how she should be worthy, is the opinion that fire cannot melt out of me: I will die in it at the stake. DON PEDRO Thou wast ever an obstinate heretic in the despite of beauty. CLAUDIO And never could maintain his part but in the force of his will. BENEDICK That a woman conceived me, I thank her; that she brought me up, I likewise give her most humble thanks: but that I will have a recheat winded in my forehead, or hang my bugle in an invisible baldrick, all women shall pardon me. Because I will not do them the wrong to mistrust any, I will do myself the right to trust none; and the fine is, for the which I may go the finer, I will live a bachelor. DON PEDRO I shall see thee, ere I die, look pale with love. BENEDICK With anger, with sickness, or with hunger, my lord, not with love: prove that ever I lose more blood with love than I will get again with drinking, pick out mine eyes with a ballad-maker's pen and hang me up at the door of a brothel-house for the sign of blind Cupid. DON PEDRO Well, if ever thou dost fall from this faith, thou wilt prove a notable argument. BENEDICK If I do, hang me in a bottle like a cat and shoot at me; and he that hits me, let him be clapped on the shoulder, and called Adam. DON PEDRO Well, as time shall try: 'In time the savage bull doth bear the yoke.' BENEDICK The savage bull may; but if ever the sensible Benedick bear it, pluck off the bull's horns and set them in my forehead: and let me be vilely painted, and in such great letters as they write 'Here is good horse to hire,' let them signify under my sign 'Here you may see Benedick the married man.' CLAUDIO If this should ever happen, thou wouldst be horn-mad. DON PEDRO Nay, if Cupid have not spent all his quiver in Venice, thou wilt quake for this shortly. BENEDICK I look for an earthquake too, then. DON PEDRO Well, you temporize with the hours. In the meantime, good Signior Benedick, repair to Leonato's: commend me to him and tell him I will not fail him at supper; for indeed he hath made great preparation. BENEDICK I have almost matter enough in me for such an embassage; and so I commit you-- CLAUDIO To the tuition of God: From my house, if I had it,-- DON PEDRO The sixth of July: Your loving friend, Benedick. BENEDICK Nay, mock not, mock not. The body of your discourse is sometime guarded with fragments, and the guards are but slightly basted on neither: ere you flout old ends any further, examine your conscience: and so I leave you. Exit CLAUDIO My liege, your highness now may do me good. DON PEDRO My love is thine to teach: teach it but how, And thou shalt see how apt it is to learn Any hard lesson that may do thee good. CLAUDIO Hath Leonato any son, my lord? DON PEDRO No child but Hero; she's his only heir. Dost thou affect her, Claudio? CLAUDIO O, my lord, When you went onward on this ended action, I look'd upon her with a soldier's eye, That liked, but had a rougher task in hand Than to drive liking to the name of love: But now I am return'd and that war-thoughts Have left their places vacant, in their rooms Come thronging soft and delicate desires, All prompting me how fair young Hero is, Saying, I liked her ere I went to wars. DON PEDRO Thou wilt be like a lover presently And tire the hearer with a book of words. If thou dost love fair Hero, cherish it, And I will break with her and with her father, And thou shalt have her. Was't not to this end That thou began'st to twist so fine a story? CLAUDIO How sweetly you do minister to love, That know love's grief by his complexion! But lest my liking might too sudden seem, I would have salved it with a longer treatise. DON PEDRO What need the bridge much broader than the flood? The fairest grant is the necessity. Look, what will serve is fit: 'tis once, thou lovest, And I will fit thee with the remedy. I know we shall have revelling to-night: I will assume thy part in some disguise And tell fair Hero I am Claudio, And in her bosom I'll unclasp my heart And take her hearing prisoner with the force And strong encounter of my amorous tale: Then after to her father will I break; And the conclusion is, she shall be thine. In practise let us put it presently. Exeunt SCENE II. A room in LEONATO's house. Enter LEONATO and ANTONIO, meeting LEONATO How now, brother! Where is my cousin, your son? hath he provided this music? ANTONIO He is very busy about it. But, brother, I can tell you strange news that you yet dreamt not of. LEONATO Are they good? ANTONIO As the event stamps them: but they have a good cover; they show well outward. The prince and Count Claudio, walking in a thick-pleached alley in mine orchard, were thus much overheard by a man of mine: the prince discovered to Claudio that he loved my niece your daughter and meant to acknowledge it this night in a dance: and if he found her accordant, he meant to take the present time by the top and instantly break with you of it. LEONATO Hath the fellow any wit that told you this? ANTONIO A good sharp fellow: I will send for him; and question him yourself. LEONATO No, no; we will hold it as a dream till it appear itself: but I will acquaint my daughter withal, that she may be the better prepared for an answer, if peradventure this be true. Go you and tell her of it. Enter Attendants Cousins, you know what you have to do. O, I cry you mercy, friend; go you with me, and I will use your skill. Good cousin, have a care this busy time. Exeunt SCENE III. The same. Enter DON JOHN and CONRADE CONRADE What the good-year, my lord! why are you thus out of measure sad? DON JOHN There is no measure in the occasion that breeds; therefore the sadness is without limit. CONRADE You should hear reason. DON JOHN And when I have heard it, what blessing brings it? CONRADE If not a present remedy, at least a patient sufferance. DON JOHN I wonder that thou, being, as thou sayest thou art, born under Saturn, goest about to apply a moral medicine to a mortifying mischief. I cannot hide what I am: I must be sad when I have cause and smile at no man's jests, eat when I have stomach and wait for no man's leisure, sleep when I am drowsy and tend on no man's business, laugh when I am merry and claw no man in his humour. CONRADE Yea, but you must not make the full show of this till you may do it without controlment. You have of late stood out against your brother, and he hath ta'en you newly into his grace; where it is impossible you should take true root but by the fair weather that you make yourself: it is needful that you frame the season for your own harvest. DON JOHN I had rather be a canker in a hedge than a rose in his grace, and it better fits my blood to be disdained of all than to fashion a carriage to rob love from any: in this, though I cannot be said to be a flattering honest man, it must not be denied but I am a plain-dealing villain. I am trusted with a muzzle and enfranchised with a clog; therefore I have decreed not to sing in my cage. If I had my mouth, I would bite; if I had my liberty, I would do my liking: in the meantime let me be that I am and seek not to alter me. CONRADE Can you make no use of your discontent? DON JOHN I make all use of it, for I use it only. Who comes here? Enter BORACHIO What news, Borachio? BORACHIO I came yonder from a great supper: the prince your brother is royally entertained by Leonato: and I can give you intelligence of an intended marriage. DON JOHN Will it serve for any model to build mischief on? What is he for a fool that betroths himself to unquietness? BORACHIO Marry, it is your brother's right hand. DON JOHN Who? the most exquisite Claudio? BORACHIO Even he. DON JOHN A proper squire! And who, and who? which way looks he? BORACHIO Marry, on Hero, the daughter and heir of Leonato. DON JOHN A very forward March-chick! How came you to this? BORACHIO Being entertained for a perfumer, as I was smoking a musty room, comes me the prince and Claudio, hand in hand in sad conference: I whipt me behind the arras; and there heard it agreed upon that the prince should woo Hero for himself, and having obtained her, give her to Count Claudio. DON JOHN Come, come, let us thither: this may prove food to my displeasure. That young start-up hath all the glory of my overthrow: if I can cross him any way, I bless myself every way. You are both sure, and will assist me? CONRADE To the death, my lord. DON JOHN Let us to the great supper: their cheer is the greater that I am subdued. Would the cook were of my mind! Shall we go prove what's to be done? BORACHIO We'll wait upon your lordship. Exeunt ACT II SCENE I. A hall in LEONATO'S house. Enter LEONATO, ANTONIO, HERO, BEATRICE, and others LEONATO Was not Count John here at supper? ANTONIO I saw him not. BEATRICE How tartly that gentleman looks! I never can see him but I am heart-burned an hour after. HERO He is of a very melancholy disposition. BEATRICE He were an excellent man that were made just in the midway between him and Benedick: the one is too like an image and says nothing, and the other too like my lady's eldest son, evermore tattling. LEONATO Then half Signior Benedick's tongue in Count John's mouth, and half Count John's melancholy in Signior Benedick's face,-- BEATRICE With a good leg and a good foot, uncle, and money enough in his purse, such a man would win any woman in the world, if a' could get her good-will. LEONATO By my troth, niece, thou wilt never get thee a husband, if thou be so shrewd of thy tongue. ANTONIO In faith, she's too curst. BEATRICE Too curst is more than curst: I shall lessen God's sending that way; for it is said, 'God sends a curst cow short horns;' but to a cow too curst he sends none. LEONATO So, by being too curst, God will send you no horns. BEATRICE Just, if he send me no husband; for the which blessing I am at him upon my knees every morning and evening. Lord, I could not endure a husband with a beard on his face: I had rather lie in the woollen. LEONATO You may light on a husband that hath no beard. BEATRICE What should I do with him? dress him in my apparel and make him my waiting-gentlewoman? He that hath a beard is more than a youth, and he that hath no beard is less than a man: and he that is more than a youth is not for me, and he that is less than a man, I am not for him: therefore, I will even take sixpence in earnest of the bear-ward, and lead his apes into hell. LEONATO Well, then, go you into hell? BEATRICE No, but to the gate; and there will the devil meet me, like an old cuckold, with horns on his head, and say 'Get you to heaven, Beatrice, get you to heaven; here's no place for you maids:' so deliver I up my apes, and away to Saint Peter for the heavens; he shows me where the bachelors sit, and there live we as merry as the day is long. ANTONIO To HERO Well, niece, I trust you will be ruled by your father. BEATRICE Yes, faith; it is my cousin's duty to make curtsy and say 'Father, as it please you.' But yet for all that, cousin, let him be a handsome fellow, or else make another curtsy and say 'Father, as it please me.' LEONATO Well, niece, I hope to see you one day fitted with a husband. BEATRICE Not till God make men of some other metal than earth. Would it not grieve a woman to be overmastered with a pierce of valiant dust? to make an account of her life to a clod of wayward marl? No, uncle, I'll none: Adam's sons are my brethren; and, truly, I hold it a sin to match in my kindred. LEONATO Daughter, remember what I told you: if the prince do solicit you in that kind, you know your answer. BEATRICE The fault will be in the music, cousin, if you be not wooed in good time: if the prince be too important, tell him there is measure in every thing and so dance out the answer. For, hear me, Hero: wooing, wedding, and repenting, is as a Scotch jig, a measure, and a cinque pace: the first suit is hot and hasty, like a Scotch jig, and full as fantastical; the wedding, mannerly-modest, as a measure, full of state and ancientry; and then comes repentance and, with his bad legs, falls into the cinque pace faster and faster, till he sink into his grave. LEONATO Cousin, you apprehend passing shrewdly. BEATRICE I have a good eye, uncle; I can see a church by daylight. LEONATO The revellers are entering, brother: make good room. All put on their masks Enter DON PEDRO, CLAUDIO, BENEDICK, BALTHASAR, DON JOHN, BORACHIO, MARGARET, URSULA and others, masked DON PEDRO Lady, will you walk about with your friend? HERO So you walk softly and look sweetly and say nothing, I am yours for the walk; and especially when I walk away. DON PEDRO With me in your company? HERO I may say so, when I please. DON PEDRO And when please you to say so? HERO When I like your favour; for God defend the lute should be like the case! DON PEDRO My visor is Philemon's roof; within the house is Jove. HERO Why, then, your visor should be thatched. DON PEDRO Speak low, if you speak love. Drawing her aside BALTHASAR Well, I would you did like me. MARGARET So would not I, for your own sake; for I have many ill-qualities. BALTHASAR Which is one? MARGARET I say my prayers aloud. BALTHASAR I love you the better: the hearers may cry, Amen. MARGARET God match me with a good dancer! BALTHASAR Amen. MARGARET And God keep him out of my sight when the dance is done! Answer, clerk. BALTHASAR No more words: the clerk is answered. URSULA I know you well enough; you are Signior Antonio. ANTONIO At a word, I am not. URSULA I know you by the waggling of your head. ANTONIO To tell you true, I counterfeit him. URSULA You could never do him so ill-well, unless you were the very man. Here's his dry hand up and down: you are he, you are he. ANTONIO At a word, I am not. URSULA Come, come, do you think I do not know you by your excellent wit? can virtue hide itself? Go to, mum, you are he: graces will appear, and there's an end. BEATRICE Will you not tell me who told you so? BENEDICK No, you shall pardon me. BEATRICE Nor will you not tell me who you are? BENEDICK Not now. BEATRICE That I was disdainful, and that I had my good wit out of the 'Hundred Merry Tales:'--well this was Signior Benedick that said so. BENEDICK What's he? BEATRICE I am sure you know him well enough. BENEDICK Not I, believe me. BEATRICE Did he never make you laugh? BENEDICK I pray you, what is he? BEATRICE Why, he is the prince's jester: a very dull fool; only his gift is in devising impossible slanders: none but libertines delight in him; and the commendation is not in his wit, but in his villany; for he both pleases men and angers them, and then they laugh at him and beat him. I am sure he is in the fleet: I would he had boarded me. BENEDICK When I know the gentleman, I'll tell him what you say. BEATRICE Do, do: he'll but break a comparison or two on me; which, peradventure not marked or not laughed at, strikes him into melancholy; and then there's a partridge wing saved, for the fool will eat no supper that night. Music We must follow the leaders. BENEDICK In every good thing. BEATRICE Nay, if they lead to any ill, I will leave them at the next turning. Dance. Then exeunt all except DON JOHN, BORACHIO, and CLAUDIO DON JOHN Sure my brother is amorous on Hero and hath withdrawn her father to break with him about it. The ladies follow her and but one visor remains. BORACHIO And that is Claudio: I know him by his bearing. DON JOHN Are not you Signior Benedick? CLAUDIO You know me well; I am he. DON JOHN Signior, you are very near my brother in his love: he is enamoured on Hero; I pray you, dissuade him from her: she is no equal for his birth: you may do the part of an honest man in it. CLAUDIO How know you he loves her? DON JOHN I heard him swear his affection. BORACHIO So did I too; and he swore he would marry her to-night. DON JOHN Come, let us to the banquet. Exeunt DON JOHN and BORACHIO CLAUDIO Thus answer I in the name of Benedick, But hear these ill news with the ears of Claudio. 'Tis certain so; the prince wooes for himself. Friendship is constant in all other things Save in the office and affairs of love: Therefore, all hearts in love use their own tongues; Let every eye negotiate for itself And trust no agent; for beauty is a witch Against whose charms faith melteth into blood. This is an accident of hourly proof, Which I mistrusted not. Farewell, therefore, Hero! Re-enter BENEDICK BENEDICK Count Claudio? CLAUDIO Yea, the same. BENEDICK Come, will you go with me? CLAUDIO Whither? BENEDICK Even to the next willow, about your own business, county. What fashion will you wear the garland of? about your neck, like an usurer's chain? or under your arm, like a lieutenant's scarf? You must wear it one way, for the prince hath got your Hero. CLAUDIO I wish him joy of her. BENEDICK Why, that's spoken like an honest drovier: so they sell bullocks. But did you think the prince would have served you thus? CLAUDIO I pray you, leave me. BENEDICK Ho! now you strike like the blind man: 'twas the boy that stole your meat, and you'll beat the post. CLAUDIO If it will not be, I'll leave you. Exit BENEDICK Alas, poor hurt fowl! now will he creep into sedges. But that my Lady Beatrice should know me, and not know me! The prince's fool! Ha? It may be I go under that title because I am merry. Yea, but so I am apt to do myself wrong; I am not so reputed: it is the base, though bitter, disposition of Beatrice that puts the world into her person and so gives me out. Well, I'll be revenged as I may. Re-enter DON PEDRO DON PEDRO Now, signior, where's the count? did you see him? BENEDICK Troth, my lord, I have played the part of Lady Fame. I found him here as melancholy as a lodge in a warren: I told him, and I think I told him true, that your grace had got the good will of this young lady; and I offered him my company to a willow-tree, either to make him a garland, as being forsaken, or to bind him up a rod, as being worthy to be whipped. DON PEDRO To be whipped! What's his fault? BENEDICK The flat transgression of a schoolboy, who, being overjoyed with finding a birds' nest, shows it his companion, and he steals it. DON PEDRO Wilt thou make a trust a transgression? The transgression is in the stealer. BENEDICK Yet it had not been amiss the rod had been made, and the garland too; for the garland he might have worn himself, and the rod he might have bestowed on you, who, as I take it, have stolen his birds' nest. DON PEDRO I will but teach them to sing, and restore them to the owner. BENEDICK If their singing answer your saying, by my faith, you say honestly. DON PEDRO The Lady Beatrice hath a quarrel to you: the gentleman that danced with her told her she is much wronged by you. BENEDICK O, she misused me past the endurance of a block! an oak but with one green leaf on it would have answered her; my very visor began to assume life and scold with her. She told me, not thinking I had been myself, that I was the prince's jester, that I was duller than a great thaw; huddling jest upon jest with such impossible conveyance upon me that I stood like a man at a mark, with a whole army shooting at me. She speaks poniards, and every word stabs: if her breath were as terrible as her terminations, there were no living near her; she would infect to the north star. I would not marry her, though she were endowed with all that Adam bad left him before he transgressed: she would have made Hercules have turned spit, yea, and have cleft his club to make the fire too. Come, talk not of her: you shall find her the infernal Ate in good apparel. I would to God some scholar would conjure her; for certainly, while she is here, a man may live as quiet in hell as in a sanctuary; and people sin upon purpose, because they would go thither; so, indeed, all disquiet, horror and perturbation follows her. DON PEDRO Look, here she comes. Enter CLAUDIO, BEATRICE, HERO, and LEONATO BENEDICK Will your grace command me any service to the world's end? I will go on the slightest errand now to the Antipodes that you can devise to send me on; I will fetch you a tooth-picker now from the furthest inch of Asia, bring you the length of Prester John's foot, fetch you a hair off the great Cham's beard, do you any embassage to the Pigmies, rather than hold three words' conference with this harpy. You have no employment for me? DON PEDRO None, but to desire your good company. BENEDICK O God, sir, here's a dish I love not: I cannot endure my Lady Tongue. Exit DON PEDRO Come, lady, come; you have lost the heart of Signior Benedick. BEATRICE Indeed, my lord, he lent it me awhile; and I gave him use for it, a double heart for his single one: marry, once before he won it of me with false dice, therefore your grace may well say I have lost it. DON PEDRO You have put him down, lady, you have put him down. BEATRICE So I would not he should do me, my lord, lest I should prove the mother of fools. I have brought Count Claudio, whom you sent me to seek. DON PEDRO Why, how now, count! wherefore are you sad? CLAUDIO Not sad, my lord. DON PEDRO How then? sick? CLAUDIO Neither, my lord. BEATRICE The count is neither sad, nor sick, nor merry, nor well; but civil count, civil as an orange, and something of that jealous complexion. DON PEDRO I' faith, lady, I think your blazon to be true; though, I'll be sworn, if he be so, his conceit is false. Here, Claudio, I have wooed in thy name, and fair Hero is won: I have broke with her father, and his good will obtained: name the day of marriage, and God give thee joy! LEONATO Count, take of me my daughter, and with her my fortunes: his grace hath made the match, and an grace say Amen to it. BEATRICE Speak, count, 'tis your cue. CLAUDIO Silence is the perfectest herald of joy: I were but little happy, if I could say how much. Lady, as you are mine, I am yours: I give away myself for you and dote upon the exchange. BEATRICE Speak, cousin; or, if you cannot, stop his mouth with a kiss, and let not him speak neither. DON PEDRO In faith, lady, you have a merry heart. BEATRICE Yea, my lord; I thank it, poor fool, it keeps on the windy side of care. My cousin tells him in his ear that he is in her heart. CLAUDIO And so she doth, cousin. BEATRICE Good Lord, for alliance! Thus goes every one to the world but I, and I am sunburnt; I may sit in a corner and cry heigh-ho for a husband! DON PEDRO Lady Beatrice, I will get you one. BEATRICE I would rather have one of your father's getting. Hath your grace ne'er a brother like you? Your father got excellent husbands, if a maid could come by them. DON PEDRO Will you have me, lady? BEATRICE No, my lord, unless I might have another for working-days: your grace is too costly to wear every day. But, I beseech your grace, pardon me: I was born to speak all mirth and no matter. DON PEDRO Your silence most offends me, and to be merry best becomes you; for, out of question, you were born in a merry hour. BEATRICE No, sure, my lord, my mother cried; but then there was a star danced, and under that was I born. Cousins, God give you joy! LEONATO Niece, will you look to those things I told you of? BEATRICE I cry you mercy, uncle. By your grace's pardon. Exit DON PEDRO By my troth, a pleasant-spirited lady. LEONATO There's little of the melancholy element in her, my lord: she is never sad but when she sleeps, and not ever sad then; for I have heard my daughter say, she hath often dreamed of unhappiness and waked herself with laughing. DON PEDRO She cannot endure to hear tell of a husband. LEONATO O, by no means: she mocks all her wooers out of suit. DON PEDRO She were an excellent wife for Benedict. LEONATO O Lord, my lord, if they were but a week married, they would talk themselves mad. DON PEDRO County Claudio, when mean you to go to church? CLAUDIO To-morrow, my lord: time goes on crutches till love have all his rites. LEONATO Not till Monday, my dear son, which is hence a just seven-night; and a time too brief, too, to have all things answer my mind. DON PEDRO Come, you shake the head at so long a breathing: but, I warrant thee, Claudio, the time shall not go dully by us. I will in the interim undertake one of Hercules' labours; which is, to bring Signior Benedick and the Lady Beatrice into a mountain of affection the one with the other. I would fain have it a match, and I doubt not but to fashion it, if you three will but minister such assistance as I shall give you direction. LEONATO My lord, I am for you, though it cost me ten nights' watchings. CLAUDIO And I, my lord. DON PEDRO And you too, gentle Hero? HERO I will do any modest office, my lord, to help my cousin to a good husband. DON PEDRO And Benedick is not the unhopefullest husband that I know. Thus far can I praise him; he is of a noble strain, of approved valour and confirmed honesty. I will teach you how to humour your cousin, that she shall fall in love with Benedick; and I, with your two helps, will so practise on Benedick that, in despite of his quick wit and his queasy stomach, he shall fall in love with Beatrice. If we can do this, Cupid is no longer an archer: his glory shall be ours, for we are the only love-gods. Go in with me, and I will tell you my drift. Exeunt SCENE II. The same. Enter DON JOHN and BORACHIO DON JOHN It is so; the Count Claudio shall marry the daughter of Leonato. BORACHIO Yea, my lord; but I can cross it. DON JOHN Any bar, any cross, any impediment will be medicinable to me: I am sick in displeasure to him, and whatsoever comes athwart his affection ranges evenly with mine. How canst thou cross this marriage? BORACHIO Not honestly, my lord; but so covertly that no dishonesty shall appear in me. DON JOHN Show me briefly how. BORACHIO I think I told your lordship a year since, how much I am in the favour of Margaret, the waiting gentlewoman to Hero. DON JOHN I remember. BORACHIO I can, at any unseasonable instant of the night, appoint her to look out at her lady's chamber window. DON JOHN What life is in that, to be the death of this marriage? BORACHIO The poison of that lies in you to temper. Go you to the prince your brother; spare not to tell him that he hath wronged his honour in marrying the renowned Claudio--whose estimation do you mightily hold up--to a contaminated stale, such a one as Hero. DON JOHN What proof shall I make of that? BORACHIO Proof enough to misuse the prince, to vex Claudio, to undo Hero and kill Leonato. Look you for any other issue? DON JOHN Only to despite them, I will endeavour any thing. BORACHIO Go, then; find me a meet hour to draw Don Pedro and the Count Claudio alone: tell them that you know that Hero loves me; intend a kind of zeal both to the prince and Claudio, as,--in love of your brother's honour, who hath made this match, and his friend's reputation, who is thus like to be cozened with the semblance of a maid,--that you have discovered thus. They will scarcely believe this without trial: offer them instances; which shall bear no less likelihood than to see me at her chamber-window, hear me call Margaret Hero, hear Margaret term me Claudio; and bring them to see this the very night before the intended wedding,--for in the meantime I will so fashion the matter that Hero shall be absent,--and there shall appear such seeming truth of Hero's disloyalty that jealousy shall be called assurance and all the preparation overthrown. DON JOHN Grow this to what adverse issue it can, I will put it in practise. Be cunning in the working this, and thy fee is a thousand ducats. BORACHIO Be you constant in the accusation, and my cunning shall not shame me. DON JOHN I will presently go learn their day of marriage. Exeunt SCENE III. LEONATO'S orchard. Enter BENEDICK BENEDICK Boy! Enter Boy Boy Signior? BENEDICK In my chamber-window lies a book: bring it hither to me in the orchard. Boy I am here already, sir. BENEDICK I know that; but I would have thee hence, and here again. Exit Boy I do much wonder that one man, seeing how much another man is a fool when he dedicates his behaviors to love, will, after he hath laughed at such shallow follies in others, become the argument of his own scorn by failing in love: and such a man is Claudio. I have known when there was no music with him but the drum and the fife; and now had he rather hear the tabour and the pipe: I have known when he would have walked ten mile a-foot to see a good armour; and now will he lie ten nights awake, carving the fashion of a new doublet. He was wont to speak plain and to the purpose, like an honest man and a soldier; and now is he turned orthography; his words are a very fantastical banquet, just so many strange dishes. May I be so converted and see with these eyes? I cannot tell; I think not: I will not be sworn, but love may transform me to an oyster; but I'll take my oath on it, till he have made an oyster of me, he shall never make me such a fool. One woman is fair, yet I am well; another is wise, yet I am well; another virtuous, yet I am well; but till all graces be in one woman, one woman shall not come in my grace. Rich she shall be, that's certain; wise, or I'll none; virtuous, or I'll never cheapen her; fair, or I'll never look on her; mild, or come not near me; noble, or not I for an angel; of good discourse, an excellent musician, and her hair shall be of what colour it please God. Ha! the prince and Monsieur Love! I will hide me in the arbour. Withdraws Enter DON PEDRO, CLAUDIO, and LEONATO DON PEDRO Come, shall we hear this music? CLAUDIO Yea, my good lord. How still the evening is, As hush'd on purpose to grace harmony! DON PEDRO See you where Benedick hath hid himself? CLAUDIO O, very well, my lord: the music ended, We'll fit the kid-fox with a pennyworth. Enter BALTHASAR with Music DON PEDRO Come, Balthasar, we'll hear that song again. BALTHASAR O, good my lord, tax not so bad a voice To slander music any more than once. DON PEDRO It is the witness still of excellency To put a strange face on his own perfection. I pray thee, sing, and let me woo no more. BALTHASAR Because you talk of wooing, I will sing; Since many a wooer doth commence his suit To her he thinks not worthy, yet he wooes, Yet will he swear he loves. DON PEDRO Now, pray thee, come; Or, if thou wilt hold longer argument, Do it in notes. BALTHASAR Note this before my notes; There's not a note of mine that's worth the noting. DON PEDRO Why, these are very crotchets that he speaks; Note, notes, forsooth, and nothing. Air BENEDICK Now, divine air! now is his soul ravished! Is it not strange that sheeps' guts should hale souls out of men's bodies? Well, a horn for my money, when all's done. The Song BALTHASAR Sigh no more, ladies, sigh no more, Men were deceivers ever, One foot in sea and one on shore, To one thing constant never: Then sigh not so, but let them go, And be you blithe and bonny, Converting all your sounds of woe Into Hey nonny, nonny. Sing no more ditties, sing no moe, Of dumps so dull and heavy; The fraud of men was ever so, Since summer first was leafy: Then sigh not so, &c. DON PEDRO By my troth, a good song. BALTHASAR And an ill singer, my lord. DON PEDRO Ha, no, no, faith; thou singest well enough for a shift. BENEDICK An he had been a dog that should have howled thus, they would have hanged him: and I pray God his bad voice bode no mischief. I had as lief have heard the night-raven, come what plague could have come after it. DON PEDRO Yea, marry, dost thou hear, Balthasar? I pray thee, get us some excellent music; for to-morrow night we would have it at the Lady Hero's chamber-window. BALTHASAR The best I can, my lord. DON PEDRO Do so: farewell. Exit BALTHASAR Come hither, Leonato. What was it you told me of to-day, that your niece Beatrice was in love with Signior Benedick? CLAUDIO O, ay: stalk on. stalk on; the fowl sits. I did never think that lady would have loved any man. LEONATO No, nor I neither; but most wonderful that she should so dote on Signior Benedick, whom she hath in all outward behaviors seemed ever to abhor. BENEDICK Is't possible? Sits the wind in that corner? LEONATO By my troth, my lord, I cannot tell what to think of it but that she loves him with an enraged affection: it is past the infinite of thought. DON PEDRO May be she doth but counterfeit. CLAUDIO Faith, like enough. LEONATO O God, counterfeit! There was never counterfeit of passion came so near the life of passion as she discovers it. DON PEDRO Why, what effects of passion shows she? CLAUDIO Bait the hook well; this fish will bite. LEONATO What effects, my lord? She will sit you, you heard my daughter tell you how. CLAUDIO She did, indeed. DON PEDRO How, how, pray you? You amaze me: I would have I thought her spirit had been invincible against all assaults of affection. LEONATO I would have sworn it had, my lord; especially against Benedick. BENEDICK I should think this a gull, but that the white-bearded fellow speaks it: knavery cannot, sure, hide himself in such reverence. CLAUDIO He hath ta'en the infection: hold it up. DON PEDRO Hath she made her affection known to Benedick? LEONATO No; and swears she never will: that's her torment. CLAUDIO 'Tis true, indeed; so your daughter says: 'Shall I,' says she, 'that have so oft encountered him with scorn, write to him that I love him?' LEONATO This says she now when she is beginning to write to him; for she'll be up twenty times a night, and there will she sit in her smock till she have writ a sheet of paper: my daughter tells us all. CLAUDIO Now you talk of a sheet of paper, I remember a pretty jest your daughter told us of. LEONATO O, when she had writ it and was reading it over, she found Benedick and Beatrice between the sheet? CLAUDIO That. LEONATO O, she tore the letter into a thousand halfpence; railed at herself, that she should be so immodest to write to one that she knew would flout her; 'I measure him,' says she, 'by my own spirit; for I should flout him, if he writ to me; yea, though I love him, I should.' CLAUDIO Then down upon her knees she falls, weeps, sobs, beats her heart, tears her hair, prays, curses; 'O sweet Benedick! God give me patience!' LEONATO She doth indeed; my daughter says so: and the ecstasy hath so much overborne her that my daughter is sometime afeared she will do a desperate outrage to herself: it is very true. DON PEDRO It were good that Benedick knew of it by some other, if she will not discover it. CLAUDIO To what end? He would make but a sport of it and torment the poor lady worse. DON PEDRO An he should, it were an alms to hang him. She's an excellent sweet lady; and, out of all suspicion, she is virtuous. CLAUDIO And she is exceeding wise. DON PEDRO In every thing but in loving Benedick. LEONATO O, my lord, wisdom and blood combating in so tender a body, we have ten proofs to one that blood hath the victory. I am sorry for her, as I have just cause, being her uncle and her guardian. DON PEDRO I would she had bestowed this dotage on me: I would have daffed all other respects and made her half myself. I pray you, tell Benedick of it, and hear what a' will say. LEONATO Were it good, think you? CLAUDIO Hero thinks surely she will die; for she says she will die, if he love her not, and she will die, ere she make her love known, and she will die, if he woo her, rather than she will bate one breath of her accustomed crossness. DON PEDRO She doth well: if she should make tender of her love, 'tis very possible he'll scorn it; for the man, as you know all, hath a contemptible spirit. CLAUDIO He is a very proper man. DON PEDRO He hath indeed a good outward happiness. CLAUDIO Before God! and, in my mind, very wise. DON PEDRO He doth indeed show some sparks that are like wit. CLAUDIO And I take him to be valiant. DON PEDRO As Hector, I assure you: and in the managing of quarrels you may say he is wise; for either he avoids them with great discretion, or undertakes them with a most Christian-like fear. LEONATO If he do fear God, a' must necessarily keep peace: if he break the peace, he ought to enter into a quarrel with fear and trembling. DON PEDRO And so will he do; for the man doth fear God, howsoever it seems not in him by some large jests he will make. Well I am sorry for your niece. Shall we go seek Benedick, and tell him of her love? CLAUDIO Never tell him, my lord: let her wear it out with good counsel. LEONATO Nay, that's impossible: she may wear her heart out first. DON PEDRO Well, we will hear further of it by your daughter: let it cool the while. I love Benedick well; and I could wish he would modestly examine himself, to see how much he is unworthy so good a lady. LEONATO My lord, will you walk? dinner is ready. CLAUDIO If he do not dote on her upon this, I will never trust my expectation. DON PEDRO Let there be the same net spread for her; and that must your daughter and her gentlewomen carry. The sport will be, when they hold one an opinion of another's dotage, and no such matter: that's the scene that I would see, which will be merely a dumb-show. Let us send her to call him in to dinner. Exeunt DON PEDRO, CLAUDIO, and LEONATO BENEDICK Coming forward This can be no trick: the conference was sadly borne. They have the truth of this from Hero. They seem to pity the lady: it seems her affections have their full bent. Love me! why, it must be requited. I hear how I am censured: they say I will bear myself proudly, if I perceive the love come from her; they say too that she will rather die than give any sign of affection. I did never think to marry: I must not seem proud: happy are they that hear their detractions and can put them to mending. They say the lady is fair; 'tis a truth, I can bear them witness; and virtuous; 'tis so, I cannot reprove it; and wise, but for loving me; by my troth, it is no addition to her wit, nor no great argument of her folly, for I will be horribly in love with her. I may chance have some odd quirks and remnants of wit broken on me, because I have railed so long against marriage: but doth not the appetite alter? a man loves the meat in his youth that he cannot endure in his age. Shall quips and sentences and these paper bullets of the brain awe a man from the career of his humour? No, the world must be peopled. When I said I would die a bachelor, I did not think I should live till I were married. Here comes Beatrice. By this day! she's a fair lady: I do spy some marks of love in her. Enter BEATRICE BEATRICE Against my will I am sent to bid you come in to dinner. BENEDICK Fair Beatrice, I thank you for your pains. BEATRICE I took no more pains for those thanks than you take pains to thank me: if it had been painful, I would not have come. BENEDICK You take pleasure then in the message? BEATRICE Yea, just so much as you may take upon a knife's point and choke a daw withal. You have no stomach, signior: fare you well. Exit BENEDICK Ha! 'Against my will I am sent to bid you come in to dinner;' there's a double meaning in that 'I took no more pains for those thanks than you took pains to thank me.' that's as much as to say, Any pains that I take for you is as easy as thanks. If I do not take pity of her, I am a villain; if I do not love her, I am a Jew. I will go get her picture. Exit ACT III SCENE I. LEONATO'S garden. Enter HERO, MARGARET, and URSULA HERO Good Margaret, run thee to the parlor; There shalt thou find my cousin Beatrice Proposing with the prince and Claudio: Whisper her ear and tell her, I and Ursula Walk in the orchard and our whole discourse Is all of her; say that thou overheard'st us; And bid her steal into the pleached bower, Where honeysuckles, ripen'd by the sun, Forbid the sun to enter, like favourites, Made proud by princes, that advance their pride Against that power that bred it: there will she hide her, To listen our purpose. This is thy office; Bear thee well in it and leave us alone. MARGARET I'll make her come, I warrant you, presently. Exit HERO Now, Ursula, when Beatrice doth come, As we do trace this alley up and down, Our talk must only be of Benedick. When I do name him, let it be thy part To praise him more than ever man did merit: My talk to thee must be how Benedick Is sick in love with Beatrice. Of this matter Is little Cupid's crafty arrow made, That only wounds by hearsay. Enter BEATRICE, behind Now begin; For look where Beatrice, like a lapwing, runs Close by the ground, to hear our conference. URSULA The pleasant'st angling is to see the fish Cut with her golden oars the silver stream, And greedily devour the treacherous bait: So angle we for Beatrice; who even now Is couched in the woodbine coverture. Fear you not my part of the dialogue. HERO Then go we near her, that her ear lose nothing Of the false sweet bait that we lay for it. Approaching the bower No, truly, Ursula, she is too disdainful; I know her spirits are as coy and wild As haggerds of the rock. URSULA But are you sure That Benedick loves Beatrice so entirely? HERO So says the prince and my new-trothed lord. URSULA And did they bid you tell her of it, madam? HERO They did entreat me to acquaint her of it; But I persuaded them, if they loved Benedick, To wish him wrestle with affection, And never to let Beatrice know of it. URSULA Why did you so? Doth not the gentleman Deserve as full as fortunate a bed As ever Beatrice shall couch upon? HERO O god of love! I know he doth deserve As much as may be yielded to a man: But Nature never framed a woman's heart Of prouder stuff than that of Beatrice; Disdain and scorn ride sparkling in her eyes, Misprising what they look on, and her wit Values itself so highly that to her All matter else seems weak: she cannot love, Nor take no shape nor project of affection, She is so self-endeared. URSULA Sure, I think so; And therefore certainly it were not good She knew his love, lest she make sport at it. HERO Why, you speak truth. I never yet saw man, How wise, how noble, young, how rarely featured, But she would spell him backward: if fair-faced, She would swear the gentleman should be her sister; If black, why, Nature, drawing of an antique, Made a foul blot; if tall, a lance ill-headed; If low, an agate very vilely cut; If speaking, why, a vane blown with all winds; If silent, why, a block moved with none. So turns she every man the wrong side out And never gives to truth and virtue that Which simpleness and merit purchaseth. URSULA Sure, sure, such carping is not commendable. HERO No, not to be so odd and from all fashions As Beatrice is, cannot be commendable: But who dare tell her so? If I should speak, She would mock me into air; O, she would laugh me Out of myself, press me to death with wit. Therefore let Benedick, like cover'd fire, Consume away in sighs, waste inwardly: It were a better death than die with mocks, Which is as bad as die with tickling. URSULA Yet tell her of it: hear what she will say. HERO No; rather I will go to Benedick And counsel him to fight against his passion. And, truly, I'll devise some honest slanders To stain my cousin with: one doth not know How much an ill word may empoison liking. URSULA O, do not do your cousin such a wrong. She cannot be so much without true judgment-- Having so swift and excellent a wit As she is prized to have--as to refuse So rare a gentleman as Signior Benedick. HERO He is the only man of Italy. Always excepted my dear Claudio. URSULA I pray you, be not angry with me, madam, Speaking my fancy: Signior Benedick, For shape, for bearing, argument and valour, Goes foremost in report through Italy. HERO Indeed, he hath an excellent good name. URSULA His excellence did earn it, ere he had it. When are you married, madam? HERO Why, every day, to-morrow. Come, go in: I'll show thee some attires, and have thy counsel Which is the best to furnish me to-morrow. URSULA She's limed, I warrant you: we have caught her, madam. HERO If it proves so, then loving goes by haps: Some Cupid kills with arrows, some with traps. Exeunt HERO and URSULA BEATRICE Coming forward What fire is in mine ears? Can this be true? Stand I condemn'd for pride and scorn so much? Contempt, farewell! and maiden pride, adieu! No glory lives behind the back of such. And, Benedick, love on; I will requite thee, Taming my wild heart to thy loving hand: If thou dost love, my kindness shall incite thee To bind our loves up in a holy band; For others say thou dost deserve, and I Believe it better than reportingly. Exit SCENE II. A room in LEONATO'S house Enter DON PEDRO, CLAUDIO, BENEDICK, and LEONATO DON PEDRO I do but stay till your marriage be consummate, and then go I toward Arragon. CLAUDIO I'll bring you thither, my lord, if you'll vouchsafe me. DON PEDRO Nay, that would be as great a soil in the new gloss of your marriage as to show a child his new coat and forbid him to wear it. I will only be bold with Benedick for his company; for, from the crown of his head to the sole of his foot, he is all mirth: he hath twice or thrice cut Cupid's bow-string and the little hangman dare not shoot at him; he hath a heart as sound as a bell and his tongue is the clapper, for what his heart thinks his tongue speaks. BENEDICK Gallants, I am not as I have been. LEONATO So say I methinks you are sadder. CLAUDIO I hope he be in love. DON PEDRO Hang him, truant! there's no true drop of blood in him, to be truly touched with love: if he be sad, he wants money. BENEDICK I have the toothache. DON PEDRO Draw it. BENEDICK Hang it! CLAUDIO You must hang it first, and draw it afterwards. DON PEDRO What! sigh for the toothache? LEONATO Where is but a humour or a worm. BENEDICK Well, every one can master a grief but he that has it. CLAUDIO Yet say I, he is in love. DON PEDRO There is no appearance of fancy in him, unless it be a fancy that he hath to strange disguises; as, to be a Dutchman today, a Frenchman to-morrow, or in the shape of two countries at once, as, a German from the waist downward, all slops, and a Spaniard from the hip upward, no doublet. Unless he have a fancy to this foolery, as it appears he hath, he is no fool for fancy, as you would have it appear he is. CLAUDIO If he be not in love with some woman, there is no believing old signs: a' brushes his hat o' mornings; what should that bode? DON PEDRO Hath any man seen him at the barber's? CLAUDIO No, but the barber's man hath been seen with him, and the old ornament of his cheek hath already stuffed tennis-balls. LEONATO Indeed, he looks younger than he did, by the loss of a beard. DON PEDRO Nay, a' rubs himself with civet: can you smell him out by that? CLAUDIO That's as much as to say, the sweet youth's in love. DON PEDRO The greatest note of it is his melancholy. CLAUDIO And when was he wont to wash his face? DON PEDRO Yea, or to paint himself? for the which, I hear what they say of him. CLAUDIO Nay, but his jesting spirit; which is now crept into a lute-string and now governed by stops. DON PEDRO Indeed, that tells a heavy tale for him: conclude, conclude he is in love. CLAUDIO Nay, but I know who loves him. DON PEDRO That would I know too: I warrant, one that knows him not. CLAUDIO Yes, and his ill conditions; and, in despite of all, dies for him. DON PEDRO She shall be buried with her face upwards. BENEDICK Yet is this no charm for the toothache. Old signior, walk aside with me: I have studied eight or nine wise words to speak to you, which these hobby-horses must not hear. Exeunt BENEDICK and LEONATO DON PEDRO For my life, to break with him about Beatrice. CLAUDIO 'Tis even so. Hero and Margaret have by this played their parts with Beatrice; and then the two bears will not bite one another when they meet. Enter DON JOHN DON JOHN My lord and brother, God save you! DON PEDRO Good den, brother. DON JOHN If your leisure served, I would speak with you. DON PEDRO In private? DON JOHN If it please you: yet Count Claudio may hear; for what I would speak of concerns him. DON PEDRO What's the matter? DON JOHN To CLAUDIO Means your lordship to be married to-morrow? DON PEDRO You know he does. DON JOHN I know not that, when he knows what I know. CLAUDIO If there be any impediment, I pray you discover it. DON JOHN You may think I love you not: let that appear hereafter, and aim better at me by that I now will manifest. For my brother, I think he holds you well, and in dearness of heart hath holp to effect your ensuing marriage;--surely suit ill spent and labour ill bestowed. DON PEDRO Why, what's the matter? DON JOHN I came hither to tell you; and, circumstances shortened, for she has been too long a talking of, the lady is disloyal. CLAUDIO Who, Hero? DON PEDRO Even she; Leonato's Hero, your Hero, every man's Hero: CLAUDIO Disloyal? DON JOHN The word is too good to paint out her wickedness; I could say she were worse: think you of a worse title, and I will fit her to it. Wonder not till further warrant: go but with me to-night, you shall see her chamber-window entered, even the night before her wedding-day: if you love her then, to-morrow wed her; but it would better fit your honour to change your mind. CLAUDIO May this be so? DON PEDRO I will not think it. DON JOHN If you dare not trust that you see, confess not that you know: if you will follow me, I will show you enough; and when you have seen more and heard more, proceed accordingly. CLAUDIO If I see any thing to-night why I should not marry her to-morrow in the congregation, where I should wed, there will I shame her. DON PEDRO And, as I wooed for thee to obtain her, I will join with thee to disgrace her. DON JOHN I will disparage her no farther till you are my witnesses: bear it coldly but till midnight, and let the issue show itself. DON PEDRO O day untowardly turned! CLAUDIO O mischief strangely thwarting! DON JOHN O plague right well prevented! so will you say when you have seen the sequel. Exeunt SCENE III. A street. Enter DOGBERRY and VERGES with the Watch DOGBERRY Are you good men and true? VERGES Yea, or else it were pity but they should suffer salvation, body and soul. DOGBERRY Nay, that were a punishment too good for them, if they should have any allegiance in them, being chosen for the prince's watch. VERGES Well, give them their charge, neighbour Dogberry. DOGBERRY First, who think you the most desertless man to be constable? First Watchman Hugh Otecake, sir, or George Seacole; for they can write and read. DOGBERRY Come hither, neighbour Seacole. God hath blessed you with a good name: to be a well-favoured man is the gift of fortune; but to write and read comes by nature. Second Watchman Both which, master constable,-- DOGBERRY You have: I knew it would be your answer. Well, for your favour, sir, why, give God thanks, and make no boast of it; and for your writing and reading, let that appear when there is no need of such vanity. You are thought here to be the most senseless and fit man for the constable of the watch; therefore bear you the lantern. This is your charge: you shall comprehend all vagrom men; you are to bid any man stand, in the prince's name. Second Watchman How if a' will not stand? DOGBERRY Why, then, take no note of him, but let him go; and presently call the rest of the watch together and thank God you are rid of a knave. VERGES If he will not stand when he is bidden, he is none of the prince's subjects. DOGBERRY True, and they are to meddle with none but the prince's subjects. You shall also make no noise in the streets; for, for the watch to babble and to talk is most tolerable and not to be endured. Watchman We will rather sleep than talk: we know what belongs to a watch. DOGBERRY Why, you speak like an ancient and most quiet watchman; for I cannot see how sleeping should offend: only, have a care that your bills be not stolen. Well, you are to call at all the ale-houses, and bid those that are drunk get them to bed. Watchman How if they will not? DOGBERRY Why, then, let them alone till they are sober: if they make you not then the better answer, you may say they are not the men you took them for. Watchman Well, sir. DOGBERRY If you meet a thief, you may suspect him, by virtue of your office, to be no true man; and, for such kind of men, the less you meddle or make with them, why the more is for your honesty. Watchman If we know him to be a thief, shall we not lay hands on him? DOGBERRY Truly, by your office, you may; but I think they that touch pitch will be defiled: the most peaceable way for you, if you do take a thief, is to let him show himself what he is and steal out of your company. VERGES You have been always called a merciful man, partner. DOGBERRY Truly, I would not hang a dog by my will, much more a man who hath any honesty in him. VERGES If you hear a child cry in the night, you must call to the nurse and bid her still it. Watchman How if the nurse be asleep and will not hear us? DOGBERRY Why, then, depart in peace, and let the child wake her with crying; for the ewe that will not hear her lamb when it baes will never answer a calf when he bleats. VERGES 'Tis very true. DOGBERRY This is the end of the charge:--you, constable, are to present the prince's own person: if you meet the prince in the night, you may stay him. VERGES Nay, by'r our lady, that I think a' cannot. DOGBERRY Five shillings to one on't, with any man that knows the statutes, he may stay him: marry, not without the prince be willing; for, indeed, the watch ought to offend no man; and it is an offence to stay a man against his will. VERGES By'r lady, I think it be so. DOGBERRY Ha, ha, ha! Well, masters, good night: an there be any matter of weight chances, call up me: keep your fellows' counsels and your own; and good night. Come, neighbour. Watchman Well, masters, we hear our charge: let us go sit here upon the church-bench till two, and then all to bed. DOGBERRY One word more, honest neighbours. I pray you watch about Signior Leonato's door; for the wedding being there to-morrow, there is a great coil to-night. Adieu: be vigitant, I beseech you. Exeunt DOGBERRY and VERGES Enter BORACHIO and CONRADE BORACHIO What Conrade! Watchman Aside Peace! stir not. BORACHIO Conrade, I say! CONRADE Here, man; I am at thy elbow. BORACHIO Mass, and my elbow itched; I thought there would a scab follow. CONRADE I will owe thee an answer for that: and now forward with thy tale. BORACHIO Stand thee close, then, under this pent-house, for it drizzles rain; and I will, like a true drunkard, utter all to thee. Watchman Aside Some treason, masters: yet stand close. BORACHIO Therefore know I have earned of Don John a thousand ducats. CONRADE Is it possible that any villany should be so dear? BORACHIO Thou shouldst rather ask if it were possible any villany should be so rich; for when rich villains have need of poor ones, poor ones may make what price they will. CONRADE I wonder at it. BORACHIO That shows thou art unconfirmed. Thou knowest that the fashion of a doublet, or a hat, or a cloak, is nothing to a man. CONRADE Yes, it is apparel. BORACHIO I mean, the fashion. CONRADE Yes, the fashion is the fashion. BORACHIO Tush! I may as well say the fool's the fool. But seest thou not what a deformed thief this fashion is? Watchman Aside I know that Deformed; a' has been a vile thief this seven year; a' goes up and down like a gentleman: I remember his name. BORACHIO Didst thou not hear somebody? CONRADE No; 'twas the vane on the house. BORACHIO Seest thou not, I say, what a deformed thief this fashion is? how giddily a' turns about all the hot bloods between fourteen and five-and-thirty? sometimes fashioning them like Pharaoh's soldiers in the reeky painting, sometime like god Bel's priests in the old church-window, sometime like the shaven Hercules in the smirched worm-eaten tapestry, where his codpiece seems as massy as his club? CONRADE All this I see; and I see that the fashion wears out more apparel than the man. But art not thou thyself giddy with the fashion too, that thou hast shifted out of thy tale into telling me of the fashion? BORACHIO Not so, neither: but know that I have to-night wooed Margaret, the Lady Hero's gentlewoman, by the name of Hero: she leans me out at her mistress' chamber-window, bids me a thousand times good night,--I tell this tale vilely:--I should first tell thee how the prince, Claudio and my master, planted and placed and possessed by my master Don John, saw afar off in the orchard this amiable encounter. CONRADE And thought they Margaret was Hero? BORACHIO Two of them did, the prince and Claudio; but the devil my master knew she was Margaret; and partly by his oaths, which first possessed them, partly by the dark night, which did deceive them, but chiefly by my villany, which did confirm any slander that Don John had made, away went Claudio enraged; swore he would meet her, as he was appointed, next morning at the temple, and there, before the whole congregation, shame her with what he saw o'er night and send her home again without a husband. First Watchman We charge you, in the prince's name, stand! Second Watchman Call up the right master constable. We have here recovered the most dangerous piece of lechery that ever was known in the commonwealth. First Watchman And one Deformed is one of them: I know him; a' wears a lock. CONRADE Masters, masters,-- Second Watchman You'll be made bring Deformed forth, I warrant you. CONRADE Masters,-- First Watchman Never speak: we charge you let us obey you to go with us. BORACHIO We are like to prove a goodly commodity, being taken up of these men's bills. CONRADE A commodity in question, I warrant you. Come, we'll obey you. Exeunt SCENE IV. HERO's apartment. Enter HERO, MARGARET, and URSULA HERO Good Ursula, wake my cousin Beatrice, and desire her to rise. URSULA I will, lady. HERO And bid her come hither. URSULA Well. Exit MARGARET Troth, I think your other rabato were better. HERO No, pray thee, good Meg, I'll wear this. MARGARET By my troth, 's not so good; and I warrant your cousin will say so. HERO My cousin's a fool, and thou art another: I'll wear none but this. MARGARET I like the new tire within excellently, if the hair were a thought browner; and your gown's a most rare fashion, i' faith. I saw the Duchess of Milan's gown that they praise so. HERO O, that exceeds, they say. MARGARET By my troth, 's but a night-gown in respect of yours: cloth o' gold, and cuts, and laced with silver, set with pearls, down sleeves, side sleeves, and skirts, round underborne with a bluish tinsel: but for a fine, quaint, graceful and excellent fashion, yours is worth ten on 't. HERO God give me joy to wear it! for my heart is exceeding heavy. MARGARET 'Twill be heavier soon by the weight of a man. HERO Fie upon thee! art not ashamed? MARGARET Of what, lady? of speaking honourably? Is not marriage honourable in a beggar? Is not your lord honourable without marriage? I think you would have me say, 'saving your reverence, a husband:' and bad thinking do not wrest true speaking, I'll offend nobody: is there any harm in 'the heavier for a husband'? None, I think, and it be the right husband and the right wife; otherwise 'tis light, and not heavy: ask my Lady Beatrice else; here she comes. Enter BEATRICE HERO Good morrow, coz. BEATRICE Good morrow, sweet Hero. HERO Why how now? do you speak in the sick tune? BEATRICE I am out of all other tune, methinks. MARGARET Clap's into 'Light o' love;' that goes without a burden: do you sing it, and I'll dance it. BEATRICE Ye light o' love, with your heels! then, if your husband have stables enough, you'll see he shall lack no barns. MARGARET O illegitimate construction! I scorn that with my heels. BEATRICE 'Tis almost five o'clock, cousin; tis time you were ready. By my troth, I am exceeding ill: heigh-ho! MARGARET For a hawk, a horse, or a husband? BEATRICE For the letter that begins them all, H. MARGARET Well, and you be not turned Turk, there's no more sailing by the star. BEATRICE What means the fool, trow? MARGARET Nothing I; but God send every one their heart's desire! HERO These gloves the count sent me; they are an excellent perfume. BEATRICE I am stuffed, cousin; I cannot smell. MARGARET A maid, and stuffed! there's goodly catching of cold. BEATRICE O, God help me! God help me! how long have you professed apprehension? MARGARET Even since you left it. Doth not my wit become me rarely? BEATRICE It is not seen enough, you should wear it in your cap. By my troth, I am sick. MARGARET Get you some of this distilled Carduus Benedictus, and lay it to your heart: it is the only thing for a qualm. HERO There thou prickest her with a thistle. BEATRICE Benedictus! why Benedictus? you have some moral in this Benedictus. MARGARET Moral! no, by my troth, I have no moral meaning; I meant, plain holy-thistle. You may think perchance that I think you are in love: nay, by'r lady, I am not such a fool to think what I list, nor I list not to think what I can, nor indeed I cannot think, if I would think my heart out of thinking, that you are in love or that you will be in love or that you can be in love. Yet Benedick was such another, and now is he become a man: he swore he would never marry, and yet now, in despite of his heart, he eats his meat without grudging: and how you may be converted I know not, but methinks you look with your eyes as other women do. BEATRICE What pace is this that thy tongue keeps? MARGARET Not a false gallop. Re-enter URSULA URSULA Madam, withdraw: the prince, the count, Signior Benedick, Don John, and all the gallants of the town, are come to fetch you to church. HERO Help to dress me, good coz, good Meg, good Ursula. Exeunt SCENE V. Another room in LEONATO'S house. Enter LEONATO, with DOGBERRY and VERGES LEONATO What would you with me, honest neighbour? DOGBERRY Marry, sir, I would have some confidence with you that decerns you nearly. LEONATO Brief, I pray you; for you see it is a busy time with me. DOGBERRY Marry, this it is, sir. VERGES Yes, in truth it is, sir. LEONATO What is it, my good friends? DOGBERRY Goodman Verges, sir, speaks a little off the matter: an old man, sir, and his wits are not so blunt as, God help, I would desire they were; but, in faith, honest as the skin between his brows. VERGES Yes, I thank God I am as honest as any man living that is an old man and no honester than I. DOGBERRY Comparisons are odorous: palabras, neighbour Verges. LEONATO Neighbours, you are tedious. DOGBERRY It pleases your worship to say so, but we are the poor duke's officers; but truly, for mine own part, if I were as tedious as a king, I could find it in my heart to bestow it all of your worship. LEONATO All thy tediousness on me, ah? DOGBERRY Yea, an 'twere a thousand pound more than 'tis; for I hear as good exclamation on your worship as of any man in the city; and though I be but a poor man, I am glad to hear it. VERGES And so am I. LEONATO I would fain know what you have to say. VERGES Marry, sir, our watch to-night, excepting your worship's presence, ha' ta'en a couple of as arrant knaves as any in Messina. DOGBERRY A good old man, sir; he will be talking: as they say, when the age is in, the wit is out: God help us! it is a world to see. Well said, i' faith, neighbour Verges: well, God's a good man; an two men ride of a horse, one must ride behind. An honest soul, i' faith, sir; by my troth he is, as ever broke bread; but God is to be worshipped; all men are not alike; alas, good neighbour! LEONATO Indeed, neighbour, he comes too short of you. DOGBERRY Gifts that God gives. LEONATO I must leave you. DOGBERRY One word, sir: our watch, sir, have indeed comprehended two aspicious persons, and we would have them this morning examined before your worship. LEONATO Take their examination yourself and bring it me: I am now in great haste, as it may appear unto you. DOGBERRY It shall be suffigance. LEONATO Drink some wine ere you go: fare you well. Enter a Messenger Messenger My lord, they stay for you to give your daughter to her husband. LEONATO I'll wait upon them: I am ready. Exeunt LEONATO and Messenger DOGBERRY Go, good partner, go, get you to Francis Seacole; bid him bring his pen and inkhorn to the gaol: we are now to examination these men. VERGES And we must do it wisely. DOGBERRY We will spare for no wit, I warrant you; here's that shall drive some of them to a non-come: only get the learned writer to set down our excommunication and meet me at the gaol. Exeunt ACT IV SCENE I. A church. Enter DON PEDRO, DON JOHN, LEONATO, FRIAR FRANCIS, CLAUDIO, BENEDICK, HERO, BEATRICE, and Attendants LEONATO Come, Friar Francis, be brief; only to the plain form of marriage, and you shall recount their particular duties afterwards. FRIAR FRANCIS You come hither, my lord, to marry this lady. CLAUDIO No. LEONATO To be married to her: friar, you come to marry her. FRIAR FRANCIS Lady, you come hither to be married to this count. HERO I do. FRIAR FRANCIS If either of you know any inward impediment why you should not be conjoined, charge you, on your souls, to utter it. CLAUDIO Know you any, Hero? HERO None, my lord. FRIAR FRANCIS Know you any, count? LEONATO I dare make his answer, none. CLAUDIO O, what men dare do! what men may do! what men daily do, not knowing what they do! BENEDICK How now! interjections? Why, then, some be of laughing, as, ah, ha, he! CLAUDIO Stand thee by, friar. Father, by your leave: Will you with free and unconstrained soul Give me this maid, your daughter? LEONATO As freely, son, as God did give her me. CLAUDIO And what have I to give you back, whose worth May counterpoise this rich and precious gift? DON PEDRO Nothing, unless you render her again. CLAUDIO Sweet prince, you learn me noble thankfulness. There, Leonato, take her back again: Give not this rotten orange to your friend; She's but the sign and semblance of her honour. Behold how like a maid she blushes here! O, what authority and show of truth Can cunning sin cover itself withal! Comes not that blood as modest evidence To witness simple virtue? Would you not swear, All you that see her, that she were a maid, By these exterior shows? But she is none: She knows the heat of a luxurious bed; Her blush is guiltiness, not modesty. LEONATO What do you mean, my lord? CLAUDIO Not to be married, Not to knit my soul to an approved wanton. LEONATO Dear my lord, if you, in your own proof, Have vanquish'd the resistance of her youth, And made defeat of her virginity,-- CLAUDIO I know what you would say: if I have known her, You will say she did embrace me as a husband, And so extenuate the 'forehand sin: No, Leonato, I never tempted her with word too large; But, as a brother to his sister, show'd Bashful sincerity and comely love. HERO And seem'd I ever otherwise to you? CLAUDIO Out on thee! Seeming! I will write against it: You seem to me as Dian in her orb, As chaste as is the bud ere it be blown; But you are more intemperate in your blood Than Venus, or those pamper'd animals That rage in savage sensuality. HERO Is my lord well, that he doth speak so wide? LEONATO Sweet prince, why speak not you? DON PEDRO What should I speak? I stand dishonour'd, that have gone about To link my dear friend to a common stale. LEONATO Are these things spoken, or do I but dream? DON JOHN Sir, they are spoken, and these things are true. BENEDICK This looks not like a nuptial. HERO True! O God! CLAUDIO Leonato, stand I here? Is this the prince? is this the prince's brother? Is this face Hero's? are our eyes our own? LEONATO All this is so: but what of this, my lord? CLAUDIO Let me but move one question to your daughter; And, by that fatherly and kindly power That you have in her, bid her answer truly. LEONATO I charge thee do so, as thou art my child. HERO O, God defend me! how am I beset! What kind of catechising call you this? CLAUDIO To make you answer truly to your name. HERO Is it not Hero? Who can blot that name With any just reproach? CLAUDIO Marry, that can Hero; Hero itself can blot out Hero's virtue. What man was he talk'd with you yesternight Out at your window betwixt twelve and one? Now, if you are a maid, answer to this. HERO I talk'd with no man at that hour, my lord. DON PEDRO Why, then are you no maiden. Leonato, I am sorry you must hear: upon mine honour, Myself, my brother and this grieved count Did see her, hear her, at that hour last night Talk with a ruffian at her chamber-window Who hath indeed, most like a liberal villain, Confess'd the vile encounters they have had A thousand times in secret. DON JOHN Fie, fie! they are not to be named, my lord, Not to be spoke of; There is not chastity enough in language Without offence to utter them. Thus, pretty lady, I am sorry for thy much misgovernment. CLAUDIO O Hero, what a Hero hadst thou been, If half thy outward graces had been placed About thy thoughts and counsels of thy heart! But fare thee well, most foul, most fair! farewell, Thou pure impiety and impious purity! For thee I'll lock up all the gates of love, And on my eyelids shall conjecture hang, To turn all beauty into thoughts of harm, And never shall it more be gracious. LEONATO Hath no man's dagger here a point for me? HERO swoons BEATRICE Why, how now, cousin! wherefore sink you down? DON JOHN Come, let us go. These things, come thus to light, Smother her spirits up. Exeunt DON PEDRO, DON JOHN, and CLAUDIO BENEDICK How doth the lady? BEATRICE Dead, I think. Help, uncle! Hero! why, Hero! Uncle! Signior Benedick! Friar! LEONATO O Fate! take not away thy heavy hand. Death is the fairest cover for her shame That may be wish'd for. BEATRICE How now, cousin Hero! FRIAR FRANCIS Have comfort, lady. LEONATO Dost thou look up? FRIAR FRANCIS Yea, wherefore should she not? LEONATO Wherefore! Why, doth not every earthly thing Cry shame upon her? Could she here deny The story that is printed in her blood? Do not live, Hero; do not ope thine eyes: For, did I think thou wouldst not quickly die, Thought I thy spirits were stronger than thy shames, Myself would, on the rearward of reproaches, Strike at thy life. Grieved I, I had but one? Chid I for that at frugal nature's frame? O, one too much by thee! Why had I one? Why ever wast thou lovely in my eyes? Why had I not with charitable hand Took up a beggar's issue at my gates, Who smirch'd thus and mired with infamy, I might have said 'No part of it is mine; This shame derives itself from unknown loins'? But mine and mine I loved and mine I praised And mine that I was proud on, mine so much That I myself was to myself not mine, Valuing of her,--why, she, O, she is fallen Into a pit of ink, that the wide sea Hath drops too few to wash her clean again And salt too little which may season give To her foul-tainted flesh! BENEDICK Sir, sir, be patient. For my part, I am so attired in wonder, I know not what to say. BEATRICE O, on my soul, my cousin is belied! BENEDICK Lady, were you her bedfellow last night? BEATRICE No, truly not; although, until last night, I have this twelvemonth been her bedfellow. LEONATO Confirm'd, confirm'd! O, that is stronger made Which was before barr'd up with ribs of iron! Would the two princes lie, and Claudio lie, Who loved her so, that, speaking of her foulness, Wash'd it with tears? Hence from her! let her die. FRIAR FRANCIS Hear me a little; for I have only been Silent so long and given way unto This course of fortune By noting of the lady. I have mark'd A thousand blushing apparitions To start into her face, a thousand innocent shames In angel whiteness beat away those blushes; And in her eye there hath appear'd a fire, To burn the errors that these princes hold Against her maiden truth. Call me a fool; Trust not my reading nor my observations, Which with experimental seal doth warrant The tenor of my book; trust not my age, My reverence, calling, nor divinity, If this sweet lady lie not guiltless here Under some biting error. LEONATO Friar, it cannot be. Thou seest that all the grace that she hath left Is that she will not add to her damnation A sin of perjury; she not denies it: Why seek'st thou then to cover with excuse That which appears in proper nakedness? FRIAR FRANCIS Lady, what man is he you are accused of? HERO They know that do accuse me; I know none: If I know more of any man alive Than that which maiden modesty doth warrant, Let all my sins lack mercy! O my father, Prove you that any man with me conversed At hours unmeet, or that I yesternight Maintain'd the change of words with any creature, Refuse me, hate me, torture me to death! FRIAR FRANCIS There is some strange misprision in the princes. BENEDICK Two of them have the very bent of honour; And if their wisdoms be misled in this, The practise of it lives in John the bastard, Whose spirits toil in frame of villanies. LEONATO I know not. If they speak but truth of her, These hands shall tear her; if they wrong her honour, The proudest of them shall well hear of it. Time hath not yet so dried this blood of mine, Nor age so eat up my invention, Nor fortune made such havoc of my means, Nor my bad life reft me so much of friends, But they shall find, awaked in such a kind, Both strength of limb and policy of mind, Ability in means and choice of friends, To quit me of them throughly. FRIAR FRANCIS Pause awhile, And let my counsel sway you in this case. Your daughter here the princes left for dead: Let her awhile be secretly kept in, And publish it that she is dead indeed; Maintain a mourning ostentation And on your family's old monument Hang mournful epitaphs and do all rites That appertain unto a burial. LEONATO What shall become of this? what will this do? FRIAR FRANCIS Marry, this well carried shall on her behalf Change slander to remorse; that is some good: But not for that dream I on this strange course, But on this travail look for greater birth. She dying, as it must so be maintain'd, Upon the instant that she was accused, Shall be lamented, pitied and excused Of every hearer: for it so falls out That what we have we prize not to the worth Whiles we enjoy it, but being lack'd and lost, Why, then we rack the value, then we find The virtue that possession would not show us Whiles it was ours. So will it fare with Claudio: When he shall hear she died upon his words, The idea of her life shall sweetly creep Into his study of imagination, And every lovely organ of her life Shall come apparell'd in more precious habit, More moving-delicate and full of life, Into the eye and prospect of his soul, Than when she lived indeed; then shall he mourn, If ever love had interest in his liver, And wish he had not so accused her, No, though he thought his accusation true. Let this be so, and doubt not but success Will fashion the event in better shape Than I can lay it down in likelihood. But if all aim but this be levell'd false, The supposition of the lady's death Will quench the wonder of her infamy: And if it sort not well, you may conceal her, As best befits her wounded reputation, In some reclusive and religious life, Out of all eyes, tongues, minds and injuries. BENEDICK Signior Leonato, let the friar advise you: And though you know my inwardness and love Is very much unto the prince and Claudio, Yet, by mine honour, I will deal in this As secretly and justly as your soul Should with your body. LEONATO Being that I flow in grief, The smallest twine may lead me. FRIAR FRANCIS 'Tis well consented: presently away; For to strange sores strangely they strain the cure. Come, lady, die to live: this wedding-day Perhaps is but prolong'd: have patience and endure. Exeunt all but BENEDICK and BEATRICE BENEDICK Lady Beatrice, have you wept all this while? BEATRICE Yea, and I will weep a while longer. BENEDICK I will not desire that. BEATRICE You have no reason; I do it freely. BENEDICK Surely I do believe your fair cousin is wronged. BEATRICE Ah, how much might the man deserve of me that would right her! BENEDICK Is there any way to show such friendship? BEATRICE A very even way, but no such friend. BENEDICK May a man do it? BEATRICE It is a man's office, but not yours. BENEDICK I do love nothing in the world so well as you: is not that strange? BEATRICE As strange as the thing I know not. It were as possible for me to say I loved nothing so well as you: but believe me not; and yet I lie not; I confess nothing, nor I deny nothing. I am sorry for my cousin. BENEDICK By my sword, Beatrice, thou lovest me. BEATRICE Do not swear, and eat it. BENEDICK I will swear by it that you love me; and I will make him eat it that says I love not you. BEATRICE Will you not eat your word? BENEDICK With no sauce that can be devised to it. I protest I love thee. BEATRICE Why, then, God forgive me! BENEDICK What offence, sweet Beatrice? BEATRICE You have stayed me in a happy hour: I was about to protest I loved you. BENEDICK And do it with all thy heart. BEATRICE I love you with so much of my heart that none is left to protest. BENEDICK Come, bid me do any thing for thee. BEATRICE Kill Claudio. BENEDICK Ha! not for the wide world. BEATRICE You kill me to deny it. Farewell. BENEDICK Tarry, sweet Beatrice. BEATRICE I am gone, though I am here: there is no love in you: nay, I pray you, let me go. BENEDICK Beatrice,-- BEATRICE In faith, I will go. BENEDICK We'll be friends first. BEATRICE You dare easier be friends with me than fight with mine enemy. BENEDICK Is Claudio thine enemy? BEATRICE Is he not approved in the height a villain, that hath slandered, scorned, dishonoured my kinswoman? O that I were a man! What, bear her in hand until they come to take hands; and then, with public accusation, uncovered slander, unmitigated rancour, --O God, that I were a man! I would eat his heart in the market-place. BENEDICK Hear me, Beatrice,-- BEATRICE Talk with a man out at a window! A proper saying! BENEDICK Nay, but, Beatrice,-- BEATRICE Sweet Hero! She is wronged, she is slandered, she is undone. BENEDICK Beat-- BEATRICE Princes and counties! Surely, a princely testimony, a goodly count, Count Comfect; a sweet gallant, surely! O that I were a man for his sake! or that I had any friend would be a man for my sake! But manhood is melted into courtesies, valour into compliment, and men are only turned into tongue, and trim ones too: he is now as valiant as Hercules that only tells a lie and swears it. I cannot be a man with wishing, therefore I will die a woman with grieving. BENEDICK Tarry, good Beatrice. By this hand, I love thee. BEATRICE Use it for my love some other way than swearing by it. BENEDICK Think you in your soul the Count Claudio hath wronged Hero? BEATRICE Yea, as sure as I have a thought or a soul. BENEDICK Enough, I am engaged; I will challenge him. I will kiss your hand, and so I leave you. By this hand, Claudio shall render me a dear account. As you hear of me, so think of me. Go, comfort your cousin: I must say she is dead: and so, farewell. Exeunt SCENE II. A prison. Enter DOGBERRY, VERGES, and Sexton, in gowns; and the Watch, with CONRADE and BORACHIO DOGBERRY Is our whole dissembly appeared? VERGES O, a stool and a cushion for the sexton. Sexton Which be the malefactors? DOGBERRY Marry, that am I and my partner. VERGES Nay, that's certain; we have the exhibition to examine. Sexton But which are the offenders that are to be examined? let them come before master constable. DOGBERRY Yea, marry, let them come before me. What is your name, friend? BORACHIO Borachio. DOGBERRY Pray, write down, Borachio. Yours, sirrah? CONRADE I am a gentleman, sir, and my name is Conrade. DOGBERRY Write down, master gentleman Conrade. Masters, do you serve God? CONRADE BORACHIO Yea, sir, we hope. DOGBERRY Write down, that they hope they serve God: and write God first; for God defend but God should go before such villains! Masters, it is proved already that you are little better than false knaves; and it will go near to be thought so shortly. How answer you for yourselves? CONRADE Marry, sir, we say we are none. DOGBERRY A marvellous witty fellow, I assure you: but I will go about with him. Come you hither, sirrah; a word in your ear: sir, I say to you, it is thought you are false knaves. BORACHIO Sir, I say to you we are none. DOGBERRY Well, stand aside. 'Fore God, they are both in a tale. Have you writ down, that they are none? Sexton Master constable, you go not the way to examine: you must call forth the watch that are their accusers. DOGBERRY Yea, marry, that's the eftest way. Let the watch come forth. Masters, I charge you, in the prince's name, accuse these men. First Watchman This man said, sir, that Don John, the prince's brother, was a villain. DOGBERRY Write down Prince John a villain. Why, this is flat perjury, to call a prince's brother villain. BORACHIO Master constable,-- DOGBERRY Pray thee, fellow, peace: I do not like thy look, I promise thee. Sexton What heard you him say else? Second Watchman Marry, that he had received a thousand ducats of Don John for accusing the Lady Hero wrongfully. DOGBERRY Flat burglary as ever was committed. VERGES Yea, by mass, that it is. Sexton What else, fellow? First Watchman And that Count Claudio did mean, upon his words, to disgrace Hero before the whole assembly. and not marry her. DOGBERRY O villain! thou wilt be condemned into everlasting redemption for this. Sexton What else? Watchman This is all. Sexton And this is more, masters, than you can deny. Prince John is this morning secretly stolen away; Hero was in this manner accused, in this very manner refused, and upon the grief of this suddenly died. Master constable, let these men be bound, and brought to Leonato's: I will go before and show him their examination. Exit DOGBERRY Come, let them be opinioned. VERGES Let them be in the hands-- CONRADE Off, coxcomb! DOGBERRY God's my life, where's the sexton? let him write down the prince's officer coxcomb. Come, bind them. Thou naughty varlet! CONRADE Away! you are an ass, you are an ass. DOGBERRY Dost thou not suspect my place? dost thou not suspect my years? O that he were here to write me down an ass! But, masters, remember that I am an ass; though it be not written down, yet forget not that I am an ass. No, thou villain, thou art full of piety, as shall be proved upon thee by good witness. I am a wise fellow, and, which is more, an officer, and, which is more, a householder, and, which is more, as pretty a piece of flesh as any is in Messina, and one that knows the law, go to; and a rich fellow enough, go to; and a fellow that hath had losses, and one that hath two gowns and every thing handsome about him. Bring him away. O that I had been writ down an ass! Exeunt ACT V SCENE I. Before LEONATO'S house. Enter LEONATO and ANTONIO ANTONIO If you go on thus, you will kill yourself: And 'tis not wisdom thus to second grief Against yourself. LEONATO I pray thee, cease thy counsel, Which falls into mine ears as profitless As water in a sieve: give not me counsel; Nor let no comforter delight mine ear But such a one whose wrongs do suit with mine. Bring me a father that so loved his child, Whose joy of her is overwhelm'd like mine, And bid him speak of patience; Measure his woe the length and breadth of mine And let it answer every strain for strain, As thus for thus and such a grief for such, In every lineament, branch, shape, and form: If such a one will smile and stroke his beard, Bid sorrow wag, cry 'hem!' when he should groan, Patch grief with proverbs, make misfortune drunk With candle-wasters; bring him yet to me, And I of him will gather patience. But there is no such man: for, brother, men Can counsel and speak comfort to that grief Which they themselves not feel; but, tasting it, Their counsel turns to passion, which before Would give preceptial medicine to rage, Fetter strong madness in a silken thread, Charm ache with air and agony with words: No, no; 'tis all men's office to speak patience To those that wring under the load of sorrow, But no man's virtue nor sufficiency To be so moral when he shall endure The like himself. Therefore give me no counsel: My griefs cry louder than advertisement. ANTONIO Therein do men from children nothing differ. LEONATO I pray thee, peace. I will be flesh and blood; For there was never yet philosopher That could endure the toothache patiently, However they have writ the style of gods And made a push at chance and sufferance. ANTONIO Yet bend not all the harm upon yourself; Make those that do offend you suffer too. LEONATO There thou speak'st reason: nay, I will do so. My soul doth tell me Hero is belied; And that shall Claudio know; so shall the prince And all of them that thus dishonour her. ANTONIO Here comes the prince and Claudio hastily. Enter DON PEDRO and CLAUDIO DON PEDRO Good den, good den. CLAUDIO Good day to both of you. LEONATO Hear you. my lords,-- DON PEDRO We have some haste, Leonato. LEONATO Some haste, my lord! well, fare you well, my lord: Are you so hasty now? well, all is one. DON PEDRO Nay, do not quarrel with us, good old man. ANTONIO If he could right himself with quarreling, Some of us would lie low. CLAUDIO Who wrongs him? LEONATO Marry, thou dost wrong me; thou dissembler, thou:-- Nay, never lay thy hand upon thy sword; I fear thee not. CLAUDIO Marry, beshrew my hand, If it should give your age such cause of fear: In faith, my hand meant nothing to my sword. LEONATO Tush, tush, man; never fleer and jest at me: I speak not like a dotard nor a fool, As under privilege of age to brag What I have done being young, or what would do Were I not old. Know, Claudio, to thy head, Thou hast so wrong'd mine innocent child and me That I am forced to lay my reverence by And, with grey hairs and bruise of many days, Do challenge thee to trial of a man. I say thou hast belied mine innocent child; Thy slander hath gone through and through her heart, And she lies buried with her ancestors; O, in a tomb where never scandal slept, Save this of hers, framed by thy villany! CLAUDIO My villany? LEONATO Thine, Claudio; thine, I say. DON PEDRO You say not right, old man. LEONATO My lord, my lord, I'll prove it on his body, if he dare, Despite his nice fence and his active practise, His May of youth and bloom of lustihood. CLAUDIO Away! I will not have to do with you. LEONATO Canst thou so daff me? Thou hast kill'd my child: If thou kill'st me, boy, thou shalt kill a man. ANTONIO He shall kill two of us, and men indeed: But that's no matter; let him kill one first; Win me and wear me; let him answer me. Come, follow me, boy; come, sir boy, come, follow me: Sir boy, I'll whip you from your foining fence; Nay, as I am a gentleman, I will. LEONATO Brother,-- ANTONIO Content yourself. God knows I loved my niece; And she is dead, slander'd to death by villains, That dare as well answer a man indeed As I dare take a serpent by the tongue: Boys, apes, braggarts, Jacks, milksops! LEONATO Brother Antony,-- ANTONIO Hold you content. What, man! I know them, yea, And what they weigh, even to the utmost scruple,-- Scrambling, out-facing, fashion-monging boys, That lie and cog and flout, deprave and slander, Go anticly, show outward hideousness, And speak off half a dozen dangerous words, How they might hurt their enemies, if they durst; And this is all. LEONATO But, brother Antony,-- ANTONIO Come, 'tis no matter: Do not you meddle; let me deal in this. DON PEDRO Gentlemen both, we will not wake your patience. My heart is sorry for your daughter's death: But, on my honour, she was charged with nothing But what was true and very full of proof. LEONATO My lord, my lord,-- DON PEDRO I will not hear you. LEONATO No? Come, brother; away! I will be heard. ANTONIO And shall, or some of us will smart for it. Exeunt LEONATO and ANTONIO DON PEDRO See, see; here comes the man we went to seek. Enter BENEDICK CLAUDIO Now, signior, what news? BENEDICK Good day, my lord. DON PEDRO Welcome, signior: you are almost come to part almost a fray. CLAUDIO We had like to have had our two noses snapped off with two old men without teeth. DON PEDRO Leonato and his brother. What thinkest thou? Had we fought, I doubt we should have been too young for them. BENEDICK In a false quarrel there is no true valour. I came to seek you both. CLAUDIO We have been up and down to seek thee; for we are high-proof melancholy and would fain have it beaten away. Wilt thou use thy wit? BENEDICK It is in my scabbard: shall I draw it? DON PEDRO Dost thou wear thy wit by thy side? CLAUDIO Never any did so, though very many have been beside their wit. I will bid thee draw, as we do the minstrels; draw, to pleasure us. DON PEDRO As I am an honest man, he looks pale. Art thou sick, or angry? CLAUDIO What, courage, man! What though care killed a cat, thou hast mettle enough in thee to kill care. BENEDICK Sir, I shall meet your wit in the career, and you charge it against me. I pray you choose another subject. CLAUDIO Nay, then, give him another staff: this last was broke cross. DON PEDRO By this light, he changes more and more: I think he be angry indeed. CLAUDIO If he be, he knows how to turn his girdle. BENEDICK Shall I speak a word in your ear? CLAUDIO God bless me from a challenge! BENEDICK Aside to CLAUDIO You are a villain; I jest not: I will make it good how you dare, with what you dare, and when you dare. Do me right, or I will protest your cowardice. You have killed a sweet lady, and her death shall fall heavy on you. Let me hear from you. CLAUDIO Well, I will meet you, so I may have good cheer. DON PEDRO What, a feast, a feast? CLAUDIO I' faith, I thank him; he hath bid me to a calf's head and a capon; the which if I do not carve most curiously, say my knife's naught. Shall I not find a woodcock too? BENEDICK Sir, your wit ambles well; it goes easily. DON PEDRO I'll tell thee how Beatrice praised thy wit the other day. I said, thou hadst a fine wit: 'True,' said she, 'a fine little one.' 'No,' said I, 'a great wit:' 'Right,' says she, 'a great gross one.' 'Nay,' said I, 'a good wit:' 'Just,' said she, 'it hurts nobody.' 'Nay,' said I, 'the gentleman is wise:' 'Certain,' said she, 'a wise gentleman.' 'Nay,' said I, 'he hath the tongues:' 'That I believe,' said she, 'for he swore a thing to me on Monday night, which he forswore on Tuesday morning; there's a double tongue; there's two tongues.' Thus did she, an hour together, transshape thy particular virtues: yet at last she concluded with a sigh, thou wast the properest man in Italy. CLAUDIO For the which she wept heartily and said she cared not. DON PEDRO Yea, that she did: but yet, for all that, an if she did not hate him deadly, she would love him dearly: the old man's daughter told us all. CLAUDIO All, all; and, moreover, God saw him when he was hid in the garden. DON PEDRO But when shall we set the savage bull's horns on the sensible Benedick's head? CLAUDIO Yea, and text underneath, 'Here dwells Benedick the married man'? BENEDICK Fare you well, boy: you know my mind. I will leave you now to your gossip-like humour: you break jests as braggarts do their blades, which God be thanked, hurt not. My lord, for your many courtesies I thank you: I must discontinue your company: your brother the bastard is fled from Messina: you have among you killed a sweet and innocent lady. For my Lord Lackbeard there, he and I shall meet: and, till then, peace be with him. Exit DON PEDRO He is in earnest. CLAUDIO In most profound earnest; and, I'll warrant you, for the love of Beatrice. DON PEDRO And hath challenged thee. CLAUDIO Most sincerely. DON PEDRO What a pretty thing man is when he goes in his doublet and hose and leaves off his wit! CLAUDIO He is then a giant to an ape; but then is an ape a doctor to such a man. DON PEDRO But, soft you, let me be: pluck up, my heart, and be sad. Did he not say, my brother was fled? Enter DOGBERRY, VERGES, and the Watch, with CONRADE and BORACHIO DOGBERRY Come you, sir: if justice cannot tame you, she shall ne'er weigh more reasons in her balance: nay, an you be a cursing hypocrite once, you must be looked to. DON PEDRO How now? two of my brother's men bound! Borachio one! CLAUDIO Hearken after their offence, my lord. DON PEDRO Officers, what offence have these men done? DOGBERRY Marry, sir, they have committed false report; moreover, they have spoken untruths; secondarily, they are slanders; sixth and lastly, they have belied a lady; thirdly, they have verified unjust things; and, to conclude, they are lying knaves. DON PEDRO First, I ask thee what they have done; thirdly, I ask thee what's their offence; sixth and lastly, why they are committed; and, to conclude, what you lay to their charge. CLAUDIO Rightly reasoned, and in his own division: and, by my troth, there's one meaning well suited. DON PEDRO Who have you offended, masters, that you are thus bound to your answer? this learned constable is too cunning to be understood: what's your offence? BORACHIO Sweet prince, let me go no farther to mine answer: do you hear me, and let this count kill me. I have deceived even your very eyes: what your wisdoms could not discover, these shallow fools have brought to light: who in the night overheard me confessing to this man how Don John your brother incensed me to slander the Lady Hero, how you were brought into the orchard and saw me court Margaret in Hero's garments, how you disgraced her, when you should marry her: my villany they have upon record; which I had rather seal with my death than repeat over to my shame. The lady is dead upon mine and my master's false accusation; and, briefly, I desire nothing but the reward of a villain. DON PEDRO Runs not this speech like iron through your blood? CLAUDIO I have drunk poison whiles he utter'd it. DON PEDRO But did my brother set thee on to this? BORACHIO Yea, and paid me richly for the practise of it. DON PEDRO He is composed and framed of treachery: And fled he is upon this villany. CLAUDIO Sweet Hero! now thy image doth appear In the rare semblance that I loved it first. DOGBERRY Come, bring away the plaintiffs: by this time our sexton hath reformed Signior Leonato of the matter: and, masters, do not forget to specify, when time and place shall serve, that I am an ass. VERGES Here, here comes master Signior Leonato, and the Sexton too. Re-enter LEONATO and ANTONIO, with the Sexton LEONATO Which is the villain? let me see his eyes, That, when I note another man like him, I may avoid him: which of these is he? BORACHIO If you would know your wronger, look on me. LEONATO Art thou the slave that with thy breath hast kill'd Mine innocent child? BORACHIO Yea, even I alone. LEONATO No, not so, villain; thou beliest thyself: Here stand a pair of honourable men; A third is fled, that had a hand in it. I thank you, princes, for my daughter's death: Record it with your high and worthy deeds: 'Twas bravely done, if you bethink you of it. CLAUDIO I know not how to pray your patience; Yet I must speak. Choose your revenge yourself; Impose me to what penance your invention Can lay upon my sin: yet sinn'd I not But in mistaking. DON PEDRO By my soul, nor I: And yet, to satisfy this good old man, I would bend under any heavy weight That he'll enjoin me to. LEONATO I cannot bid you bid my daughter live; That were impossible: but, I pray you both, Possess the people in Messina here How innocent she died; and if your love Can labour ought in sad invention, Hang her an epitaph upon her tomb And sing it to her bones, sing it to-night: To-morrow morning come you to my house, And since you could not be my son-in-law, Be yet my nephew: my brother hath a daughter, Almost the copy of my child that's dead, And she alone is heir to both of us: Give her the right you should have given her cousin, And so dies my revenge. CLAUDIO O noble sir, Your over-kindness doth wring tears from me! I do embrace your offer; and dispose For henceforth of poor Claudio. LEONATO To-morrow then I will expect your coming; To-night I take my leave. This naughty man Shall face to face be brought to Margaret, Who I believe was pack'd in all this wrong, Hired to it by your brother. BORACHIO No, by my soul, she was not, Nor knew not what she did when she spoke to me, But always hath been just and virtuous In any thing that I do know by her. DOGBERRY Moreover, sir, which indeed is not under white and black, this plaintiff here, the offender, did call me ass: I beseech you, let it be remembered in his punishment. And also, the watch heard them talk of one Deformed: they say be wears a key in his ear and a lock hanging by it, and borrows money in God's name, the which he hath used so long and never paid that now men grow hard-hearted and will lend nothing for God's sake: pray you, examine him upon that point. LEONATO I thank thee for thy care and honest pains. DOGBERRY Your worship speaks like a most thankful and reverend youth; and I praise God for you. LEONATO There's for thy pains. DOGBERRY God save the foundation! LEONATO Go, I discharge thee of thy prisoner, and I thank thee. DOGBERRY I leave an arrant knave with your worship; which I beseech your worship to correct yourself, for the example of others. God keep your worship! I wish your worship well; God restore you to health! I humbly give you leave to depart; and if a merry meeting may be wished, God prohibit it! Come, neighbour. Exeunt DOGBERRY and VERGES LEONATO Until to-morrow morning, lords, farewell. ANTONIO Farewell, my lords: we look for you to-morrow. DON PEDRO We will not fail. CLAUDIO To-night I'll mourn with Hero. LEONATO To the Watch Bring you these fellows on. We'll talk with Margaret, How her acquaintance grew with this lewd fellow. Exeunt, severally SCENE II. LEONATO'S garden. Enter BENEDICK and MARGARET, meeting BENEDICK Pray thee, sweet Mistress Margaret, deserve well at my hands by helping me to the speech of Beatrice. MARGARET Will you then write me a sonnet in praise of my beauty? BENEDICK In so high a style, Margaret, that no man living shall come over it; for, in most comely truth, thou deservest it. MARGARET To have no man come over me! why, shall I always keep below stairs? BENEDICK Thy wit is as quick as the greyhound's mouth; it catches. MARGARET And yours as blunt as the fencer's foils, which hit, but hurt not. BENEDICK A most manly wit, Margaret; it will not hurt a woman: and so, I pray thee, call Beatrice: I give thee the bucklers. MARGARET Give us the swords; we have bucklers of our own. BENEDICK If you use them, Margaret, you must put in the pikes with a vice; and they are dangerous weapons for maids. MARGARET Well, I will call Beatrice to you, who I think hath legs. BENEDICK And therefore will come. Exit MARGARET Sings The god of love, That sits above, And knows me, and knows me, How pitiful I deserve,-- I mean in singing; but in loving, Leander the good swimmer, Troilus the first employer of panders, and a whole bookful of these quondam carpet-mangers, whose names yet run smoothly in the even road of a blank verse, why, they were never so truly turned over and over as my poor self in love. Marry, I cannot show it in rhyme; I have tried: I can find out no rhyme to 'lady' but 'baby,' an innocent rhyme; for 'scorn,' 'horn,' a hard rhyme; for, 'school,' 'fool,' a babbling rhyme; very ominous endings: no, I was not born under a rhyming planet, nor I cannot woo in festival terms. Enter BEATRICE Sweet Beatrice, wouldst thou come when I called thee? BEATRICE Yea, signior, and depart when you bid me. BENEDICK O, stay but till then! BEATRICE 'Then' is spoken; fare you well now: and yet, ere I go, let me go with that I came; which is, with knowing what hath passed between you and Claudio. BENEDICK Only foul words; and thereupon I will kiss thee. BEATRICE Foul words is but foul wind, and foul wind is but foul breath, and foul breath is noisome; therefore I will depart unkissed. BENEDICK Thou hast frighted the word out of his right sense, so forcible is thy wit. But I must tell thee plainly, Claudio undergoes my challenge; and either I must shortly hear from him, or I will subscribe him a coward. And, I pray thee now, tell me for which of my bad parts didst thou first fall in love with me? BEATRICE For them all together; which maintained so politic a state of evil that they will not admit any good part to intermingle with them. But for which of my good parts did you first suffer love for me? BENEDICK Suffer love! a good epithet! I do suffer love indeed, for I love thee against my will. BEATRICE In spite of your heart, I think; alas, poor heart! If you spite it for my sake, I will spite it for yours; for I will never love that which my friend hates. BENEDICK Thou and I are too wise to woo peaceably. BEATRICE It appears not in this confession: there's not one wise man among twenty that will praise himself. BENEDICK An old, an old instance, Beatrice, that lived in the lime of good neighbours. If a man do not erect in this age his own tomb ere he dies, he shall live no longer in monument than the bell rings and the widow weeps. BEATRICE And how long is that, think you? BENEDICK Question: why, an hour in clamour and a quarter in rheum: therefore is it most expedient for the wise, if Don Worm, his conscience, find no impediment to the contrary, to be the trumpet of his own virtues, as I am to myself. So much for praising myself, who, I myself will bear witness, is praiseworthy: and now tell me, how doth your cousin? BEATRICE Very ill. BENEDICK And how do you? BEATRICE Very ill too. BENEDICK Serve God, love me and mend. There will I leave you too, for here comes one in haste. Enter URSULA URSULA Madam, you must come to your uncle. Yonder's old coil at home: it is proved my Lady Hero hath been falsely accused, the prince and Claudio mightily abused; and Don John is the author of all, who is fed and gone. Will you come presently? BEATRICE Will you go hear this news, signior? BENEDICK I will live in thy heart, die in thy lap, and be buried in thy eyes; and moreover I will go with thee to thy uncle's. Exeunt SCENE III. A church. Enter DON PEDRO, CLAUDIO, and three or four with tapers CLAUDIO Is this the monument of Leonato? Lord It is, my lord. CLAUDIO Reading out of a scroll Done to death by slanderous tongues Was the Hero that here lies: Death, in guerdon of her wrongs, Gives her fame which never dies. So the life that died with shame Lives in death with glorious fame. Hang thou there upon the tomb, Praising her when I am dumb. Now, music, sound, and sing your solemn hymn. SONG. Pardon, goddess of the night, Those that slew thy virgin knight; For the which, with songs of woe, Round about her tomb they go. Midnight, assist our moan; Help us to sigh and groan, Heavily, heavily: Graves, yawn and yield your dead, Till death be uttered, Heavily, heavily. CLAUDIO Now, unto thy bones good night! Yearly will I do this rite. DON PEDRO Good morrow, masters; put your torches out: The wolves have prey'd; and look, the gentle day, Before the wheels of Phoebus, round about Dapples the drowsy east with spots of grey. Thanks to you all, and leave us: fare you well. CLAUDIO Good morrow, masters: each his several way. DON PEDRO Come, let us hence, and put on other weeds; And then to Leonato's we will go. CLAUDIO And Hymen now with luckier issue speed's Than this for whom we render'd up this woe. Exeunt SCENE IV. A room in LEONATO'S house. Enter LEONATO, ANTONIO, BENEDICK, BEATRICE, MARGARET, URSULA, FRIAR FRANCIS, and HERO FRIAR FRANCIS Did I not tell you she was innocent? LEONATO So are the prince and Claudio, who accused her Upon the error that you heard debated: But Margaret was in some fault for this, Although against her will, as it appears In the true course of all the question. ANTONIO Well, I am glad that all things sort so well. BENEDICK And so am I, being else by faith enforced To call young Claudio to a reckoning for it. LEONATO Well, daughter, and you gentle-women all, Withdraw into a chamber by yourselves, And when I send for you, come hither mask'd. Exeunt Ladies The prince and Claudio promised by this hour To visit me. You know your office, brother: You must be father to your brother's daughter And give her to young Claudio. ANTONIO Which I will do with confirm'd countenance. BENEDICK Friar, I must entreat your pains, I think. FRIAR FRANCIS To do what, signior? BENEDICK To bind me, or undo me; one of them. Signior Leonato, truth it is, good signior, Your niece regards me with an eye of favour. LEONATO That eye my daughter lent her: 'tis most true. BENEDICK And I do with an eye of love requite her. LEONATO The sight whereof I think you had from me, From Claudio and the prince: but what's your will? BENEDICK Your answer, sir, is enigmatical: But, for my will, my will is your good will May stand with ours, this day to be conjoin'd In the state of honourable marriage: In which, good friar, I shall desire your help. LEONATO My heart is with your liking. FRIAR FRANCIS And my help. Here comes the prince and Claudio. Enter DON PEDRO and CLAUDIO, and two or three others DON PEDRO Good morrow to this fair assembly. LEONATO Good morrow, prince; good morrow, Claudio: We here attend you. Are you yet determined To-day to marry with my brother's daughter? CLAUDIO I'll hold my mind, were she an Ethiope. LEONATO Call her forth, brother; here's the friar ready. Exit ANTONIO DON PEDRO Good morrow, Benedick. Why, what's the matter, That you have such a February face, So full of frost, of storm and cloudiness? CLAUDIO I think he thinks upon the savage bull. Tush, fear not, man; we'll tip thy horns with gold And all Europa shall rejoice at thee, As once Europa did at lusty Jove, When he would play the noble beast in love. BENEDICK Bull Jove, sir, had an amiable low; And some such strange bull leap'd your father's cow, And got a calf in that same noble feat Much like to you, for you have just his bleat. CLAUDIO For this I owe you: here comes other reckonings. Re-enter ANTONIO, with the Ladies masked Which is the lady I must seize upon? ANTONIO This same is she, and I do give you her. CLAUDIO Why, then she's mine. Sweet, let me see your face. LEONATO No, that you shall not, till you take her hand Before this friar and swear to marry her. CLAUDIO Give me your hand: before this holy friar, I am your husband, if you like of me. HERO And when I lived, I was your other wife: Unmasking And when you loved, you were my other husband. CLAUDIO Another Hero! HERO Nothing certainer: One Hero died defiled, but I do live, And surely as I live, I am a maid. DON PEDRO The former Hero! Hero that is dead! LEONATO She died, my lord, but whiles her slander lived. FRIAR FRANCIS All this amazement can I qualify: When after that the holy rites are ended, I'll tell you largely of fair Hero's death: Meantime let wonder seem familiar, And to the chapel let us presently. BENEDICK Soft and fair, friar. Which is Beatrice? BEATRICE Unmasking I answer to that name. What is your will? BENEDICK Do not you love me? BEATRICE Why, no; no more than reason. BENEDICK Why, then your uncle and the prince and Claudio Have been deceived; they swore you did. BEATRICE Do not you love me? BENEDICK Troth, no; no more than reason. BEATRICE Why, then my cousin Margaret and Ursula Are much deceived; for they did swear you did. BENEDICK They swore that you were almost sick for me. BEATRICE They swore that you were well-nigh dead for me. BENEDICK 'Tis no such matter. Then you do not love me? BEATRICE No, truly, but in friendly recompense. LEONATO Come, cousin, I am sure you love the gentleman. CLAUDIO And I'll be sworn upon't that he loves her; For here's a paper written in his hand, A halting sonnet of his own pure brain, Fashion'd to Beatrice. HERO And here's another Writ in my cousin's hand, stolen from her pocket, Containing her affection unto Benedick. BENEDICK A miracle! here's our own hands against our hearts. Come, I will have thee; but, by this light, I take thee for pity. BEATRICE I would not deny you; but, by this good day, I yield upon great persuasion; and partly to save your life, for I was told you were in a consumption. BENEDICK Peace! I will stop your mouth. Kissing her DON PEDRO How dost thou, Benedick, the married man? BENEDICK I'll tell thee what, prince; a college of wit-crackers cannot flout me out of my humour. Dost thou think I care for a satire or an epigram? No: if a man will be beaten with brains, a' shall wear nothing handsome about him. In brief, since I do purpose to marry, I will think nothing to any purpose that the world can say against it; and therefore never flout at me for what I have said against it; for man is a giddy thing, and this is my conclusion. For thy part, Claudio, I did think to have beaten thee, but in that thou art like to be my kinsman, live unbruised and love my cousin. CLAUDIO I had well hoped thou wouldst have denied Beatrice, that I might have cudgelled thee out of thy single life, to make thee a double-dealer; which, out of question, thou wilt be, if my cousin do not look exceedingly narrowly to thee. BENEDICK Come, come, we are friends: let's have a dance ere we are married, that we may lighten our own hearts and our wives' heels. LEONATO We'll have dancing afterward. BENEDICK First, of my word; therefore play, music. Prince, thou art sad; get thee a wife, get thee a wife: there is no staff more reverend than one tipped with horn. Enter a Messenger Messenger My lord, your brother John is ta'en in flight, And brought with armed men back to Messina. BENEDICK Think not on him till to-morrow: I'll devise thee brave punishments for him. Strike up, pipers. Dance Exeunt
dom4j-1.6.1/xml/russArticle.xml0000644000175000017500000000105510242120024015672 0ustar ebourgebourg
Russian Foto & Video_01_03_1.pdf Any caption relating to the article , . , . Casio QV-R3
dom4j-1.6.1/xml/testNamespaces.xml0000644000175000017500000000075410242117777016403 0ustar ebourgebourg dom4j-1.6.1/xml/xml.xml0000644000175000017500000047766610242120002014217 0ustar ebourgebourg "> '"> amp, lt, gt, apos, quot"> ]>
Extensible Markup Language (XML) 1.0 REC-xml-&iso6.doc.date; W3C Recommendation &draft.day;&draft.month;&draft.year; http://www.w3.org/TR/1998/REC-xml-&iso6.doc.date; http://www.w3.org/TR/1998/REC-xml-&iso6.doc.date;.xml http://www.w3.org/TR/1998/REC-xml-&iso6.doc.date;.html http://www.w3.org/TR/1998/REC-xml-&iso6.doc.date;.pdf http://www.w3.org/TR/1998/REC-xml-&iso6.doc.date;.ps http://www.w3.org/TR/REC-xml http://www.w3.org/TR/PR-xml-971208 Tim Bray Textuality and Netscape tbray@textuality.com Jean Paoli Microsoft jeanpa@microsoft.com C. M. Sperberg-McQueen University of Illinois at Chicago cmsmcq@uic.edu

The Extensible Markup Language (XML) is a subset of SGML that is completely described in this document. Its goal is to enable generic SGML to be served, received, and processed on the Web in the way that is now possible with HTML. XML has been designed for ease of implementation and for interoperability with both SGML and HTML.

This document has been reviewed by W3C Members and other interested parties and has been endorsed by the Director as a W3C Recommendation. It is a stable document and may be used as reference material or cited as a normative reference from another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web.

This document specifies a syntax created by subsetting an existing, widely used international text processing standard (Standard Generalized Markup Language, ISO 8879:1986(E) as amended and corrected) for use on the World Wide Web. It is a product of the W3C XML Activity, details of which can be found at http://www.w3.org/XML. A list of current W3C Recommendations and other technical documents can be found at http://www.w3.org/TR.

This specification uses the term URI, which is defined by , a work in progress expected to update and .

The list of known errors in this specification is available at http://www.w3.org/XML/xml-19980210-errata.

Please report errors in this document to xml-editor@w3.org.

Chicago, Vancouver, Mountain View, et al.: World-Wide Web Consortium, XML Working Group, 1996, 1997.

Created in electronic form.

English Extended Backus-Naur Form (formal grammar) 1997-12-03 : CMSMcQ : yet further changes 1997-12-02 : TB : further changes (see TB to XML WG, 2 December 1997) 1997-12-02 : CMSMcQ : deal with as many corrections and comments from the proofreaders as possible: entify hard-coded document date in pubdate element, change expansion of entity WebSGML, update status description as per Dan Connolly (am not sure about refernece to Berners-Lee et al.), add 'The' to abstract as per WG decision, move Relationship to Existing Standards to back matter and combine with References, re-order back matter so normative appendices come first, re-tag back matter so informative appendices are tagged informdiv1, remove XXX XXX from list of 'normative' specs in prose, move some references from Other References to Normative References, add RFC 1738, 1808, and 2141 to Other References (they are not normative since we do not require the processor to enforce any rules based on them), add reference to 'Fielding draft' (Berners-Lee et al.), move notation section to end of body, drop URIchar non-terminal and use SkipLit instead, lose stray reference to defunct nonterminal 'markupdecls', move reference to Aho et al. into appendix (Tim's right), add prose note saying that hash marks and fragment identifiers are NOT part of the URI formally speaking, and are NOT legal in system identifiers (processor 'may' signal an error). Work through: Tim Bray reacting to James Clark, Tim Bray on his own, Eve Maler, NOT DONE YET: change binary / text to unparsed / parsed. handle James's suggestion about < in attriubte values uppercase hex characters, namechar list, 1997-12-01 : JB : add some column-width parameters 1997-12-01 : CMSMcQ : begin round of changes to incorporate recent WG decisions and other corrections: binding sources of character encoding info (27 Aug / 3 Sept), correct wording of Faust quotation (restore dropped line), drop SDD from EncodingDecl, change text at version number 1.0, drop misleading (wrong!) sentence about ignorables and extenders, modify definition of PCData to make bar on msc grammatical, change grammar's handling of internal subset (drop non-terminal markupdecls), change definition of includeSect to allow conditional sections, add integral-declaration constraint on internal subset, drop misleading / dangerous sentence about relationship of entities with system storage objects, change table body tag to htbody as per EM change to DTD, add rule about space normalization in public identifiers, add description of how to generate our name-space rules from Unicode character database (needs further work!). 1997-10-08 : TB : Removed %-constructs again, new rules for PE appearance. 1997-10-01 : TB : Case-sensitive markup; cleaned up element-type defs, lotsa little edits for style 1997-09-25 : TB : Change to elm's new DTD, with substantial detail cleanup as a side-effect 1997-07-24 : CMSMcQ : correct error (lost *) in definition of ignoreSectContents (thanks to Makoto Murata) Allow all empty elements to have end-tags, consistent with SGML TC (as per JJC). 1997-07-23 : CMSMcQ : pre-emptive strike on pending corrections: introduce the term 'empty-element tag', note that all empty elements may use it, and elements declared EMPTY must use it. Add WFC requiring encoding decl to come first in an entity. Redefine notations to point to PIs as well as binary entities. Change autodetection table by removing bytes 3 and 4 from examples with Byte Order Mark. Add content model as a term and clarify that it applies to both mixed and element content. 1997-06-30 : CMSMcQ : change date, some cosmetic changes, changes to productions for choice, seq, Mixed, NotationType, Enumeration. Follow James Clark's suggestion and prohibit conditional sections in internal subset. TO DO: simplify production for ignored sections as a result, since we don't need to worry about parsers which don't expand PErefs finding a conditional section. 1997-06-29 : TB : various edits 1997-06-29 : CMSMcQ : further changes: Suppress old FINAL EDIT comments and some dead material. Revise occurrences of % in grammar to exploit Henry Thompson's pun, especially markupdecl and attdef. Remove RMD requirement relating to element content (?). 1997-06-28 : CMSMcQ : Various changes for 1 July draft: Add text for draconian error handling (introduce the term Fatal Error). RE deleta est (changing wording from original announcement to restrict the requirement to validating parsers). Tag definition of validating processor and link to it. Add colon as name character. Change def of %operator. Change standard definitions of lt, gt, amp. Strip leading zeros from #x00nn forms. 1997-04-02 : CMSMcQ : final corrections of editorial errors found in last night's proofreading. Reverse course once more on well-formed: Webster's Second hyphenates it, and that's enough for me. 1997-04-01 : CMSMcQ : corrections from JJC, EM, HT, and self 1997-03-31 : Tim Bray : many changes 1997-03-29 : CMSMcQ : some Henry Thompson (on entity handling), some Charles Goldfarb, some ERB decisions (PE handling in miscellaneous declarations. Changed Ident element to accept def attribute. Allow normalization of Unicode characters. move def of systemliteral into section on literals. 1997-03-28 : CMSMcQ : make as many corrections as possible, from Terry Allen, Norbert Mikula, James Clark, Jon Bosak, Henry Thompson, Paul Grosso, and self. Among other things: give in on "well formed" (Terry is right), tentatively rename QuotedCData as AttValue and Literal as EntityValue to be more informative, since attribute values are the only place QuotedCData was used, and vice versa for entity text and Literal. (I'd call it Entity Text, but 8879 uses that name for both internal and external entities.) 1997-03-26 : CMSMcQ : resynch the two forks of this draft, reapply my changes dated 03-20 and 03-21. Normalize old 'may not' to 'must not' except in the one case where it meant 'may or may not'. 1997-03-21 : TB : massive changes on plane flight from Chicago to Vancouver 1997-03-21 : CMSMcQ : correct as many reported errors as possible. 1997-03-20 : CMSMcQ : correct typos listed in CMSMcQ hand copy of spec. 1997-03-20 : CMSMcQ : cosmetic changes preparatory to revision for WWW conference April 1997: restore some of the internal entity references (e.g. to docdate, etc.), change character xA0 to &nbsp; and define nbsp as &#160;, and refill a lot of paragraphs for legibility. 1996-11-12 : CMSMcQ : revise using Tim's edits: Add list type of NUMBERED and change most lists either to BULLETS or to NUMBERED. Suppress QuotedNames, Names (not used). Correct trivial-grammar doc type decl. Rename 'marked section' as 'CDATA section' passim. Also edits from James Clark: Define the set of characters from which [^abc] subtracts. Charref should use just [0-9] not Digit. Location info needs cleaner treatment: remove? (ERB question). One example of a PI has wrong pic. Clarify discussion of encoding names. Encoding failure should lead to unspecified results; don't prescribe error recovery. Don't require exposure of entity boundaries. Ignore white space in element content. Reserve entity names of the form u-NNNN. Clarify relative URLs. And some of my own: Correct productions for content model: model cannot consist of a name, so "elements ::= cp" is no good. 1996-11-11 : CMSMcQ : revise for style. Add new rhs to entity declaration, for parameter entities. 1996-11-10 : CMSMcQ : revise for style. Fix / complete section on names, characters. Add sections on parameter entities, conditional sections. Still to do: Add compatibility note on deterministic content models. Finish stylistic revision. 1996-10-31 : TB : Add Entity Handling section 1996-10-30 : TB : Clean up term & termdef. Slip in ERB decision re EMPTY. 1996-10-28 : TB : Change DTD. Implement some of Michael's suggestions. Change comments back to //. Introduce language for XML namespace reservation. Add section on white-space handling. Lots more cleanup. 1996-10-24 : CMSMcQ : quick tweaks, implement some ERB decisions. Characters are not integers. Comments are /* */ not //. Add bibliographic refs to 10646, HyTime, Unicode. Rename old Cdata as MsData since it's only seen in marked sections. Call them attribute-value pairs not name-value pairs, except once. Internal subset is optional, needs '?'. Implied attributes should be signaled to the app, not have values supplied by processor. 1996-10-16 : TB : track down & excise all DSD references; introduce some EBNF for entity declarations. 1996-10-?? : TB : consistency check, fix up scraps so they all parse, get formatter working, correct a few productions. 1996-10-10/11 : CMSMcQ : various maintenance, stylistic, and organizational changes: Replace a few literals with xmlpio and pic entities, to make them consistent and ensure we can change pic reliably when the ERB votes. Drop paragraph on recognizers from notation section. Add match, exact match to terminology. Move old 2.2 XML Processors and Apps into intro. Mention comments, PIs, and marked sections in discussion of delimiter escaping. Streamline discussion of doctype decl syntax. Drop old section of 'PI syntax' for doctype decl, and add section on partial-DTD summary PIs to end of Logical Structures section. Revise DSD syntax section to use Tim's subset-in-a-PI mechanism. 1996-10-10 : TB : eliminate name recognizers (and more?) 1996-10-09 : CMSMcQ : revise for style, consistency through 2.3 (Characters) 1996-10-09 : CMSMcQ : re-unite everything for convenience, at least temporarily, and revise quickly 1996-10-08 : TB : first major homogenization pass 1996-10-08 : TB : turn "current" attribute on div type into CDATA 1996-10-02 : TB : remould into skeleton + entities 1996-09-30 : CMSMcQ : add a few more sections prior to exchange with Tim. 1996-09-20 : CMSMcQ : finish transcribing notes. 1996-09-19 : CMSMcQ : begin transcribing notes for draft. 1996-09-13 : CMSMcQ : made outline from notes of 09-06, do some housekeeping
Introduction

Extensible Markup Language, abbreviated XML, describes a class of data objects called XML documents and partially describes the behavior of computer programs which process them. XML is an application profile or restricted form of SGML, the Standard Generalized Markup Language . By construction, XML documents are conforming SGML documents.

XML documents are made up of storage units called entities, which contain either parsed or unparsed data. Parsed data is made up of characters, some of which form character data, and some of which form markup. Markup encodes a description of the document's storage layout and logical structure. XML provides a mechanism to impose constraints on the storage layout and logical structure.

A software module called an XML processor is used to read XML documents and provide access to their content and structure. It is assumed that an XML processor is doing its work on behalf of another module, called the application. This specification describes the required behavior of an XML processor in terms of how it must read XML data and the information it must provide to the application.

Origin and Goals

XML was developed by an XML Working Group (originally known as the SGML Editorial Review Board) formed under the auspices of the World Wide Web Consortium (W3C) in 1996. It was chaired by Jon Bosak of Sun Microsystems with the active participation of an XML Special Interest Group (previously known as the SGML Working Group) also organized by the W3C. The membership of the XML Working Group is given in an appendix. Dan Connolly served as the WG's contact with the W3C.

The design goals for XML are:

XML shall be straightforwardly usable over the Internet.

XML shall support a wide variety of applications.

XML shall be compatible with SGML.

It shall be easy to write programs which process XML documents.

The number of optional features in XML is to be kept to the absolute minimum, ideally zero.

XML documents should be human-legible and reasonably clear.

The XML design should be prepared quickly.

The design of XML shall be formal and concise.

XML documents shall be easy to create.

Terseness in XML markup is of minimal importance.

This specification, together with associated standards (Unicode and ISO/IEC 10646 for characters, Internet RFC 1766 for language identification tags, ISO 639 for language name codes, and ISO 3166 for country name codes), provides all the information necessary to understand XML Version &XML.version; and construct computer programs to process it.

This version of the XML specification &doc.distribution;.

Terminology

The terminology used to describe XML documents is defined in the body of this specification. The terms defined in the following list are used in building those definitions and in describing the actions of an XML processor:

Conforming documents and XML processors are permitted to but need not behave as described.

Conforming documents and XML processors are required to behave as described; otherwise they are in error.

A violation of the rules of this specification; results are undefined. Conforming software may detect and report an error and may recover from it.

An error which a conforming XML processor must detect and report to the application. After encountering a fatal error, the processor may continue processing the data to search for further errors and may report such errors to the application. In order to support correction of errors, the processor may make unprocessed data from the document (with intermingled character data and markup) available to the application. Once a fatal error is detected, however, the processor must not continue normal processing (i.e., it must not continue to pass character data and information about the document's logical structure to the application in the normal way).

Conforming software may or must (depending on the modal verb in the sentence) behave as described; if it does, it must provide users a means to enable or disable the behavior described.

A rule which applies to all valid XML documents. Violations of validity constraints are errors; they must, at user option, be reported by validating XML processors.

A rule which applies to all well-formed XML documents. Violations of well-formedness constraints are fatal errors.

(Of strings or names:) Two strings or names being compared must be identical. Characters with multiple possible representations in ISO/IEC 10646 (e.g. characters with both precomposed and base+diacritic forms) match only if they have the same representation in both strings. At user option, processors may normalize such characters to some canonical form. No case folding is performed. (Of strings and rules in the grammar:) A string matches a grammatical production if it belongs to the language generated by that production. (Of content and content models:) An element matches its declaration when it conforms in the fashion described in the constraint .

A feature of XML included solely to ensure that XML remains compatible with SGML.

A non-binding recommendation included to increase the chances that XML documents can be processed by the existing installed base of SGML processors which predate the &WebSGML;.

Documents

A data object is an XML document if it is well-formed, as defined in this specification. A well-formed XML document may in addition be valid if it meets certain further constraints.

Each XML document has both a logical and a physical structure. Physically, the document is composed of units called entities. An entity may refer to other entities to cause their inclusion in the document. A document begins in a "root" or document entity. Logically, the document is composed of declarations, elements, comments, character references, and processing instructions, all of which are indicated in the document by explicit markup. The logical and physical structures must nest properly, as described in .

Well-Formed XML Documents

A textual object is a well-formed XML document if:

Taken as a whole, it matches the production labeled document.

It meets all the well-formedness constraints given in this specification.

Each of the parsed entities which is referenced directly or indirectly within the document is well-formed.

Document document prolog element Misc*

Matching the document production implies that:

It contains one or more elements.

There is exactly one element, called the root, or document element, no part of which appears in the content of any other element. For all other elements, if the start-tag is in the content of another element, the end-tag is in the content of the same element. More simply stated, the elements, delimited by start- and end-tags, nest properly within each other.

As a consequence of this, for each non-root element C in the document, there is one other element P in the document such that C is in the content of P, but is not in the content of any other element that is in the content of P. P is referred to as the parent of C, and C as a child of P.

Characters

A parsed entity contains text, a sequence of characters, which may represent markup or character data. A character is an atomic unit of text as specified by ISO/IEC 10646 . Legal characters are tab, carriage return, line feed, and the legal graphic characters of Unicode and ISO/IEC 10646. The use of "compatibility characters", as defined in section 6.8 of , is discouraged. Character Range Char #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.

The mechanism for encoding character code points into bit patterns may vary from entity to entity. All XML processors must accept the UTF-8 and UTF-16 encodings of 10646; the mechanisms for signaling which of the two is in use, or for bringing other encodings into play, are discussed later, in .

Common Syntactic Constructs

This section defines some symbols used widely in the grammar.

S (white space) consists of one or more space (#x20) characters, carriage returns, line feeds, or tabs. White Space S (#x20 | #x9 | #xD | #xA)+

Characters are classified for convenience as letters, digits, or other characters. Letters consist of an alphabetic or syllabic base character possibly followed by one or more combining characters, or of an ideographic character. Full definitions of the specific characters in each class are given in .

A Name is a token beginning with a letter or one of a few punctuation characters, and continuing with letters, digits, hyphens, underscores, colons, or full stops, together known as name characters. Names beginning with the string "xml", or any string which would match (('X'|'x') ('M'|'m') ('L'|'l')), are reserved for standardization in this or future versions of this specification.

The colon character within XML names is reserved for experimentation with name spaces. Its meaning is expected to be standardized at some future point, at which point those documents using the colon for experimental purposes may need to be updated. (There is no guarantee that any name-space mechanism adopted for XML will in fact use the colon as a name-space delimiter.) In practice, this means that authors should not use the colon in XML names except as part of name-space experiments, but that XML processors should accept the colon as a name character.

An Nmtoken (name token) is any mixture of name characters. Names and Tokens NameChar Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender Name (Letter | '_' | ':') (NameChar)* Names Name (S Name)* Nmtoken (NameChar)+ Nmtokens Nmtoken (S Nmtoken)*

Literal data is any quoted string not containing the quotation mark used as a delimiter for that string. Literals are used for specifying the content of internal entities (EntityValue), the values of attributes (AttValue), and external identifiers (SystemLiteral). Note that a SystemLiteral can be parsed without scanning for markup. Literals EntityValue '"' ([^%&"] | PEReference | Reference)* '"' |  "'" ([^%&'] | PEReference | Reference)* "'" AttValue '"' ([^<&"] | Reference)* '"' |  "'" ([^<&'] | Reference)* "'" SystemLiteral ('"' [^"]* '"') | ("'" [^']* "'") PubidLiteral '"' PubidChar* '"' | "'" (PubidChar - "'")* "'" PubidChar #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%]

Character Data and Markup

Text consists of intermingled character data and markup. Markup takes the form of start-tags, end-tags, empty-element tags, entity references, character references, comments, CDATA section delimiters, document type declarations, and processing instructions.

All text that is not markup constitutes the character data of the document.

The ampersand character (&) and the left angle bracket (<) may appear in their literal form only when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. They are also legal within the literal entity value of an internal entity declaration; see . If they are needed elsewhere, they must be escaped using either numeric character references or the strings "&amp;" and "&lt;" respectively. The right angle bracket (>) may be represented using the string "&gt;", and must, for compatibility, be escaped using "&gt;" or a character reference when it appears in the string "]]>" in content, when that string is not marking the end of a CDATA section.

In the content of elements, character data is any string of characters which does not contain the start-delimiter of any markup. In a CDATA section, character data is any string of characters not including the CDATA-section-close delimiter, "]]>".

To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (') may be represented as "&apos;", and the double-quote character (") as "&quot;". Character Data CharData [^<&]* - ([^<&]* ']]>' [^<&]*)

Comments

Comments may appear anywhere in a document outside other markup; in addition, they may appear within the document type declaration at places allowed by the grammar. They are not part of the document's character data; an XML processor may, but need not, make it possible for an application to retrieve the text of comments. For compatibility, the string "--" (double-hyphen) must not occur within comments. Comments Comment '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'

An example of a comment: <!&como; declarations for <head> & <body> &comc;>

Processing Instructions

Processing instructions (PIs) allow documents to contain instructions for applications. Processing Instructions PI '<?' PITarget (S (Char* - (Char* &pic; Char*)))? &pic; PITarget Name - (('X' | 'x') ('M' | 'm') ('L' | 'l')) PIs are not part of the document's character data, but must be passed through to the application. The PI begins with a target (PITarget) used to identify the application to which the instruction is directed. The target names "XML", "xml", and so on are reserved for standardization in this or future versions of this specification. The XML Notation mechanism may be used for formal declaration of PI targets.

CDATA Sections

CDATA sections may occur anywhere character data may occur; they are used to escape blocks of text containing characters which would otherwise be recognized as markup. CDATA sections begin with the string "<![CDATA[" and end with the string "]]>": CDATA Sections CDSect CDStart CData CDEnd CDStart '<![CDATA[' CData (Char* - (Char* ']]>' Char*)) CDEnd ']]>' Within a CDATA section, only the CDEnd string is recognized as markup, so that left angle brackets and ampersands may occur in their literal form; they need not (and cannot) be escaped using "&lt;" and "&amp;". CDATA sections cannot nest.

An example of a CDATA section, in which "<greeting>" and "</greeting>" are recognized as character data, not markup: <![CDATA[<greeting>Hello, world!</greeting>]]>

Prolog and Document Type Declaration

XML documents may, and should, begin with an XML declaration which specifies the version of XML being used. For example, the following is a complete XML document, well-formed but not valid: Hello, world! ]]> and so is this: Hello, world! ]]>

The version number "1.0" should be used to indicate conformance to this version of this specification; it is an error for a document to use the value "1.0" if it does not conform to this version of this specification. It is the intent of the XML working group to give later versions of this specification numbers other than "1.0", but this intent does not indicate a commitment to produce any future versions of XML, nor if any are produced, to use any particular numbering scheme. Since future versions are not ruled out, this construct is provided as a means to allow the possibility of automatic version recognition, should it become necessary. Processors may signal an error if they receive documents labeled with versions they do not support.

The function of the markup in an XML document is to describe its storage and logical structure and to associate attribute-value pairs with its logical structures. XML provides a mechanism, the document type declaration, to define constraints on the logical structure and to support the use of predefined storage units. An XML document is valid if it has an associated document type declaration and if the document complies with the constraints expressed in it.

The document type declaration must appear before the first element in the document. Prolog prolog XMLDecl? Misc* (doctypedecl Misc*)? XMLDecl &xmlpio; VersionInfo EncodingDecl? SDDecl? S? &pic; VersionInfo S 'version' Eq (' VersionNum ' | " VersionNum ") Eq S? '=' S? VersionNum ([a-zA-Z0-9_.:] | '-')+ Misc Comment | PI | S

The XML document type declaration contains or points to markup declarations that provide a grammar for a class of documents. This grammar is known as a document type definition, or DTD. The document type declaration can point to an external subset (a special kind of external entity) containing markup declarations, or can contain the markup declarations directly in an internal subset, or can do both. The DTD for a document consists of both subsets taken together.

A markup declaration is an element type declaration, an attribute-list declaration, an entity declaration, or a notation declaration. These declarations may be contained in whole or in part within parameter entities, as described in the well-formedness and validity constraints below. For fuller information, see .

Document Type Definition doctypedecl '<!DOCTYPE' S Name (S ExternalID)? S? ('[' (markupdecl | PEReference | S)* ']' S?)? '>' markupdecl elementdecl | AttlistDecl | EntityDecl | NotationDecl | PI | Comment

The markup declarations may be made up in whole or in part of the replacement text of parameter entities. The productions later in this specification for individual nonterminals (elementdecl, AttlistDecl, and so on) describe the declarations after all the parameter entities have been included.

Root Element Type

The Name in the document type declaration must match the element type of the root element.

Proper Declaration/PE Nesting

Parameter-entity replacement text must be properly nested with markup declarations. That is to say, if either the first character or the last character of a markup declaration (markupdecl above) is contained in the replacement text for a parameter-entity reference, both must be contained in the same replacement text.

PEs in Internal Subset

In the internal DTD subset, parameter-entity references can occur only where markup declarations can occur, not within markup declarations. (This does not apply to references that occur in external parameter entities or to the external subset.)

Like the internal subset, the external subset and any external parameter entities referred to in the DTD must consist of a series of complete markup declarations of the types allowed by the non-terminal symbol markupdecl, interspersed with white space or parameter-entity references. However, portions of the contents of the external subset or of external parameter entities may conditionally be ignored by using the conditional section construct; this is not allowed in the internal subset. External Subset extSubset TextDecl? extSubsetDecl extSubsetDecl ( markupdecl | conditionalSect | PEReference | S )*

The external subset and external parameter entities also differ from the internal subset in that in them, parameter-entity references are permitted within markup declarations, not only between markup declarations.

An example of an XML document with a document type declaration: Hello, world! ]]> The system identifier "hello.dtd" gives the URI of a DTD for the document.

The declarations can also be given locally, as in this example: ]> Hello, world! ]]> If both the external and internal subsets are used, the internal subset is considered to occur before the external subset. This has the effect that entity and attribute-list declarations in the internal subset take precedence over those in the external subset.

Standalone Document Declaration

Markup declarations can affect the content of the document, as passed from an XML processor to an application; examples are attribute defaults and entity declarations. The standalone document declaration, which may appear as a component of the XML declaration, signals whether or not there are such declarations which appear external to the document entity. Standalone Document Declaration SDDecl S 'standalone' Eq (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no') '"'))

In a standalone document declaration, the value "yes" indicates that there are no markup declarations external to the document entity (either in the DTD external subset, or in an external parameter entity referenced from the internal subset) which affect the information passed from the XML processor to the application. The value "no" indicates that there are or may be such external markup declarations. Note that the standalone document declaration only denotes the presence of external declarations; the presence, in a document, of references to external entities, when those entities are internally declared, does not change its standalone status.

If there are no external markup declarations, the standalone document declaration has no meaning. If there are external markup declarations but there is no standalone document declaration, the value "no" is assumed.

Any XML document for which standalone="no" holds can be converted algorithmically to a standalone document, which may be desirable for some network delivery applications.

Standalone Document Declaration

The standalone document declaration must have the value "no" if any external markup declarations contain declarations of:

attributes with default values, if elements to which these attributes apply appear in the document without specifications of values for these attributes, or

entities (other than &magicents;), if references to those entities appear in the document, or

attributes with values subject to normalization, where the attribute appears in the document with a value which will change as a result of normalization, or

element types with element content, if white space occurs directly within any instance of those types.

An example XML declaration with a standalone document declaration:<?xml version="&XML.version;" standalone='yes'?>

White Space Handling

In editing XML documents, it is often convenient to use "white space" (spaces, tabs, and blank lines, denoted by the nonterminal S in this specification) to set apart the markup for greater readability. Such white space is typically not intended for inclusion in the delivered version of the document. On the other hand, "significant" white space that should be preserved in the delivered version is common, for example in poetry and source code.

An XML processor must always pass all characters in a document that are not markup through to the application. A validating XML processor must also inform the application which of these characters constitute white space appearing in element content.

A special attribute named xml:space may be attached to an element to signal an intention that in that element, white space should be preserved by applications. In valid documents, this attribute, like any other, must be declared if it is used. When declared, it must be given as an enumerated type whose only possible values are "default" and "preserve". For example:]]>

The value "default" signals that applications' default white-space processing modes are acceptable for this element; the value "preserve" indicates the intent that applications preserve all the white space. This declared intent is considered to apply to all elements within the content of the element where it is specified, unless overriden with another instance of the xml:space attribute.

The root element of any document is considered to have signaled no intentions as regards application space handling, unless it provides a value for this attribute or the attribute is declared with a default value.

End-of-Line Handling

XML parsed entities are often stored in computer files which, for editing convenience, are organized into lines. These lines are typically separated by some combination of the characters carriage-return (#xD) and line-feed (#xA).

To simplify the tasks of applications, wherever an external parsed entity or the literal entity value of an internal parsed entity contains either the literal two-character sequence "#xD#xA" or a standalone literal #xD, an XML processor must pass to the application the single character #xA. (This behavior can conveniently be produced by normalizing all line breaks to #xA on input, before parsing.)

Language Identification

In document processing, it is often useful to identify the natural or formal language in which the content is written. A special attribute named xml:lang may be inserted in documents to specify the language used in the contents and attribute values of any element in an XML document. In valid documents, this attribute, like any other, must be declared if it is used. The values of the attribute are language identifiers as defined by , "Tags for the Identification of Languages": Language Identification LanguageID Langcode ('-' Subcode)* Langcode ISO639Code | IanaCode | UserCode ISO639Code ([a-z] | [A-Z]) ([a-z] | [A-Z]) IanaCode ('i' | 'I') '-' ([a-z] | [A-Z])+ UserCode ('x' | 'X') '-' ([a-z] | [A-Z])+ Subcode ([a-z] | [A-Z])+ The Langcode may be any of the following:

a two-letter language code as defined by , "Codes for the representation of names of languages"

a language identifier registered with the Internet Assigned Numbers Authority ; these begin with the prefix "i-" (or "I-")

a language identifier assigned by the user, or agreed on between parties in private use; these must begin with the prefix "x-" or "X-" in order to ensure that they do not conflict with names later standardized or registered with IANA

There may be any number of Subcode segments; if the first subcode segment exists and the Subcode consists of two letters, then it must be a country code from , "Codes for the representation of names of countries." If the first subcode consists of more than two letters, it must be a subcode for the language in question registered with IANA, unless the Langcode begins with the prefix "x-" or "X-".

It is customary to give the language code in lower case, and the country code (if any) in upper case. Note that these values, unlike other names in XML documents, are case insensitive.

For example: The quick brown fox jumps over the lazy dog.

What colour is it?

What color is it?

Habe nun, ach! Philosophie, Juristerei, und Medizin und leider auch Theologie durchaus studiert mit heiem Bemh'n. ]]>

The intent declared with xml:lang is considered to apply to all attributes and content of the element where it is specified, unless overridden with an instance of xml:lang on another element within that content.

A simple declaration for xml:lang might take the form xml:lang NMTOKEN #IMPLIED but specific default values may also be given, if appropriate. In a collection of French poems for English students, with glosses and notes in English, the xml:lang attribute might be declared this way: ]]>

Logical Structures

Each XML document contains one or more elements, the boundaries of which are either delimited by start-tags and end-tags, or, for empty elements, by an empty-element tag. Each element has a type, identified by name, sometimes called its "generic identifier" (GI), and may have a set of attribute specifications. Each attribute specification has a name and a value.

Element element EmptyElemTag | STag content ETag

This specification does not constrain the semantics, use, or (beyond syntax) names of the element types and attributes, except that names beginning with a match to (('X'|'x')('M'|'m')('L'|'l')) are reserved for standardization in this or future versions of this specification.

Element Type Match

The Name in an element's end-tag must match the element type in the start-tag.

Element Valid

An element is valid if there is a declaration matching elementdecl where the Name matches the element type, and one of the following holds:

The declaration matches EMPTY and the element has no content.

The declaration matches children and the sequence of child elements belongs to the language generated by the regular expression in the content model, with optional white space (characters matching the nonterminal S) between each pair of child elements.

The declaration matches Mixed and the content consists of character data and child elements whose types match names in the content model.

The declaration matches ANY, and the types of any child elements have been declared.

Start-Tags, End-Tags, and Empty-Element Tags

The beginning of every non-empty XML element is marked by a start-tag. Start-tag STag '<' Name (S Attribute)* S? '>' Attribute Name Eq AttValue The Name in the start- and end-tags gives the element's type. The Name-AttValue pairs are referred to as the attribute specifications of the element, with the Name in each pair referred to as the attribute name and the content of the AttValue (the text between the ' or " delimiters) as the attribute value.

Unique Att Spec

No attribute name may appear more than once in the same start-tag or empty-element tag.

Attribute Value Type

The attribute must have been declared; the value must be of the type declared for it. (For attribute types, see .)

No External Entity References

Attribute values cannot contain direct or indirect entity references to external entities.

No < in Attribute Values

The replacement text of any entity referred to directly or indirectly in an attribute value (other than "&lt;") must not contain a <.

An example of a start-tag: <termdef id="dt-dog" term="dog">

The end of every element that begins with a start-tag must be marked by an end-tag containing a name that echoes the element's type as given in the start-tag: End-tag ETag '</' Name S? '>'

An example of an end-tag:</termdef>

The text between the start-tag and end-tag is called the element's content: Content of Elements content (element | CharData | Reference | CDSect | PI | Comment)*

If an element is empty, it must be represented either by a start-tag immediately followed by an end-tag or by an empty-element tag. An empty-element tag takes a special form: Tags for Empty Elements EmptyElemTag '<' Name (S Attribute)* S? '/>'

Empty-element tags may be used for any element which has no content, whether or not it is declared using the keyword EMPTY. For interoperability, the empty-element tag must be used, and can only be used, for elements which are declared EMPTY.

Examples of empty elements: <IMG align="left" src="http://www.w3.org/Icons/WWW/w3c_home" /> <br></br> <br/>

Element Type Declarations

The element structure of an XML document may, for validation purposes, be constrained using element type and attribute-list declarations. An element type declaration constrains the element's content.

Element type declarations often constrain which element types can appear as children of the element. At user option, an XML processor may issue a warning when a declaration mentions an element type for which no declaration is provided, but this is not an error.

An element type declaration takes the form: Element Type Declaration elementdecl '<!ELEMENT' S Name S contentspec S? '>' contentspec 'EMPTY' | 'ANY' | Mixed | children where the Name gives the element type being declared.

Unique Element Type Declaration

No element type may be declared more than once.

Examples of element type declarations: <!ELEMENT br EMPTY> <!ELEMENT p (#PCDATA|emph)* > <!ELEMENT %name.para; %content.para; > <!ELEMENT container ANY>

Element Content

An element type has element content when elements of that type must contain only child elements (no character data), optionally separated by white space (characters matching the nonterminal S). In this case, the constraint includes a content model, a simple grammar governing the allowed types of the child elements and the order in which they are allowed to appear. The grammar is built on content particles (cps), which consist of names, choice lists of content particles, or sequence lists of content particles: Element-content Models children (choice | seq) ('?' | '*' | '+')? cp (Name | choice | seq) ('?' | '*' | '+')? choice '(' S? cp ( S? '|' S? cp )* S? ')' seq '(' S? cp ( S? ',' S? cp )* S? ')' where each Name is the type of an element which may appear as a child. Any content particle in a choice list may appear in the element content at the location where the choice list appears in the grammar; content particles occurring in a sequence list must each appear in the element content in the order given in the list. The optional character following a name or list governs whether the element or the content particles in the list may occur one or more (+), zero or more (*), or zero or one times (?). The absence of such an operator means that the element or content particle must appear exactly once. This syntax and meaning are identical to those used in the productions in this specification.

The content of an element matches a content model if and only if it is possible to trace out a path through the content model, obeying the sequence, choice, and repetition operators and matching each element in the content against an element type in the content model. For compatibility, it is an error if an element in the document can match more than one occurrence of an element type in the content model. For more information, see .

Proper Group/PE Nesting

Parameter-entity replacement text must be properly nested with parenthetized groups. That is to say, if either of the opening or closing parentheses in a choice, seq, or Mixed construct is contained in the replacement text for a parameter entity, both must be contained in the same replacement text.

For interoperability, if a parameter-entity reference appears in a choice, seq, or Mixed construct, its replacement text should not be empty, and neither the first nor last non-blank character of the replacement text should be a connector (| or ,).

Examples of element-content models: <!ELEMENT spec (front, body, back?)> <!ELEMENT div1 (head, (p | list | note)*, div2*)> <!ELEMENT dictionary-body (%div.mix; | %dict.mix;)*>

Mixed Content

An element type has mixed content when elements of that type may contain character data, optionally interspersed with child elements. In this case, the types of the child elements may be constrained, but not their order or their number of occurrences: Mixed-content Declaration Mixed '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*' | '(' S? '#PCDATA' S? ')' where the Names give the types of elements that may appear as children.

No Duplicate Types

The same name must not appear more than once in a single mixed-content declaration.

Examples of mixed content declarations: <!ELEMENT p (#PCDATA|a|ul|b|i|em)*> <!ELEMENT p (#PCDATA | %font; | %phrase; | %special; | %form;)* > <!ELEMENT b (#PCDATA)>

Attribute-List Declarations

Attributes are used to associate name-value pairs with elements. Attribute specifications may appear only within start-tags and empty-element tags; thus, the productions used to recognize them appear in . Attribute-list declarations may be used:

To define the set of attributes pertaining to a given element type.

To establish type constraints for these attributes.

To provide default values for attributes.

Attribute-list declarations specify the name, data type, and default value (if any) of each attribute associated with a given element type: Attribute-list Declaration AttlistDecl '<!ATTLIST' S Name AttDef* S? '>' AttDef S Name S AttType S DefaultDecl The Name in the AttlistDecl rule is the type of an element. At user option, an XML processor may issue a warning if attributes are declared for an element type not itself declared, but this is not an error. The Name in the AttDef rule is the name of the attribute.

When more than one AttlistDecl is provided for a given element type, the contents of all those provided are merged. When more than one definition is provided for the same attribute of a given element type, the first declaration is binding and later declarations are ignored. For interoperability, writers of DTDs may choose to provide at most one attribute-list declaration for a given element type, at most one attribute definition for a given attribute name, and at least one attribute definition in each attribute-list declaration. For interoperability, an XML processor may at user option issue a warning when more than one attribute-list declaration is provided for a given element type, or more than one attribute definition is provided for a given attribute, but this is not an error.

Attribute Types

XML attribute types are of three kinds: a string type, a set of tokenized types, and enumerated types. The string type may take any literal string as a value; the tokenized types have varying lexical and semantic constraints, as noted: Attribute Types AttType StringType | TokenizedType | EnumeratedType StringType 'CDATA' TokenizedType 'ID' | 'IDREF' | 'IDREFS' | 'ENTITY' | 'ENTITIES' | 'NMTOKEN' | 'NMTOKENS'

ID

Values of type ID must match the Name production. A name must not appear more than once in an XML document as a value of this type; i.e., ID values must uniquely identify the elements which bear them.

One ID per Element Type

No element type may have more than one ID attribute specified.

ID Attribute Default

An ID attribute must have a declared default of #IMPLIED or #REQUIRED.

IDREF

Values of type IDREF must match the Name production, and values of type IDREFS must match Names; each Name must match the value of an ID attribute on some element in the XML document; i.e. IDREF values must match the value of some ID attribute.

Entity Name

Values of type ENTITY must match the Name production, values of type ENTITIES must match Names; each Name must match the name of an unparsed entity declared in the DTD.

Name Token

Values of type NMTOKEN must match the Nmtoken production; values of type NMTOKENS must match Nmtokens.

Enumerated attributes can take one of a list of values provided in the declaration. There are two kinds of enumerated types: Enumerated Attribute Types EnumeratedType NotationType | Enumeration NotationType 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')' Enumeration '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')' A NOTATION attribute identifies a notation, declared in the DTD with associated system and/or public identifiers, to be used in interpreting the element to which the attribute is attached.

Notation Attributes

Values of this type must match one of the notation names included in the declaration; all notation names in the declaration must be declared.

Enumeration

Values of this type must match one of the Nmtoken tokens in the declaration.

For interoperability, the same Nmtoken should not occur more than once in the enumerated attribute types of a single element type.

Attribute Defaults

An attribute declaration provides information on whether the attribute's presence is required, and if not, how an XML processor should react if a declared attribute is absent in a document. Attribute Defaults DefaultDecl '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)

In an attribute declaration, #REQUIRED means that the attribute must always be provided, #IMPLIED that no default value is provided. If the declaration is neither #REQUIRED nor #IMPLIED, then the AttValue value contains the declared default value; the #FIXED keyword states that the attribute must always have the default value. If a default value is declared, when an XML processor encounters an omitted attribute, it is to behave as though the attribute were present with the declared default value.

Required Attribute

If the default declaration is the keyword #REQUIRED, then the attribute must be specified for all elements of the type in the attribute-list declaration.

Attribute Default Legal

The declared default value must meet the lexical constraints of the declared attribute type.

Fixed Attribute Default

If an attribute has a default value declared with the #FIXED keyword, instances of that attribute must match the default value.

Examples of attribute-list declarations: <!ATTLIST termdef id ID #REQUIRED name CDATA #IMPLIED> <!ATTLIST list type (bullets|ordered|glossary) "ordered"> <!ATTLIST form method CDATA #FIXED "POST">

Attribute-Value Normalization

Before the value of an attribute is passed to the application or checked for validity, the XML processor must normalize it as follows:

a character reference is processed by appending the referenced character to the attribute value

an entity reference is processed by recursively processing the replacement text of the entity

a whitespace character (#x20, #xD, #xA, #x9) is processed by appending #x20 to the normalized value, except that only a single #x20 is appended for a "#xD#xA" sequence that is part of an external parsed entity or the literal entity value of an internal parsed entity

other characters are processed by appending them to the normalized value

If the declared value is not CDATA, then the XML processor must further process the normalized attribute value by discarding any leading and trailing space (#x20) characters, and by replacing sequences of space (#x20) characters by a single space (#x20) character.

All attributes for which no declaration has been read should be treated by a non-validating parser as if declared CDATA.

Conditional Sections

Conditional sections are portions of the document type declaration external subset which are included in, or excluded from, the logical structure of the DTD based on the keyword which governs them. Conditional Section conditionalSect includeSect | ignoreSect includeSect '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>' ignoreSect '<![' S? 'IGNORE' S? '[' ignoreSectContents* ']]>' ignoreSectContents Ignore ('<![' ignoreSectContents ']]>' Ignore)* Ignore Char* - (Char* ('<![' | ']]>') Char*)

Like the internal and external DTD subsets, a conditional section may contain one or more complete declarations, comments, processing instructions, or nested conditional sections, intermingled with white space.

If the keyword of the conditional section is INCLUDE, then the contents of the conditional section are part of the DTD. If the keyword of the conditional section is IGNORE, then the contents of the conditional section are not logically part of the DTD. Note that for reliable parsing, the contents of even ignored conditional sections must be read in order to detect nested conditional sections and ensure that the end of the outermost (ignored) conditional section is properly detected. If a conditional section with a keyword of INCLUDE occurs within a larger conditional section with a keyword of IGNORE, both the outer and the inner conditional sections are ignored.

If the keyword of the conditional section is a parameter-entity reference, the parameter entity must be replaced by its content before the processor decides whether to include or ignore the conditional section.

An example: <!ENTITY % draft 'INCLUDE' > <!ENTITY % final 'IGNORE' > <![%draft;[ <!ELEMENT book (comments*, title, body, supplements?)> ]]> <![%final;[ <!ELEMENT book (title, body, supplements?)> ]]>

Physical Structures

An XML document may consist of one or many storage units. These are called entities; they all have content and are all (except for the document entity, see below, and the external DTD subset) identified by name. Each XML document has one entity called the document entity, which serves as the starting point for the XML processor and may contain the whole document.

Entities may be either parsed or unparsed. A parsed entity's contents are referred to as its replacement text; this text is considered an integral part of the document.

An unparsed entity is a resource whose contents may or may not be text, and if text, may not be XML. Each unparsed entity has an associated notation, identified by name. Beyond a requirement that an XML processor make the identifiers for the entity and notation available to the application, XML places no constraints on the contents of unparsed entities.

Parsed entities are invoked by name using entity references; unparsed entities by name, given in the value of ENTITY or ENTITIES attributes.

General entities are entities for use within the document content. In this specification, general entities are sometimes referred to with the unqualified term entity when this leads to no ambiguity. Parameter entities are parsed entities for use within the DTD. These two types of entities use different forms of reference and are recognized in different contexts. Furthermore, they occupy different namespaces; a parameter entity and a general entity with the same name are two distinct entities.

Character and Entity References

A character reference refers to a specific character in the ISO/IEC 10646 character set, for example one not directly accessible from available input devices. Character Reference CharRef '&#' [0-9]+ ';' | '&hcro;' [0-9a-fA-F]+ ';' Legal Character

Characters referred to using character references must match the production for Char.

If the character reference begins with "&#x", the digits and letters up to the terminating ; provide a hexadecimal representation of the character's code point in ISO/IEC 10646. If it begins just with "&#", the digits up to the terminating ; provide a decimal representation of the character's code point.

An entity reference refers to the content of a named entity. References to parsed general entities use ampersand (&) and semicolon (;) as delimiters. Parameter-entity references use percent-sign (%) and semicolon (;) as delimiters.

Entity Reference Reference EntityRef | CharRef EntityRef '&' Name ';' PEReference '%' Name ';' Entity Declared

In a document without any DTD, a document with only an internal DTD subset which contains no parameter entity references, or a document with "standalone='yes'", the Name given in the entity reference must match that in an entity declaration, except that well-formed documents need not declare any of the following entities: &magicents;. The declaration of a parameter entity must precede any reference to it. Similarly, the declaration of a general entity must precede any reference to it which appears in a default value in an attribute-list declaration.

Note that if entities are declared in the external subset or in external parameter entities, a non-validating processor is not obligated to read and process their declarations; for such documents, the rule that an entity must be declared is a well-formedness constraint only if standalone='yes'.

Entity Declared

In a document with an external subset or external parameter entities with "standalone='no'", the Name given in the entity reference must match that in an entity declaration. For interoperability, valid documents should declare the entities &magicents;, in the form specified in . The declaration of a parameter entity must precede any reference to it. Similarly, the declaration of a general entity must precede any reference to it which appears in a default value in an attribute-list declaration.

Parsed Entity

An entity reference must not contain the name of an unparsed entity. Unparsed entities may be referred to only in attribute values declared to be of type ENTITY or ENTITIES.

No Recursion

A parsed entity must not contain a recursive reference to itself, either directly or indirectly.

In DTD

Parameter-entity references may only appear in the DTD.

Examples of character and entity references: Type <key>less-than</key> (&hcro;3C;) to save options. This document was prepared on &docdate; and is classified &security-level;.

Example of a parameter-entity reference: %ISOLat2;]]>

Entity Declarations

Entities are declared thus: Entity Declaration EntityDecl GEDecl | PEDecl GEDecl '<!ENTITY' S Name S EntityDef S? '>' PEDecl '<!ENTITY' S '%' S Name S PEDef S? '>' EntityDef EntityValue | (ExternalID NDataDecl?) PEDef EntityValue | ExternalID The Name identifies the entity in an entity reference or, in the case of an unparsed entity, in the value of an ENTITY or ENTITIES attribute. If the same entity is declared more than once, the first declaration encountered is binding; at user option, an XML processor may issue a warning if entities are declared multiple times.

Internal Entities

If the entity definition is an EntityValue, the defined entity is called an internal entity. There is no separate physical storage object, and the content of the entity is given in the declaration. Note that some processing of entity and character references in the literal entity value may be required to produce the correct replacement text: see .

An internal entity is a parsed entity.

Example of an internal entity declaration: <!ENTITY Pub-Status "This is a pre-release of the specification.">

External Entities

If the entity is not internal, it is an external entity, declared as follows: External Entity Declaration ExternalID 'SYSTEM' S SystemLiteral | 'PUBLIC' S PubidLiteral S SystemLiteral NDataDecl S 'NDATA' S Name If the NDataDecl is present, this is a general unparsed entity; otherwise it is a parsed entity.

Notation Declared

The Name must match the declared name of a notation.

The SystemLiteral is called the entity's system identifier. It is a URI, which may be used to retrieve the entity. Note that the hash mark (#) and fragment identifier frequently used with URIs are not, formally, part of the URI itself; an XML processor may signal an error if a fragment identifier is given as part of a system identifier. Unless otherwise provided by information outside the scope of this specification (e.g. a special XML element type defined by a particular DTD, or a processing instruction defined by a particular application specification), relative URIs are relative to the location of the resource within which the entity declaration occurs. A URI might thus be relative to the document entity, to the entity containing the external DTD subset, or to some other external parameter entity.

An XML processor should handle a non-ASCII character in a URI by representing the character in UTF-8 as one or more bytes, and then escaping these bytes with the URI escaping mechanism (i.e., by converting each byte to %HH, where HH is the hexadecimal notation of the byte value).

In addition to a system identifier, an external identifier may include a public identifier. An XML processor attempting to retrieve the entity's content may use the public identifier to try to generate an alternative URI. If the processor is unable to do so, it must use the URI specified in the system literal. Before a match is attempted, all strings of white space in the public identifier must be normalized to single space characters (#x20), and leading and trailing white space must be removed.

Examples of external entity declarations: <!ENTITY open-hatch SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml"> <!ENTITY open-hatch PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" "http://www.textuality.com/boilerplate/OpenHatch.xml"> <!ENTITY hatch-pic SYSTEM "../grafix/OpenHatch.gif" NDATA gif >

Parsed Entities The Text Declaration

External parsed entities may each begin with a text declaration. Text Declaration TextDecl &xmlpio; VersionInfo? EncodingDecl S? &pic;

The text declaration must be provided literally, not by reference to a parsed entity. No text declaration may appear at any position other than the beginning of an external parsed entity.

Well-Formed Parsed Entities

The document entity is well-formed if it matches the production labeled document. An external general parsed entity is well-formed if it matches the production labeled extParsedEnt. An external parameter entity is well-formed if it matches the production labeled extPE. Well-Formed External Parsed Entity extParsedEnt TextDecl? content extPE TextDecl? extSubsetDecl An internal general parsed entity is well-formed if its replacement text matches the production labeled content. All internal parameter entities are well-formed by definition.

A consequence of well-formedness in entities is that the logical and physical structures in an XML document are properly nested; no start-tag, end-tag, empty-element tag, element, comment, processing instruction, character reference, or entity reference can begin in one entity and end in another.

Character Encoding in Entities

Each external parsed entity in an XML document may use a different encoding for its characters. All XML processors must be able to read entities in either UTF-8 or UTF-16.

Entities encoded in UTF-16 must begin with the Byte Order Mark described by ISO/IEC 10646 Annex E and Unicode Appendix B (the ZERO WIDTH NO-BREAK SPACE character, #xFEFF). This is an encoding signature, not part of either the markup or the character data of the XML document. XML processors must be able to use this character to differentiate between UTF-8 and UTF-16 encoded documents.

Although an XML processor is required to read only entities in the UTF-8 and UTF-16 encodings, it is recognized that other encodings are used around the world, and it may be desired for XML processors to read entities that use them. Parsed entities which are stored in an encoding other than UTF-8 or UTF-16 must begin with a text declaration containing an encoding declaration: Encoding Declaration EncodingDecl S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" ) EncName [A-Za-z] ([A-Za-z0-9._] | '-')* Encoding name contains only Latin characters In the document entity, the encoding declaration is part of the XML declaration. The EncName is the name of the encoding used.

In an encoding declaration, the values "UTF-8", "UTF-16", "ISO-10646-UCS-2", and "ISO-10646-UCS-4" should be used for the various encodings and transformations of Unicode / ISO/IEC 10646, the values "ISO-8859-1", "ISO-8859-2", ... "ISO-8859-9" should be used for the parts of ISO 8859, and the values "ISO-2022-JP", "Shift_JIS", and "EUC-JP" should be used for the various encoded forms of JIS X-0208-1997. XML processors may recognize other encodings; it is recommended that character encodings registered (as charsets) with the Internet Assigned Numbers Authority , other than those just listed, should be referred to using their registered names. Note that these registered names are defined to be case-insensitive, so processors wishing to match against them should do so in a case-insensitive way.

In the absence of information provided by an external transport protocol (e.g. HTTP or MIME), it is an error for an entity including an encoding declaration to be presented to the XML processor in an encoding other than that named in the declaration, for an encoding declaration to occur other than at the beginning of an external entity, or for an entity which begins with neither a Byte Order Mark nor an encoding declaration to use an encoding other than UTF-8. Note that since ASCII is a subset of UTF-8, ordinary ASCII entities do not strictly need an encoding declaration.

It is a fatal error when an XML processor encounters an entity with an encoding that it is unable to process.

Examples of encoding declarations: <?xml encoding='UTF-8'?> <?xml encoding='EUC-JP'?>

XML Processor Treatment of Entities and References

The table below summarizes the contexts in which character references, entity references, and invocations of unparsed entities might appear and the required behavior of an XML processor in each case. The labels in the leftmost column describe the recognition context:

as a reference anywhere after the start-tag and before the end-tag of an element; corresponds to the nonterminal content.

as a reference within either the value of an attribute in a start-tag, or a default value in an attribute declaration; corresponds to the nonterminal AttValue.

as a Name, not a reference, appearing either as the value of an attribute which has been declared as type ENTITY, or as one of the space-separated tokens in the value of an attribute which has been declared as type ENTITIES.

as a reference within a parameter or internal entity's literal entity value in the entity's declaration; corresponds to the nonterminal EntityValue.

as a reference within either the internal or external subsets of the DTD, but outside of an EntityValue or AttValue.

Entity Type Character Parameter Internal General External Parsed General Unparsed Reference in Content Not recognized Included Included if validating Forbidden Included Reference in Attribute Value Not recognized Included in literal Forbidden Forbidden Included Occurs as Attribute Value Not recognized Forbidden Forbidden Notify Not recognized Reference in EntityValue Included in literal Bypassed Bypassed Forbidden Included Reference in DTD Included as PE Forbidden Forbidden Forbidden Forbidden Not Recognized

Outside the DTD, the % character has no special significance; thus, what would be parameter entity references in the DTD are not recognized as markup in content. Similarly, the names of unparsed entities are not recognized except when they appear in the value of an appropriately declared attribute.

Included

An entity is included when its replacement text is retrieved and processed, in place of the reference itself, as though it were part of the document at the location the reference was recognized. The replacement text may contain both character data and (except for parameter entities) markup, which must be recognized in the usual way, except that the replacement text of entities used to escape markup delimiters (the entities &magicents;) is always treated as data. (The string "AT&amp;T;" expands to "AT&T;" and the remaining ampersand is not recognized as an entity-reference delimiter.) A character reference is included when the indicated character is processed in place of the reference itself.

Included If Validating

When an XML processor recognizes a reference to a parsed entity, in order to validate the document, the processor must include its replacement text. If the entity is external, and the processor is not attempting to validate the XML document, the processor may, but need not, include the entity's replacement text. If a non-validating parser does not include the replacement text, it must inform the application that it recognized, but did not read, the entity.

This rule is based on the recognition that the automatic inclusion provided by the SGML and XML entity mechanism, primarily designed to support modularity in authoring, is not necessarily appropriate for other applications, in particular document browsing. Browsers, for example, when encountering an external parsed entity reference, might choose to provide a visual indication of the entity's presence and retrieve it for display only on demand.

Forbidden

The following are forbidden, and constitute fatal errors:

the appearance of a reference to an unparsed entity.

the appearance of any character or general-entity reference in the DTD except within an EntityValue or AttValue.

a reference to an external entity in an attribute value.

Included in Literal

When an entity reference appears in an attribute value, or a parameter entity reference appears in a literal entity value, its replacement text is processed in place of the reference itself as though it were part of the document at the location the reference was recognized, except that a single or double quote character in the replacement text is always treated as a normal data character and will not terminate the literal. For example, this is well-formed: ]]> while this is not: <!ENTITY EndAttr "27'" > <element attribute='a-&EndAttr;>

Notify

When the name of an unparsed entity appears as a token in the value of an attribute of declared type ENTITY or ENTITIES, a validating processor must inform the application of the system and public (if any) identifiers for both the entity and its associated notation.

Bypassed

When a general entity reference appears in the EntityValue in an entity declaration, it is bypassed and left as is.

Included as PE

Just as with external parsed entities, parameter entities need only be included if validating. When a parameter-entity reference is recognized in the DTD and included, its replacement text is enlarged by the attachment of one leading and one following space (#x20) character; the intent is to constrain the replacement text of parameter entities to contain an integral number of grammatical tokens in the DTD.

Construction of Internal Entity Replacement Text

In discussing the treatment of internal entities, it is useful to distinguish two forms of the entity's value. The literal entity value is the quoted string actually present in the entity declaration, corresponding to the non-terminal EntityValue. The replacement text is the content of the entity, after replacement of character references and parameter-entity references.

The literal entity value as given in an internal entity declaration (EntityValue) may contain character, parameter-entity, and general-entity references. Such references must be contained entirely within the literal entity value. The actual replacement text that is included as described above must contain the replacement text of any parameter entities referred to, and must contain the character referred to, in place of any character references in the literal entity value; however, general-entity references must be left as-is, unexpanded. For example, given the following declarations: ]]> then the replacement text for the entity "book" is: La Peste: Albert Camus, © 1947 Éditions Gallimard. &rights; The general-entity reference "&rights;" would be expanded should the reference "&book;" appear in the document's content or an attribute value.

These simple rules may have complex interactions; for a detailed discussion of a difficult example, see .

Predefined Entities

Entity and character references can both be used to escape the left angle bracket, ampersand, and other delimiters. A set of general entities (&magicents;) is specified for this purpose. Numeric character references may also be used; they are expanded immediately when recognized and must be treated as character data, so the numeric character references "&#60;" and "&#38;" may be used to escape < and & when they occur in character data.

All XML processors must recognize these entities whether they are declared or not. For interoperability, valid XML documents should declare these entities, like any others, before using them. If the entities in question are declared, they must be declared as internal entities whose replacement text is the single character being escaped or a character reference to that character, as shown below. ]]> Note that the < and & characters in the declarations of "lt" and "amp" are doubly escaped to meet the requirement that entity replacement be well-formed.

Notation Declarations

Notations identify by name the format of unparsed entities, the format of elements which bear a notation attribute, or the application to which a processing instruction is addressed.

Notation declarations provide a name for the notation, for use in entity and attribute-list declarations and in attribute specifications, and an external identifier for the notation which may allow an XML processor or its client application to locate a helper application capable of processing data in the given notation. Notation Declarations NotationDecl '<!NOTATION' S Name S (ExternalID | PublicID) S? '>' PublicID 'PUBLIC' S PubidLiteral

XML processors must provide applications with the name and external identifier(s) of any notation declared and referred to in an attribute value, attribute definition, or entity declaration. They may additionally resolve the external identifier into the system identifier, file name, or other information needed to allow the application to call a processor for data in the notation described. (It is not an error, however, for XML documents to declare and refer to notations for which notation-specific applications are not available on the system where the XML processor or application is running.)

Document Entity

The document entity serves as the root of the entity tree and a starting-point for an XML processor. This specification does not specify how the document entity is to be located by an XML processor; unlike other entities, the document entity has no name and might well appear on a processor input stream without any identification at all.

Conformance Validating and Non-Validating Processors

Conforming XML processors fall into two classes: validating and non-validating.

Validating and non-validating processors alike must report violations of this specification's well-formedness constraints in the content of the document entity and any other parsed entities that they read.

Validating processors must report violations of the constraints expressed by the declarations in the DTD, and failures to fulfill the validity constraints given in this specification. To accomplish this, validating XML processors must read and process the entire DTD and all external parsed entities referenced in the document.

Non-validating processors are required to check only the document entity, including the entire internal DTD subset, for well-formedness. While they are not required to check the document for validity, they are required to process all the declarations they read in the internal DTD subset and in any parameter entity that they read, up to the first reference to a parameter entity that they do not read; that is to say, they must use the information in those declarations to normalize attribute values, include the replacement text of internal entities, and supply default attribute values. They must not process entity declarations or attribute-list declarations encountered after a reference to a parameter entity that is not read, since the entity may have contained overriding declarations.

Using XML Processors

The behavior of a validating XML processor is highly predictable; it must read every piece of a document and report all well-formedness and validity violations. Less is required of a non-validating processor; it need not read any part of the document other than the document entity. This has two effects that may be important to users of XML processors:

Certain well-formedness errors, specifically those that require reading external entities, may not be detected by a non-validating processor. Examples include the constraints entitled Entity Declared, Parsed Entity, and No Recursion, as well as some of the cases described as forbidden in .

The information passed from the processor to the application may vary, depending on whether the processor reads parameter and external entities. For example, a non-validating processor may not normalize attribute values, include the replacement text of internal entities, or supply default attribute values, where doing so depends on having read declarations in external or parameter entities.

For maximum reliability in interoperating between different XML processors, applications which use non-validating processors should not rely on any behaviors not required of such processors. Applications which require facilities such as the use of default attributes or internal entities which are declared in external entities should use validating XML processors.

Notation

The formal grammar of XML is given in this specification using a simple Extended Backus-Naur Form (EBNF) notation. Each rule in the grammar defines one symbol, in the form symbol ::= expression

Symbols are written with an initial capital letter if they are defined by a regular expression, or with an initial lower case letter otherwise. Literal strings are quoted.

Within the expression on the right-hand side of a rule, the following expressions are used to match strings of one or more characters:

where N is a hexadecimal integer, the expression matches the character in ISO/IEC 10646 whose canonical (UCS-4) code value, when interpreted as an unsigned binary number, has the value indicated. The number of leading zeros in the #xN form is insignificant; the number of leading zeros in the corresponding code value is governed by the character encoding in use and is not significant for XML.

matches any character with a value in the range(s) indicated (inclusive).

matches any character with a value outside the range indicated.

matches any character with a value not among the characters given.

matches a literal string matching that given inside the double quotes.

matches a literal string matching that given inside the single quotes.

These symbols may be combined to match more complex patterns as follows, where A and B represent simple expressions:

expression is treated as a unit and may be combined as described in this list.

matches A or nothing; optional A.

matches A followed by B.

matches A or B but not both.

matches any string that matches A but does not match B.

matches one or more occurrences of A.

matches zero or more occurrences of A.

Other notations used in the productions are:

comment.

well-formedness constraint; this identifies by name a constraint on well-formed documents associated with a production.

validity constraint; this identifies by name a constraint on valid documents associated with a production.

References Normative References (Internet Assigned Numbers Authority) Official Names for Character Sets, ed. Keld Simonsen et al. See ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets. IETF (Internet Engineering Task Force). RFC 1766: Tags for the Identification of Languages, ed. H. Alvestrand. 1995. (International Organization for Standardization). ISO 639:1988 (E). Code for the representation of names of languages. [Geneva]: International Organization for Standardization, 1988. (International Organization for Standardization). ISO 3166-1:1997 (E). Codes for the representation of names of countries and their subdivisions — Part 1: Country codes [Geneva]: International Organization for Standardization, 1997. ISO (International Organization for Standardization). ISO/IEC 10646-1993 (E). Information technology — Universal Multiple-Octet Coded Character Set (UCS) — Part 1: Architecture and Basic Multilingual Plane. [Geneva]: International Organization for Standardization, 1993 (plus amendments AM 1 through AM 7). The Unicode Consortium. The Unicode Standard, Version 2.0. Reading, Mass.: Addison-Wesley Developers Press, 1996. Other References Aho, Alfred V., Ravi Sethi, and Jeffrey D. Ullman. Compilers: Principles, Techniques, and Tools. Reading: Addison-Wesley, 1986, rpt. corr. 1988. Berners-Lee, T., R. Fielding, and L. Masinter. Uniform Resource Identifiers (URI): Generic Syntax and Semantics. 1997. (Work in progress; see updates to RFC1738.) Brggemann-Klein, Anne. Regular Expressions into Finite Automata. Extended abstract in I. Simon, Hrsg., LATIN 1992, S. 97-98. Springer-Verlag, Berlin 1992. Full Version in Theoretical Computer Science 120: 197-213, 1993. Brggemann-Klein, Anne, and Derick Wood. Deterministic Regular Languages. Universitt Freiburg, Institut fr Informatik, Bericht 38, Oktober 1991. James Clark. Comparison of SGML and XML. See http://www.w3.org/TR/NOTE-sgml-xml-971215. IETF (Internet Engineering Task Force). RFC 1738: Uniform Resource Locators (URL), ed. T. Berners-Lee, L. Masinter, M. McCahill. 1994. IETF (Internet Engineering Task Force). RFC 1808: Relative Uniform Resource Locators, ed. R. Fielding. 1995. IETF (Internet Engineering Task Force). RFC 2141: URN Syntax, ed. R. Moats. 1997. ISO (International Organization for Standardization). ISO 8879:1986(E). Information processing — Text and Office Systems — Standard Generalized Markup Language (SGML). First edition — 1986-10-15. [Geneva]: International Organization for Standardization, 1986. ISO (International Organization for Standardization). ISO/IEC 10744-1992 (E). Information technology — Hypermedia/Time-based Structuring Language (HyTime). [Geneva]: International Organization for Standardization, 1992. Extended Facilities Annexe. [Geneva]: International Organization for Standardization, 1996. Character Classes

Following the characteristics defined in the Unicode standard, characters are classed as base characters (among others, these contain the alphabetic characters of the Latin alphabet, without diacritics), ideographic characters, and combining characters (among others, this class contains most diacritics); these classes combine to form the class of letters. Digits and extenders are also distinguished. Characters Letter BaseChar | Ideographic BaseChar [#x0041-#x005A] | [#x0061-#x007A] | [#x00C0-#x00D6] | [#x00D8-#x00F6] | [#x00F8-#x00FF] | [#x0100-#x0131] | [#x0134-#x013E] | [#x0141-#x0148] | [#x014A-#x017E] | [#x0180-#x01C3] | [#x01CD-#x01F0] | [#x01F4-#x01F5] | [#x01FA-#x0217] | [#x0250-#x02A8] | [#x02BB-#x02C1] | #x0386 | [#x0388-#x038A] | #x038C | [#x038E-#x03A1] | [#x03A3-#x03CE] | [#x03D0-#x03D6] | #x03DA | #x03DC | #x03DE | #x03E0 | [#x03E2-#x03F3] | [#x0401-#x040C] | [#x040E-#x044F] | [#x0451-#x045C] | [#x045E-#x0481] | [#x0490-#x04C4] | [#x04C7-#x04C8] | [#x04CB-#x04CC] | [#x04D0-#x04EB] | [#x04EE-#x04F5] | [#x04F8-#x04F9] | [#x0531-#x0556] | #x0559 | [#x0561-#x0586] | [#x05D0-#x05EA] | [#x05F0-#x05F2] | [#x0621-#x063A] | [#x0641-#x064A] | [#x0671-#x06B7] | [#x06BA-#x06BE] | [#x06C0-#x06CE] | [#x06D0-#x06D3] | #x06D5 | [#x06E5-#x06E6] | [#x0905-#x0939] | #x093D | [#x0958-#x0961] | [#x0985-#x098C] | [#x098F-#x0990] | [#x0993-#x09A8] | [#x09AA-#x09B0] | #x09B2 | [#x09B6-#x09B9] | [#x09DC-#x09DD] | [#x09DF-#x09E1] | [#x09F0-#x09F1] | [#x0A05-#x0A0A] | [#x0A0F-#x0A10] | [#x0A13-#x0A28] | [#x0A2A-#x0A30] | [#x0A32-#x0A33] | [#x0A35-#x0A36] | [#x0A38-#x0A39] | [#x0A59-#x0A5C] | #x0A5E | [#x0A72-#x0A74] | [#x0A85-#x0A8B] | #x0A8D | [#x0A8F-#x0A91] | [#x0A93-#x0AA8] | [#x0AAA-#x0AB0] | [#x0AB2-#x0AB3] | [#x0AB5-#x0AB9] | #x0ABD | #x0AE0 | [#x0B05-#x0B0C] | [#x0B0F-#x0B10] | [#x0B13-#x0B28] | [#x0B2A-#x0B30] | [#x0B32-#x0B33] | [#x0B36-#x0B39] | #x0B3D | [#x0B5C-#x0B5D] | [#x0B5F-#x0B61] | [#x0B85-#x0B8A] | [#x0B8E-#x0B90] | [#x0B92-#x0B95] | [#x0B99-#x0B9A] | #x0B9C | [#x0B9E-#x0B9F] | [#x0BA3-#x0BA4] | [#x0BA8-#x0BAA] | [#x0BAE-#x0BB5] | [#x0BB7-#x0BB9] | [#x0C05-#x0C0C] | [#x0C0E-#x0C10] | [#x0C12-#x0C28] | [#x0C2A-#x0C33] | [#x0C35-#x0C39] | [#x0C60-#x0C61] | [#x0C85-#x0C8C] | [#x0C8E-#x0C90] | [#x0C92-#x0CA8] | [#x0CAA-#x0CB3] | [#x0CB5-#x0CB9] | #x0CDE | [#x0CE0-#x0CE1] | [#x0D05-#x0D0C] | [#x0D0E-#x0D10] | [#x0D12-#x0D28] | [#x0D2A-#x0D39] | [#x0D60-#x0D61] | [#x0E01-#x0E2E] | #x0E30 | [#x0E32-#x0E33] | [#x0E40-#x0E45] | [#x0E81-#x0E82] | #x0E84 | [#x0E87-#x0E88] | #x0E8A | #x0E8D | [#x0E94-#x0E97] | [#x0E99-#x0E9F] | [#x0EA1-#x0EA3] | #x0EA5 | #x0EA7 | [#x0EAA-#x0EAB] | [#x0EAD-#x0EAE] | #x0EB0 | [#x0EB2-#x0EB3] | #x0EBD | [#x0EC0-#x0EC4] | [#x0F40-#x0F47] | [#x0F49-#x0F69] | [#x10A0-#x10C5] | [#x10D0-#x10F6] | #x1100 | [#x1102-#x1103] | [#x1105-#x1107] | #x1109 | [#x110B-#x110C] | [#x110E-#x1112] | #x113C | #x113E | #x1140 | #x114C | #x114E | #x1150 | [#x1154-#x1155] | #x1159 | [#x115F-#x1161] | #x1163 | #x1165 | #x1167 | #x1169 | [#x116D-#x116E] | [#x1172-#x1173] | #x1175 | #x119E | #x11A8 | #x11AB | [#x11AE-#x11AF] | [#x11B7-#x11B8] | #x11BA | [#x11BC-#x11C2] | #x11EB | #x11F0 | #x11F9 | [#x1E00-#x1E9B] | [#x1EA0-#x1EF9] | [#x1F00-#x1F15] | [#x1F18-#x1F1D] | [#x1F20-#x1F45] | [#x1F48-#x1F4D] | [#x1F50-#x1F57] | #x1F59 | #x1F5B | #x1F5D | [#x1F5F-#x1F7D] | [#x1F80-#x1FB4] | [#x1FB6-#x1FBC] | #x1FBE | [#x1FC2-#x1FC4] | [#x1FC6-#x1FCC] | [#x1FD0-#x1FD3] | [#x1FD6-#x1FDB] | [#x1FE0-#x1FEC] | [#x1FF2-#x1FF4] | [#x1FF6-#x1FFC] | #x2126 | [#x212A-#x212B] | #x212E | [#x2180-#x2182] | [#x3041-#x3094] | [#x30A1-#x30FA] | [#x3105-#x312C] | [#xAC00-#xD7A3] Ideographic [#x4E00-#x9FA5] | #x3007 | [#x3021-#x3029] CombiningChar [#x0300-#x0345] | [#x0360-#x0361] | [#x0483-#x0486] | [#x0591-#x05A1] | [#x05A3-#x05B9] | [#x05BB-#x05BD] | #x05BF | [#x05C1-#x05C2] | #x05C4 | [#x064B-#x0652] | #x0670 | [#x06D6-#x06DC] | [#x06DD-#x06DF] | [#x06E0-#x06E4] | [#x06E7-#x06E8] | [#x06EA-#x06ED] | [#x0901-#x0903] | #x093C | [#x093E-#x094C] | #x094D | [#x0951-#x0954] | [#x0962-#x0963] | [#x0981-#x0983] | #x09BC | #x09BE | #x09BF | [#x09C0-#x09C4] | [#x09C7-#x09C8] | [#x09CB-#x09CD] | #x09D7 | [#x09E2-#x09E3] | #x0A02 | #x0A3C | #x0A3E | #x0A3F | [#x0A40-#x0A42] | [#x0A47-#x0A48] | [#x0A4B-#x0A4D] | [#x0A70-#x0A71] | [#x0A81-#x0A83] | #x0ABC | [#x0ABE-#x0AC5] | [#x0AC7-#x0AC9] | [#x0ACB-#x0ACD] | [#x0B01-#x0B03] | #x0B3C | [#x0B3E-#x0B43] | [#x0B47-#x0B48] | [#x0B4B-#x0B4D] | [#x0B56-#x0B57] | [#x0B82-#x0B83] | [#x0BBE-#x0BC2] | [#x0BC6-#x0BC8] | [#x0BCA-#x0BCD] | #x0BD7 | [#x0C01-#x0C03] | [#x0C3E-#x0C44] | [#x0C46-#x0C48] | [#x0C4A-#x0C4D] | [#x0C55-#x0C56] | [#x0C82-#x0C83] | [#x0CBE-#x0CC4] | [#x0CC6-#x0CC8] | [#x0CCA-#x0CCD] | [#x0CD5-#x0CD6] | [#x0D02-#x0D03] | [#x0D3E-#x0D43] | [#x0D46-#x0D48] | [#x0D4A-#x0D4D] | #x0D57 | #x0E31 | [#x0E34-#x0E3A] | [#x0E47-#x0E4E] | #x0EB1 | [#x0EB4-#x0EB9] | [#x0EBB-#x0EBC] | [#x0EC8-#x0ECD] | [#x0F18-#x0F19] | #x0F35 | #x0F37 | #x0F39 | #x0F3E | #x0F3F | [#x0F71-#x0F84] | [#x0F86-#x0F8B] | [#x0F90-#x0F95] | #x0F97 | [#x0F99-#x0FAD] | [#x0FB1-#x0FB7] | #x0FB9 | [#x20D0-#x20DC] | #x20E1 | [#x302A-#x302F] | #x3099 | #x309A Digit [#x0030-#x0039] | [#x0660-#x0669] | [#x06F0-#x06F9] | [#x0966-#x096F] | [#x09E6-#x09EF] | [#x0A66-#x0A6F] | [#x0AE6-#x0AEF] | [#x0B66-#x0B6F] | [#x0BE7-#x0BEF] | [#x0C66-#x0C6F] | [#x0CE6-#x0CEF] | [#x0D66-#x0D6F] | [#x0E50-#x0E59] | [#x0ED0-#x0ED9] | [#x0F20-#x0F29] Extender #x00B7 | #x02D0 | #x02D1 | #x0387 | #x0640 | #x0E46 | #x0EC6 | #x3005 | [#x3031-#x3035] | [#x309D-#x309E] | [#x30FC-#x30FE]

The character classes defined here can be derived from the Unicode character database as follows:

Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.

Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.

Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.

Characters which have a font or compatibility decomposition (i.e. those with a "compatibility formatting tag" in field 5 of the database -- marked by field 5 beginning with a "<") are not allowed.

The following characters are treated as name-start characters rather than name characters, because the property file classifies them as Alphabetic: [#x02BB-#x02C1], #x0559, #x06E5, #x06E6.

Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).

Character #x00B7 is classified as an extender, because the property list so identifies it.

Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.

Characters ':' and '_' are allowed as name-start characters.

Characters '-' and '.' are allowed as name characters.

XML and SGML

XML is designed to be a subset of SGML, in that every valid XML document should also be a conformant SGML document. For a detailed comparison of the additional restrictions that XML places on documents beyond those of SGML, see .

Expansion of Entity and Character References

This appendix contains some examples illustrating the sequence of entity- and character-reference recognition and expansion, as specified in .

If the DTD contains the declaration An ampersand (&#38;) may be escaped numerically (&#38;#38;) or with a general entity (&amp;).

" > ]]> then the XML processor will recognize the character references when it parses the entity declaration, and resolve them before storing the following string as the value of the entity "example": An ampersand (&) may be escaped numerically (&#38;) or with a general entity (&amp;).

]]>
A reference in the document to "&example;" will cause the text to be reparsed, at which time the start- and end-tags of the "p" element will be recognized and the three references will be recognized and expanded, resulting in a "p" element with the following content (all data, no delimiters or markup):

A more complex example will illustrate the rules and their effects fully. In the following example, the line numbers are solely for reference. 2 4 5 ' > 6 %xx; 7 ]> 8 This sample shows a &tricky; method. ]]> This produces the following:

in line 4, the reference to character 37 is expanded immediately, and the parameter entity "xx" is stored in the symbol table with the value "%zz;". Since the replacement text is not rescanned, the reference to parameter entity "zz" is not recognized. (And it would be an error if it were, since "zz" is not yet declared.)

in line 5, the character reference "&#60;" is expanded immediately and the parameter entity "zz" is stored with the replacement text "<!ENTITY tricky "error-prone" >", which is a well-formed entity declaration.

in line 6, the reference to "xx" is recognized, and the replacement text of "xx" (namely "%zz;") is parsed. The reference to "zz" is recognized in its turn, and its replacement text ("<!ENTITY tricky "error-prone" >") is parsed. The general entity "tricky" has now been declared, with the replacement text "error-prone".

in line 8, the reference to the general entity "tricky" is recognized, and it is expanded, so the full content of the "test" element is the self-describing (and ungrammatical) string This sample shows a error-prone method.

Deterministic Content Models

For compatibility, it is required that content models in element type declarations be deterministic.

SGML requires deterministic content models (it calls them "unambiguous"); XML processors built using SGML systems may flag non-deterministic content models as errors.

For example, the content model ((b, c) | (b, d)) is non-deterministic, because given an initial b the parser cannot know which b in the model is being matched without looking ahead to see which element follows the b. In this case, the two references to b can be collapsed into a single reference, making the model read (b, (c | d)). An initial b now clearly matches only a single name in the content model. The parser doesn't need to look ahead to see what follows; either c or d would be accepted.

More formally: a finite state automaton may be constructed from the content model using the standard algorithms, e.g. algorithm 3.5 in section 3.9 of Aho, Sethi, and Ullman . In many such algorithms, a follow set is constructed for each position in the regular expression (i.e., each leaf node in the syntax tree for the regular expression); if any position has a follow set in which more than one following position is labeled with the same element type name, then the content model is in error and may be reported as an error.

Algorithms exist which allow many but not all non-deterministic content models to be reduced automatically to equivalent deterministic models; see Brggemann-Klein 1991 .

Autodetection of Character Encodings

The XML encoding declaration functions as an internal label on each entity, indicating which character encoding is in use. Before an XML processor can read the internal label, however, it apparently has to know what character encoding is in use—which is what the internal label is trying to indicate. In the general case, this is a hopeless situation. It is not entirely hopeless in XML, however, because XML limits the general case in two ways: each implementation is assumed to support only a finite set of character encodings, and the XML encoding declaration is restricted in position and content in order to make it feasible to autodetect the character encoding in use in each entity in normal cases. Also, in many cases other sources of information are available in addition to the XML data stream itself. Two cases may be distinguished, depending on whether the XML entity is presented to the processor without, or with, any accompanying (external) information. We consider the first case first.

Because each XML entity not in UTF-8 or UTF-16 format must begin with an XML encoding declaration, in which the first characters must be '<?xml', any conforming processor can detect, after two to four octets of input, which of the following cases apply. In reading this list, it may help to know that in UCS-4, '<' is "#x0000003C" and '?' is "#x0000003F", and the Byte Order Mark required of UTF-16 data streams is "#xFEFF".

00 00 00 3C: UCS-4, big-endian machine (1234 order)

3C 00 00 00: UCS-4, little-endian machine (4321 order)

00 00 3C 00: UCS-4, unusual octet order (2143)

00 3C 00 00: UCS-4, unusual octet order (3412)

FE FF: UTF-16, big-endian

FF FE: UTF-16, little-endian

00 3C 00 3F: UTF-16, big-endian, no Byte Order Mark (and thus, strictly speaking, in error)

3C 00 3F 00: UTF-16, little-endian, no Byte Order Mark (and thus, strictly speaking, in error)

3C 3F 78 6D: UTF-8, ISO 646, ASCII, some part of ISO 8859, Shift-JIS, EUC, or any other 7-bit, 8-bit, or mixed-width encoding which ensures that the characters of ASCII have their normal positions, width, and values; the actual encoding declaration must be read to detect which of these applies, but since all of these encodings use the same bit patterns for the ASCII characters, the encoding declaration itself may be read reliably

4C 6F A7 94: EBCDIC (in some flavor; the full encoding declaration must be read to tell which code page is in use)

other: UTF-8 without an encoding declaration, or else the data stream is corrupt, fragmentary, or enclosed in a wrapper of some kind

This level of autodetection is enough to read the XML encoding declaration and parse the character-encoding identifier, which is still necessary to distinguish the individual members of each family of encodings (e.g. to tell UTF-8 from 8859, and the parts of 8859 from each other, or to distinguish the specific EBCDIC code page in use, and so on).

Because the contents of the encoding declaration are restricted to ASCII characters, a processor can reliably read the entire encoding declaration as soon as it has detected which family of encodings is in use. Since in practice, all widely used character encodings fall into one of the categories above, the XML encoding declaration allows reasonably reliable in-band labeling of character encodings, even when external sources of information at the operating-system or transport-protocol level are unreliable.

Once the processor has detected the character encoding in use, it can act appropriately, whether by invoking a separate input routine for each case, or by calling the proper conversion function on each character of input.

Like any self-labeling system, the XML encoding declaration will not work if any software changes the entity's character set or encoding without updating the encoding declaration. Implementors of character-encoding routines should be careful to ensure the accuracy of the internal and external information used to label the entity.

The second possible case occurs when the XML entity is accompanied by encoding information, as in some file systems and some network protocols. When multiple sources of information are available, their relative priority and the preferred method of handling conflict should be specified as part of the higher-level protocol used to deliver XML. Rules for the relative priority of the internal label and the MIME-type label in an external header, for example, should be part of the RFC document defining the text/xml and application/xml MIME types. In the interests of interoperability, however, the following rules are recommended.

If an XML entity is in a file, the Byte-Order Mark and encoding-declaration PI are used (if present) to determine the character encoding. All other heuristics and sources of information are solely for error recovery.

If an XML entity is delivered with a MIME type of text/xml, then the charset parameter on the MIME type determines the character encoding method; all other heuristics and sources of information are solely for error recovery.

If an XML entity is delivered with a MIME type of application/xml, then the Byte-Order Mark and encoding-declaration PI are used (if present) to determine the character encoding. All other heuristics and sources of information are solely for error recovery.

These rules apply only in the absence of protocol-level documentation; in particular, when the MIME types text/xml and application/xml are defined, the recommendations of the relevant RFC will supersede these rules.

W3C XML Working Group

This specification was prepared and approved for publication by the W3C XML Working Group (WG). WG approval of this specification does not necessarily imply that all WG members voted for its approval. The current and former members of the XML WG are:

Jon Bosak, SunChair James ClarkTechnical Lead Tim Bray, Textuality and NetscapeXML Co-editor Jean Paoli, MicrosoftXML Co-editor C. M. Sperberg-McQueen, U. of Ill.XML Co-editor Dan Connolly, W3CW3C Liaison Paula Angerstein, Texcel Steve DeRose, INSO Dave Hollander, HP Eliot Kimber, ISOGEN Eve Maler, ArborText Tom Magliery, NCSA Murray Maloney, Muzmo and Grif Makoto Murata, Fuji Xerox Information Systems Joel Nava, Adobe Conleth O'Connell, Vignette Peter Sharpe, SoftQuad John Tigue, DataChannel
dom4j-1.6.1/xml/xhtml.xml0000644000175000017500000000223310242117776014551 0ustar ebourgebourg ]>

This is some HTML & and entites

Here are some entities

home page

This is some text containing some entities

God fortsättning på det nya millenniet!


http://foo.com/bar?a=123&b=456&d=d9d9d something

Here is some CDATA


quick start guide dom4j-1.6.1/xml/dtd/0000755000175000017500000000000012133227266013443 5ustar ebourgebourgdom4j-1.6.1/xml/dtd/external.xml0000644000175000017500000000022010242120006015760 0ustar ebourgebourg Hello, world! dom4j-1.6.1/xml/dtd/mixed.xml0000644000175000017500000000062610242120010015251 0ustar ebourgebourg ]> Hello, world! dom4j-1.6.1/xml/dtd/sample.dtd0000644000175000017500000000026510242120017015405 0ustar ebourgebourg dom4j-1.6.1/xml/dtd/internal.xml0000644000175000017500000000055210242120014015761 0ustar ebourgebourg ]> Hello, world! dom4j-1.6.1/src/0000755000175000017500000000000010242120020012632 5ustar ebourgebourgdom4j-1.6.1/src/conf/0000755000175000017500000000000012133227266013604 5ustar ebourgebourgdom4j-1.6.1/src/conf/repository.dtd0000644000175000017500000000155410242120015016504 0ustar ebourgebourg dom4j-1.6.1/src/conf/MANIFEST.MF0000644000175000017500000000040410242120020015207 0ustar ebourgebourgManifest-Version: 1.0 Extension-Name: org.dom4j Specification-Title: dom4j Specification-Version: 1.3 Specification-Vendor: MetaStuff Ltd. Created-By: Ant 1.4.1 Implementation-Vendor: MetaStuff Ltd. Implementation-Version: 1.3 Implementation-Title: dom4j dom4j-1.6.1/src/conf/xsa.xml0000644000175000017500000000140410242120010015072 0ustar ebourgebourg MetaStuff Ltd. info@dom4j.org http://dom4j.org dom4j 1.3 20020317 http://dom4j.org/ dom4j is a simple and flexible open source library for working with XML, XPath and XSLT on the Java platform using the Java Collections Framework with full integration with DOM, SAX and JAXP. This release is primarily a bug fix release. dom4j-1.6.1/src/conf/repository.xml0000644000175000017500000000204110242120021016516 0ustar ebourgebourg dom4j: the flexible XML framework for Java http://dom4j.org production dom4j-1.0.jar current CVS HEAD dom4j-daily.jar dom4j-1.6.1/src/java/0000755000175000017500000000000010242117775013602 5ustar ebourgebourgdom4j-1.6.1/src/java/org/0000755000175000017500000000000010242117775014371 5ustar ebourgebourgdom4j-1.6.1/src/java/org/dom4j/0000755000175000017500000000000012133227266015404 5ustar ebourgebourgdom4j-1.6.1/src/java/org/dom4j/bean/0000755000175000017500000000000012133227266016311 5ustar ebourgebourgdom4j-1.6.1/src/java/org/dom4j/bean/BeanAttribute.java0000644000175000017500000000661510242120015021674 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.bean; import org.dom4j.Element; import org.dom4j.QName; import org.dom4j.tree.AbstractAttribute; /** *

* BeanAttribute represents a mutable XML attribute which is * backed by a property of the JavaBean of its parent element. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public class BeanAttribute extends AbstractAttribute { /** The list of Bean attributes */ private final BeanAttributeList beanList; /** The index in the Bean attribute list */ private final int index; public BeanAttribute(BeanAttributeList beanList, int index) { this.beanList = beanList; this.index = index; } public QName getQName() { return beanList.getQName(index); } public Element getParent() { return beanList.getParent(); } public String getValue() { Object data = getData(); return (data != null) ? data.toString() : null; } public void setValue(String data) { beanList.setData(index, data); } public Object getData() { return beanList.getData(index); } public void setData(Object data) { beanList.setData(index, data); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/bean/BeanDocumentFactory.java0000644000175000017500000001105410242120010023023 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.bean; import org.dom4j.Attribute; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.QName; import org.dom4j.tree.DefaultAttribute; import org.xml.sax.Attributes; /** *

* BeanDocumentFactory is a factory of DOM4J objects which may be * BeanElements which are backed by JavaBeans and their properties. *

* *

* The tree built allows full XPath expressions from anywhere on the tree. *

* * @author James Strachan * @version $Revision: 1.14 $ */ public class BeanDocumentFactory extends DocumentFactory { /** The Singleton instance */ private static BeanDocumentFactory singleton = new BeanDocumentFactory(); /** *

* Access to the singleton instance of this factory. *

* * @return the default singleon instance */ public static DocumentFactory getInstance() { return singleton; } // Factory methods public Element createElement(QName qname) { Object bean = createBean(qname); if (bean == null) { return new BeanElement(qname); } else { return new BeanElement(qname, bean); } } public Element createElement(QName qname, Attributes attributes) { Object bean = createBean(qname, attributes); if (bean == null) { return new BeanElement(qname); } else { return new BeanElement(qname, bean); } } public Attribute createAttribute(Element owner, QName qname, String value) { return new DefaultAttribute(qname, value); } // Implementation methods protected Object createBean(QName qname) { return null; } protected Object createBean(QName qname, Attributes attributes) { String value = attributes.getValue("class"); if (value != null) { try { Class beanClass = Class.forName(value, true, BeanDocumentFactory.class.getClassLoader()); return beanClass.newInstance(); } catch (Exception e) { handleException(e); } } return null; } protected void handleException(Exception e) { // ignore introspection exceptions System.out.println("#### Warning: couldn't create bean: " + e); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/bean/BeanAttributeList.java0000644000175000017500000001376510242120004022532 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.bean; import java.util.AbstractList; import org.dom4j.Attribute; import org.dom4j.QName; /** *

* BeanAttributeList implements a list of Attributes which are * the properties of a JavaBean. *

* * @author James Strachan * @version $Revision: 1.9 $ */ public class BeanAttributeList extends AbstractList { /** The BeanElement that this */ private BeanElement parent; /** The BeanElement that this */ private BeanMetaData beanMetaData; /** The attributes */ private BeanAttribute[] attributes; public BeanAttributeList(BeanElement parent, BeanMetaData beanMetaData) { this.parent = parent; this.beanMetaData = beanMetaData; this.attributes = new BeanAttribute[beanMetaData.attributeCount()]; } public BeanAttributeList(BeanElement parent) { this.parent = parent; Object data = parent.getData(); Class beanClass = (data != null) ? data.getClass() : null; this.beanMetaData = BeanMetaData.get(beanClass); this.attributes = new BeanAttribute[beanMetaData.attributeCount()]; } public Attribute attribute(String name) { int index = beanMetaData.getIndex(name); return attribute(index); } public Attribute attribute(QName qname) { int index = beanMetaData.getIndex(qname); return attribute(index); } public BeanAttribute attribute(int index) { if ((index >= 0) && (index <= attributes.length)) { BeanAttribute attribute = attributes[index]; if (attribute == null) { attribute = createAttribute(parent, index); attributes[index] = attribute; } return attribute; } return null; } public BeanElement getParent() { return parent; } public QName getQName(int index) { return beanMetaData.getQName(index); } public Object getData(int index) { return beanMetaData.getData(index, parent.getData()); } public void setData(int index, Object data) { beanMetaData.setData(index, parent.getData(), data); } // List interface // ------------------------------------------------------------------------- public int size() { return attributes.length; } public Object get(int index) { BeanAttribute attribute = attributes[index]; if (attribute == null) { attribute = createAttribute(parent, index); attributes[index] = attribute; } return attribute; } public boolean add(Object object) { throw new UnsupportedOperationException("add(Object) unsupported"); } public void add(int index, Object object) { throw new UnsupportedOperationException("add(int,Object) unsupported"); } public Object set(int index, Object object) { throw new UnsupportedOperationException("set(int,Object) unsupported"); } public boolean remove(Object object) { return false; } public Object remove(int index) { BeanAttribute attribute = (BeanAttribute) get(index); Object oldValue = attribute.getValue(); attribute.setValue(null); return oldValue; } public void clear() { for (int i = 0, size = attributes.length; i < size; i++) { BeanAttribute attribute = attributes[i]; if (attribute != null) { attribute.setValue(null); } } } // Implementation methods // ------------------------------------------------------------------------- protected BeanAttribute createAttribute(BeanElement element, int index) { return new BeanAttribute(this, index); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/bean/BeanMetaData.java0000644000175000017500000001522310242120020021400 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.bean; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.dom4j.DocumentFactory; import org.dom4j.QName; /** *

* BeanMetaData contains metadata about a bean class. *

* * @author James Strachan * @version $Revision: 1.10 $ */ public class BeanMetaData { /** Empty arguments for reflection calls */ protected static final Object[] NULL_ARGS = {}; /** Singleton cache */ private static Map singletonCache = new HashMap(); private static final DocumentFactory DOCUMENT_FACTORY = BeanDocumentFactory .getInstance(); /** The class of the bean */ private Class beanClass; /** Property descriptors for the bean */ private PropertyDescriptor[] propertyDescriptors; /** QNames for the attributes */ private QName[] qNames; /** Read methods used for getting properties */ private Method[] readMethods; /** Write methods used for setting properties */ private Method[] writeMethods; /** Index of names and QNames to indices */ private Map nameMap = new HashMap(); public BeanMetaData(Class beanClass) { this.beanClass = beanClass; if (beanClass != null) { try { BeanInfo beanInfo = Introspector.getBeanInfo(beanClass); propertyDescriptors = beanInfo.getPropertyDescriptors(); } catch (IntrospectionException e) { handleException(e); } } if (propertyDescriptors == null) { propertyDescriptors = new PropertyDescriptor[0]; } int size = propertyDescriptors.length; qNames = new QName[size]; readMethods = new Method[size]; writeMethods = new Method[size]; for (int i = 0; i < size; i++) { PropertyDescriptor propertyDescriptor = propertyDescriptors[i]; String name = propertyDescriptor.getName(); QName qName = DOCUMENT_FACTORY.createQName(name); qNames[i] = qName; readMethods[i] = propertyDescriptor.getReadMethod(); writeMethods[i] = propertyDescriptor.getWriteMethod(); Integer index = new Integer(i); nameMap.put(name, index); nameMap.put(qName, index); } } /** * Static helper method to find and cache meta data objects for bean types * * @param beanClass * DOCUMENT ME! * * @return DOCUMENT ME! */ public static BeanMetaData get(Class beanClass) { BeanMetaData answer = (BeanMetaData) singletonCache.get(beanClass); if (answer == null) { answer = new BeanMetaData(beanClass); singletonCache.put(beanClass, answer); } return answer; } /** * DOCUMENT ME! * * @return the number of attribtutes for this bean type */ public int attributeCount() { return propertyDescriptors.length; } public BeanAttributeList createAttributeList(BeanElement parent) { return new BeanAttributeList(parent, this); } public QName getQName(int index) { return qNames[index]; } public int getIndex(String name) { Integer index = (Integer) nameMap.get(name); return (index != null) ? index.intValue() : (-1); } public int getIndex(QName qName) { Integer index = (Integer) nameMap.get(qName); return (index != null) ? index.intValue() : (-1); } public Object getData(int index, Object bean) { try { Method method = readMethods[index]; return method.invoke(bean, NULL_ARGS); } catch (Exception e) { handleException(e); return null; } } public void setData(int index, Object bean, Object data) { try { Method method = writeMethods[index]; Object[] args = {data}; method.invoke(bean, args); } catch (Exception e) { handleException(e); } } // Implementation methods // ------------------------------------------------------------------------- protected void handleException(Exception e) { // ignore introspection exceptions } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/bean/BeanElement.java0000644000175000017500000001455610242120006021325 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.bean; import java.util.List; import org.dom4j.Attribute; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.QName; import org.dom4j.tree.DefaultElement; import org.dom4j.tree.NamespaceStack; import org.xml.sax.Attributes; /** *

* BeanElement uses a Java Bean to store its attributes. *

* * @author James Strachan * @version $Revision: 1.15 $ */ public class BeanElement extends DefaultElement { /** The DocumentFactory instance used by default */ private static final DocumentFactory DOCUMENT_FACTORY = BeanDocumentFactory .getInstance(); /** The JavaBean which defines my attributes */ private Object bean; public BeanElement(String name, Object bean) { this(DOCUMENT_FACTORY.createQName(name), bean); } public BeanElement(String name, Namespace namespace, Object bean) { this(DOCUMENT_FACTORY.createQName(name, namespace), bean); } public BeanElement(QName qname, Object bean) { super(qname); this.bean = bean; } public BeanElement(QName qname) { super(qname); } /** * DOCUMENT ME! * * @return the JavaBean associated with this element */ public Object getData() { return bean; } public void setData(Object data) { this.bean = data; // force the attributeList to be lazily // created next time an attribute related // method is called again. setAttributeList(null); } public Attribute attribute(String name) { return getBeanAttributeList().attribute(name); } public Attribute attribute(QName qname) { return getBeanAttributeList().attribute(qname); } public Element addAttribute(String name, String value) { Attribute attribute = attribute(name); if (attribute != null) { attribute.setValue(value); } return this; } public Element addAttribute(QName qName, String value) { Attribute attribute = attribute(qName); if (attribute != null) { attribute.setValue(value); } return this; } public void setAttributes(List attributes) { throw new UnsupportedOperationException("Not implemented yet."); } // Method overridden from AbstractElement public void setAttributes(Attributes attributes, NamespaceStack namespaceStack, boolean noNamespaceAttributes) { String className = attributes.getValue("class"); if (className != null) { try { Class beanClass = Class.forName(className, true, BeanElement.class.getClassLoader()); this.setData(beanClass.newInstance()); for (int i = 0; i < attributes.getLength(); i++) { String attributeName = attributes.getLocalName(i); if (!"class".equalsIgnoreCase(attributeName)) { addAttribute(attributeName, attributes.getValue(i)); } } } catch (Exception ex) { // What to do here? ((BeanDocumentFactory) this.getDocumentFactory()) .handleException(ex); } } else { super.setAttributes(attributes, namespaceStack, noNamespaceAttributes); } } // Implementation methods // ------------------------------------------------------------------------- protected DocumentFactory getDocumentFactory() { return DOCUMENT_FACTORY; } protected BeanAttributeList getBeanAttributeList() { return (BeanAttributeList) attributeList(); } /** * A Factory Method pattern which lazily creates a List implementation used * to store content * * @return DOCUMENT ME! */ protected List createAttributeList() { return new BeanAttributeList(this); } protected List createAttributeList(int size) { return new BeanAttributeList(this); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/bean/package.html0000644000175000017500000000031210242117777020572 0ustar ebourgebourg

An implementation of the dom4j API which allows JavaBeans to be used to store and retrieve attribute values from Element.

dom4j-1.6.1/src/java/org/dom4j/Entity.java0000644000175000017500000000453310242120015017507 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; /** *

* Entity defines an XML entity. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public interface Entity extends Node { } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/Attribute.java0000644000175000017500000001325010242120015020172 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; /** *

* Attribute defines an XML attribute. An attribute may have a * name, an optional namespace and a value. *

* * @author James Strachan * @version $Revision: 1.9 $ */ public interface Attribute extends Node { /** *

* Returns the QName of this attribute which represents the * local name, the qualified name and the Namespace. *

* * @return the QName associated with this attribute */ QName getQName(); /** *

* Returns the Namespace of this element if one exists * otherwise null is returned returned. *

* * @return the Namespace associated with this node */ Namespace getNamespace(); /** *

* Sets the Namespace of this element or if this element is * read only then an UnsupportedOperationException is thrown. *

* * @param namespace * is the Namespace to associate with this element */ void setNamespace(Namespace namespace); /** *

* Returns the namespace prefix of this element if one exists otherwise an * empty String is returned. *

* * @return the prefix of the Namespace of this element or an * empty String */ String getNamespacePrefix(); /** *

* Returns the URI mapped to the namespace of this element if one exists * otherwise an empty String is returned. *

* * @return the URI for the Namespace of this element or an * empty String */ String getNamespaceURI(); /** *

* Returns the fully qualified name of this element. *

* *

* This will be the same as the value returned from {@link Node#getName()} * if this element has no namespace attached to this element or an * expression of the form * *

     * getNamespacePrefix() + ":" + getName()
     * 
* * will be returned. *

* * @return the fully qualified name of the element */ String getQualifiedName(); /** *

* Returns the value of the attribute. This method returns the same value as * the {@link Node#getText()}method. *

* * @return the value of the attribute */ String getValue(); /** *

* Sets the value of this attribute or this method will throw an * UnsupportedOperationException if it is read-only. *

* * @param value * is the new value of this attribute */ void setValue(String value); /** *

* Accesses the data of this attribute which may implement data typing * bindings such as XML Schema or Java Bean * bindings or will return the same value as {@link Node#getText()}. *

* * @return the attribute data */ Object getData(); /** *

* Sets the data value of this attribute if this element supports data * binding or calls {@link Node#setText(String)}if it doesn't. *

* * @param data * the attribute data */ void setData(Object data); } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/VisitorSupport.java0000644000175000017500000000606610242120023021271 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; /** *

* VisitorSupport is an abstract base class which is useful for * implementation inheritence or when using anonymous inner classes to create * simple Visitor implementations. *

* * @author James Strachan * @version $Revision: 1.6 $ */ public abstract class VisitorSupport implements Visitor { public VisitorSupport() { } public void visit(Document document) { } public void visit(DocumentType documentType) { } public void visit(Element node) { } public void visit(Attribute node) { } public void visit(CDATA node) { } public void visit(Comment node) { } public void visit(Entity node) { } public void visit(Namespace namespace) { } public void visit(ProcessingInstruction node) { } public void visit(Text node) { } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/QName.java0000644000175000017500000002232310242120004017227 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.dom4j.tree.QNameCache; import org.dom4j.util.SingletonStrategy; /** *

* QName represents a qualified name value of an XML element or * attribute. It consists of a local name and a {@link Namespace}instance. This * object is immutable. *

* * @author James Strachan */ public class QName implements Serializable { /** The Singleton instance */ private static SingletonStrategy singleton = null; static { try { String defaultSingletonClass = "org.dom4j.util.SimpleSingleton"; Class clazz = null; try { String singletonClass = defaultSingletonClass; singletonClass = System.getProperty( "org.dom4j.QName.singleton.strategy", singletonClass); clazz = Class.forName(singletonClass); } catch (Exception exc1) { try { String singletonClass = defaultSingletonClass; clazz = Class.forName(singletonClass); } catch (Exception exc2) { } } singleton = (SingletonStrategy) clazz.newInstance(); singleton.setSingletonClassName(QNameCache.class.getName()); } catch (Exception exc3) { } } /** The local name of the element or attribute */ private String name; /** The qualified name of the element or attribute */ private String qualifiedName; /** The Namespace of this element or attribute */ private transient Namespace namespace; /** A cached version of the hashcode for efficiency */ private int hashCode; /** The document factory used for this QName if specified or null */ private DocumentFactory documentFactory; public QName(String name) { this(name, Namespace.NO_NAMESPACE); } public QName(String name, Namespace namespace) { this.name = (name == null) ? "" : name; this.namespace = (namespace == null) ? Namespace.NO_NAMESPACE : namespace; } public QName(String name, Namespace namespace, String qualifiedName) { this.name = (name == null) ? "" : name; this.qualifiedName = qualifiedName; this.namespace = (namespace == null) ? Namespace.NO_NAMESPACE : namespace; } public static QName get(String name) { return getCache().get(name); } public static QName get(String name, Namespace namespace) { return getCache().get(name, namespace); } public static QName get(String name, String prefix, String uri) { if (((prefix == null) || (prefix.length() == 0)) && (uri == null)) { return QName.get(name); } else if ((prefix == null) || (prefix.length() == 0)) { return getCache().get(name, Namespace.get(uri)); } else if (uri == null) { return QName.get(name); } else { return getCache().get(name, Namespace.get(prefix, uri)); } } public static QName get(String qualifiedName, String uri) { if (uri == null) { return getCache().get(qualifiedName); } else { return getCache().get(qualifiedName, uri); } } public static QName get(String localName, Namespace namespace, String qualifiedName) { return getCache().get(localName, namespace, qualifiedName); } /** * DOCUMENT ME! * * @return the local name */ public String getName() { return name; } /** * DOCUMENT ME! * * @return the qualified name in the format prefix:localName */ public String getQualifiedName() { if (qualifiedName == null) { String prefix = getNamespacePrefix(); if ((prefix != null) && (prefix.length() > 0)) { qualifiedName = prefix + ":" + name; } else { qualifiedName = name; } } return qualifiedName; } /** * DOCUMENT ME! * * @return the namespace of this QName */ public Namespace getNamespace() { return namespace; } /** * DOCUMENT ME! * * @return the namespace URI of this QName */ public String getNamespacePrefix() { if (namespace == null) { return ""; } return namespace.getPrefix(); } /** * DOCUMENT ME! * * @return the namespace URI of this QName */ public String getNamespaceURI() { if (namespace == null) { return ""; } return namespace.getURI(); } /** * DOCUMENT ME! * * @return the hash code based on the qualified name and the URI of the * namespace. */ public int hashCode() { if (hashCode == 0) { hashCode = getName().hashCode() ^ getNamespaceURI().hashCode(); if (hashCode == 0) { hashCode = 0xbabe; } } return hashCode; } public boolean equals(Object object) { if (this == object) { return true; } else if (object instanceof QName) { QName that = (QName) object; // we cache hash codes so this should be quick if (hashCode() == that.hashCode()) { return getName().equals(that.getName()) && getNamespaceURI().equals(that.getNamespaceURI()); } } return false; } public String toString() { return super.toString() + " [name: " + getName() + " namespace: \"" + getNamespace() + "\"]"; } /** * DOCUMENT ME! * * @return the factory that should be used for Elements of this QName */ public DocumentFactory getDocumentFactory() { return documentFactory; } public void setDocumentFactory(DocumentFactory documentFactory) { this.documentFactory = documentFactory; } private void writeObject(ObjectOutputStream out) throws IOException { // We use writeObject() and not writeUTF() to minimize space // This allows for writing pointers to already written strings out.writeObject(namespace.getPrefix()); out.writeObject(namespace.getURI()); out.defaultWriteObject(); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { String prefix = (String) in.readObject(); String uri = (String) in.readObject(); in.defaultReadObject(); namespace = Namespace.get(prefix, uri); } private static QNameCache getCache() { QNameCache cache = (QNameCache) singleton.instance(); return cache; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */dom4j-1.6.1/src/java/org/dom4j/tree/0000755000175000017500000000000012133227266016343 5ustar ebourgebourgdom4j-1.6.1/src/java/org/dom4j/tree/SingleIterator.java0000644000175000017500000000566310242120014022131 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.util.Iterator; /** *

* SingleIterator is an {@link Iterator}over a single object * instance. *

* * @author James Strachan * @version $Revision: 1.9 $ */ public class SingleIterator implements Iterator { private boolean first = true; private Object object; public SingleIterator(Object object) { this.object = object; } public boolean hasNext() { return first; } public Object next() { Object answer = object; object = null; first = false; return answer; } public void remove() { throw new UnsupportedOperationException("remove() is not supported by " + "this iterator"); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/AbstractNode.java0000644000175000017500000001775210242120011021546 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.io.IOException; import java.io.Serializable; import java.io.Writer; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.NodeFilter; import org.dom4j.XPath; import org.dom4j.rule.Pattern; /** *

* AbstractNode is an abstract base class for tree implementors * to use for implementation inheritence. *

* * @author James Strachan * @version $Revision: 1.31 $ */ public abstract class AbstractNode implements Node, Cloneable, Serializable { protected static final String[] NODE_TYPE_NAMES = {"Node", "Element", "Attribute", "Text", "CDATA", "Entity", "Entity", "ProcessingInstruction", "Comment", "Document", "DocumentType", "DocumentFragment", "Notation", "Namespace", "Unknown" }; /** The DocumentFactory instance used by default */ private static final DocumentFactory DOCUMENT_FACTORY = DocumentFactory .getInstance(); public AbstractNode() { } public short getNodeType() { return UNKNOWN_NODE; } public String getNodeTypeName() { int type = getNodeType(); if ((type < 0) || (type >= NODE_TYPE_NAMES.length)) { return "Unknown"; } return NODE_TYPE_NAMES[type]; } public Document getDocument() { Element element = getParent(); return (element != null) ? element.getDocument() : null; } public void setDocument(Document document) { } public Element getParent() { return null; } public void setParent(Element parent) { } public boolean supportsParent() { return false; } public boolean isReadOnly() { return true; } public boolean hasContent() { return false; } public String getPath() { return getPath(null); } public String getUniquePath() { return getUniquePath(null); } public Object clone() { if (isReadOnly()) { return this; } else { try { Node answer = (Node) super.clone(); answer.setParent(null); answer.setDocument(null); return answer; } catch (CloneNotSupportedException e) { // should never happen throw new RuntimeException("This should never happen. Caught: " + e); } } } public Node detach() { Element parent = getParent(); if (parent != null) { parent.remove(this); } else { Document document = getDocument(); if (document != null) { document.remove(this); } } setParent(null); setDocument(null); return this; } public String getName() { return null; } public void setName(String name) { throw new UnsupportedOperationException("This node cannot be modified"); } public String getText() { return null; } public String getStringValue() { return getText(); } public void setText(String text) { throw new UnsupportedOperationException("This node cannot be modified"); } public void write(Writer writer) throws IOException { writer.write(asXML()); } // XPath methods public Object selectObject(String xpathExpression) { XPath xpath = createXPath(xpathExpression); return xpath.evaluate(this); } public List selectNodes(String xpathExpression) { XPath xpath = createXPath(xpathExpression); return xpath.selectNodes(this); } public List selectNodes(String xpathExpression, String comparisonXPathExpression) { return selectNodes(xpathExpression, comparisonXPathExpression, false); } public List selectNodes(String xpathExpression, String comparisonXPathExpression, boolean removeDuplicates) { XPath xpath = createXPath(xpathExpression); XPath sortBy = createXPath(comparisonXPathExpression); return xpath.selectNodes(this, sortBy, removeDuplicates); } public Node selectSingleNode(String xpathExpression) { XPath xpath = createXPath(xpathExpression); return xpath.selectSingleNode(this); } public String valueOf(String xpathExpression) { XPath xpath = createXPath(xpathExpression); return xpath.valueOf(this); } public Number numberValueOf(String xpathExpression) { XPath xpath = createXPath(xpathExpression); return xpath.numberValueOf(this); } public boolean matches(String patternText) { NodeFilter filter = createXPathFilter(patternText); return filter.matches(this); } public XPath createXPath(String xpathExpression) { return getDocumentFactory().createXPath(xpathExpression); } public NodeFilter createXPathFilter(String patternText) { return getDocumentFactory().createXPathFilter(patternText); } public Pattern createPattern(String patternText) { return getDocumentFactory().createPattern(patternText); } public Node asXPathResult(Element parent) { if (supportsParent()) { return this; } return createXPathResult(parent); } protected DocumentFactory getDocumentFactory() { return DOCUMENT_FACTORY; } protected Node createXPathResult(Element parent) { throw new RuntimeException("asXPathResult() not yet implemented fully " + "for: " + this); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/NamespaceCache.java0000644000175000017500000001620610242120023022011 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.lang.ref.WeakReference; import java.lang.reflect.Constructor; import java.util.Map; import org.dom4j.Namespace; /** *

* NamespaceCache caches instances of * DefaultNamespace for reuse both across documents and within * documents. *

* * @author James Strachan * @author Maarten Coene * @author Brett Finnell * @version $Revision: 1.15 $ */ public class NamespaceCache { private static final String CONCURRENTREADERHASHMAP_CLASS = "EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap"; /** * Cache of {@link Map}instances indexed by URI which contain caches of * {@link Namespace}for each prefix */ protected static Map cache; /** * Cache of {@link Namespace}instances indexed by URI for default * namespaces with no prefixes */ protected static Map noPrefixCache; static { /* Try the java.util.concurrent.ConcurrentHashMap first. */ try { Class clazz = Class .forName("java.util.concurrent.ConcurrentHashMap"); Constructor construct = clazz.getConstructor(new Class[] { Integer.TYPE, Float.TYPE, Integer.TYPE }); cache = (Map) construct.newInstance(new Object[] {new Integer(11), new Float(0.75f), new Integer(1) }); noPrefixCache = (Map) construct.newInstance(new Object[] { new Integer(11), new Float(0.75f), new Integer(1) }); } catch (Throwable t1) { /* Try to use the util.concurrent library (if in classpath) */ try { Class clazz = Class.forName(CONCURRENTREADERHASHMAP_CLASS); cache = (Map) clazz.newInstance(); noPrefixCache = (Map) clazz.newInstance(); } catch (Throwable t2) { /* If previous implementations fail, use internal one */ cache = new ConcurrentReaderHashMap(); noPrefixCache = new ConcurrentReaderHashMap(); } } } /** * DOCUMENT ME! * * @param prefix * DOCUMENT ME! * @param uri * DOCUMENT ME! * * @return the namespace for the given prefix and uri */ public Namespace get(String prefix, String uri) { Map uriCache = getURICache(uri); WeakReference ref = (WeakReference) uriCache.get(prefix); Namespace answer = null; if (ref != null) { answer = (Namespace) ref.get(); } if (answer == null) { synchronized (uriCache) { ref = (WeakReference) uriCache.get(prefix); if (ref != null) { answer = (Namespace) ref.get(); } if (answer == null) { answer = createNamespace(prefix, uri); uriCache.put(prefix, new WeakReference(answer)); } } } return answer; } /** * DOCUMENT ME! * * @param uri * DOCUMENT ME! * * @return the name model for the given name and namepsace */ public Namespace get(String uri) { WeakReference ref = (WeakReference) noPrefixCache.get(uri); Namespace answer = null; if (ref != null) { answer = (Namespace) ref.get(); } if (answer == null) { synchronized (noPrefixCache) { ref = (WeakReference) noPrefixCache.get(uri); if (ref != null) { answer = (Namespace) ref.get(); } if (answer == null) { answer = createNamespace("", uri); noPrefixCache.put(uri, new WeakReference(answer)); } } } return answer; } /** * DOCUMENT ME! * * @param uri * DOCUMENT ME! * * @return the cache for the given namespace URI. If one does not currently * exist it is created. */ protected Map getURICache(String uri) { Map answer = (Map) cache.get(uri); if (answer == null) { synchronized (cache) { answer = (Map) cache.get(uri); if (answer == null) { answer = new ConcurrentReaderHashMap(); cache.put(uri, answer); } } } return answer; } /** * A factory method to create {@link Namespace}instance * * @param prefix * DOCUMENT ME! * @param uri * DOCUMENT ME! * * @return a newly created {@link Namespace}instance. */ protected Namespace createNamespace(String prefix, String uri) { return new Namespace(prefix, uri); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/DefaultNamespace.java0000644000175000017500000001106310242120007022370 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import org.dom4j.Element; import org.dom4j.Namespace; /** *

* DefaultNamespace implements a doubly linked node which * supports the parent relationship and is mutable. It is useful when returning * results from XPath expressions. *

* * @author James Strachan * @version $Revision: 1.16 $ */ public class DefaultNamespace extends Namespace { /** The parent of this node */ private Element parent; /** * DOCUMENT ME! * * @param prefix * is the prefix for this namespace * @param uri * is the URI for this namespace */ public DefaultNamespace(String prefix, String uri) { super(prefix, uri); } /** * DOCUMENT ME! * * @param parent * is the parent element * @param prefix * is the prefix for this namespace * @param uri * is the URI for this namespace */ public DefaultNamespace(Element parent, String prefix, String uri) { super(prefix, uri); this.parent = parent; } /** * DOCUMENT ME! * * @return the hash code based on the qualified name and the URI of the * namespace and the hashCode() of the parent element. */ protected int createHashCode() { int hashCode = super.createHashCode(); if (parent != null) { hashCode ^= parent.hashCode(); } return hashCode; } /** * Implements an identity based comparsion using the parent element as well * as the prefix and URI * * @param object * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean equals(Object object) { if (object instanceof DefaultNamespace) { DefaultNamespace that = (DefaultNamespace) object; if (that.parent == parent) { return super.equals(object); } } return false; } public int hashCode() { return super.hashCode(); } public Element getParent() { return parent; } public void setParent(Element parent) { this.parent = parent; } public boolean supportsParent() { return true; } public boolean isReadOnly() { return false; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/AbstractEntity.java0000644000175000017500000000745010242120005022132 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.io.IOException; import java.io.Writer; import org.dom4j.Element; import org.dom4j.Entity; import org.dom4j.Visitor; /** *

* AbstractEntity is an abstract base class for tree implementors * to use for implementation inheritence. *

* * @author James Strachan * @version $Revision: 1.15 $ */ public abstract class AbstractEntity extends AbstractNode implements Entity { public AbstractEntity() { } public short getNodeType() { return ENTITY_REFERENCE_NODE; } public String getPath(Element context) { // From XPaths perspective, entities are included in text Element parent = getParent(); return ((parent != null) && (parent != context)) ? (parent .getPath(context) + "/text()") : "text()"; } public String getUniquePath(Element context) { // From XPaths perspective, entities are included in text Element parent = getParent(); return ((parent != null) && (parent != context)) ? (parent .getUniquePath(context) + "/text()") : "text()"; } public String toString() { return super.toString() + " [Entity: &" + getName() + ";]"; } public String getStringValue() { return "&" + getName() + ";"; } public String asXML() { return "&" + getName() + ";"; } public void write(Writer writer) throws IOException { writer.write("&"); writer.write(getName()); writer.write(";"); } public void accept(Visitor visitor) { visitor.visit(this); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/DefaultComment.java0000644000175000017500000000661210242120016022102 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import org.dom4j.Element; /** *

* DefaultComment is the default Comment implementation. It is a * doubly linked node which supports the parent relationship and can be modified * in place. *

* * @author James Strachan * @version $Revision: 1.11 $ */ public class DefaultComment extends FlyweightComment { /** The parent of this node */ private Element parent; /** * DOCUMENT ME! * * @param text * is the Comment text */ public DefaultComment(String text) { super(text); } /** * DOCUMENT ME! * * @param parent * is the parent element * @param text * is the Comment text */ public DefaultComment(Element parent, String text) { super(text); this.parent = parent; } public void setText(String text) { this.text = text; } public Element getParent() { return parent; } public void setParent(Element parent) { this.parent = parent; } public boolean supportsParent() { return true; } public boolean isReadOnly() { return false; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/FlyweightText.java0000644000175000017500000000607710242120021022003 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.Text; /** *

* FlyweightText is a Flyweight pattern implementation of a * singly linked, read-only XML Text. *

* *

* This node could be shared across documents and elements though it does not * support the parent relationship. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public class FlyweightText extends AbstractText implements Text { /** Text of the Text node */ protected String text; /** * DOCUMENT ME! * * @param text * is the Text text */ public FlyweightText(String text) { this.text = text; } public String getText() { return text; } protected Node createXPathResult(Element parent) { return new DefaultText(parent, getText()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/AbstractAttribute.java0000644000175000017500000001365410242120021022622 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.io.IOException; import java.io.Writer; import org.dom4j.Attribute; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.Node; import org.dom4j.Visitor; /** *

* AbstractNamespace is an abstract base class for tree * implementors to use for implementation inheritence. *

* * @author James Strachan * @version $Revision: 1.21 $ */ public abstract class AbstractAttribute extends AbstractNode implements Attribute { public short getNodeType() { return ATTRIBUTE_NODE; } public void setNamespace(Namespace namespace) { String msg = "This Attribute is read only and cannot be changed"; throw new UnsupportedOperationException(msg); } public String getText() { return getValue(); } public void setText(String text) { setValue(text); } public void setValue(String value) { String msg = "This Attribute is read only and cannot be changed"; throw new UnsupportedOperationException(msg); } public Object getData() { return getValue(); } public void setData(Object data) { setValue((data == null) ? null : data.toString()); } public String toString() { return super.toString() + " [Attribute: name " + getQualifiedName() + " value \"" + getValue() + "\"]"; } public String asXML() { return getQualifiedName() + "=\"" + getValue() + "\""; } public void write(Writer writer) throws IOException { writer.write(getQualifiedName()); writer.write("=\""); writer.write(getValue()); writer.write("\""); } public void accept(Visitor visitor) { visitor.visit(this); } // QName methods public Namespace getNamespace() { return getQName().getNamespace(); } public String getName() { return getQName().getName(); } public String getNamespacePrefix() { return getQName().getNamespacePrefix(); } public String getNamespaceURI() { return getQName().getNamespaceURI(); } public String getQualifiedName() { return getQName().getQualifiedName(); } public String getPath(Element context) { StringBuffer result = new StringBuffer(); Element parent = getParent(); if ((parent != null) && (parent != context)) { result.append(parent.getPath(context)); result.append("/"); } result.append("@"); String uri = getNamespaceURI(); String prefix = getNamespacePrefix(); if ((uri == null) || (uri.length() == 0) || (prefix == null) || (prefix.length() == 0)) { result.append(getName()); } else { result.append(getQualifiedName()); } return result.toString(); } public String getUniquePath(Element context) { StringBuffer result = new StringBuffer(); Element parent = getParent(); if ((parent != null) && (parent != context)) { result.append(parent.getUniquePath(context)); result.append("/"); } result.append("@"); String uri = getNamespaceURI(); String prefix = getNamespacePrefix(); if ((uri == null) || (uri.length() == 0) || (prefix == null) || (prefix.length() == 0)) { result.append(getName()); } else { result.append(getQualifiedName()); } return result.toString(); } protected Node createXPathResult(Element parent) { return new DefaultAttribute(parent, getQName(), getValue()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/DefaultProcessingInstruction.java0000644000175000017500000001107510242120013025052 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.util.Map; import org.dom4j.Element; /** *

* DefaultProcessingInstruction is the default Processing * Instruction implementation. It is a doubly linked node which supports the * parent relationship and can be modified in place. *

* * @author James Strachan * @version $Revision: 1.13 $ */ public class DefaultProcessingInstruction extends org.dom4j.tree.FlyweightProcessingInstruction { /** The parent of this node */ private Element parent; /** *

* This will create a new PI with the given target and values *

* * @param target * is the name of the PI * @param values * is the Map values for the PI */ public DefaultProcessingInstruction(String target, Map values) { super(target, values); } /** *

* This will create a new PI with the given target and values *

* * @param target * is the name of the PI * @param values * is the values for the PI */ public DefaultProcessingInstruction(String target, String values) { super(target, values); } /** *

* This will create a new PI with the given target and values *

* * @param parent * is the parent element * @param target * is the name of the PI * @param values * is the values for the PI */ public DefaultProcessingInstruction(Element parent, String target, String values) { super(target, values); this.parent = parent; } public void setTarget(String target) { this.target = target; } public void setText(String text) { this.text = text; this.values = parseValues(text); } public void setValues(Map values) { this.values = values; this.text = toString(values); } public void setValue(String name, String value) { values.put(name, value); } public Element getParent() { return parent; } public void setParent(Element parent) { this.parent = parent; } public boolean supportsParent() { return true; } public boolean isReadOnly() { return false; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/FlyweightEntity.java0000644000175000017500000001127110242117777022353 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import org.dom4j.Element; import org.dom4j.Node; /** *

* FlyweightEntity is a Flyweight pattern implementation of a * singly linked, read-only XML entity. *

* *

* This node could be shared across documents and elements though it does not * support the parent relationship. *

* *

* Often this node needs to be created and then the text content added later * (for example in SAX) so this implementation allows a call to {@link#setText} * providing the entity has no text already. *

* * @author James Strachan * @version $Revision: 1.6 $ */ public class FlyweightEntity extends AbstractEntity { /** The name of the Entity */ protected String name; /** The text of the Entity */ protected String text; /** * A default constructor for implementors to use. */ protected FlyweightEntity() { } /** * Creates the Entity with the specified name * * @param name * is the name of the entity */ public FlyweightEntity(String name) { this.name = name; } /** * Creates the Entity with the specified name and text. * * @param name * is the name of the entity * @param text * is the text of the entity */ public FlyweightEntity(String name, String text) { this.name = name; this.text = text; } /** * DOCUMENT ME! * * @return the name of the entity */ public String getName() { return name; } /** * DOCUMENT ME! * * @return the text of the entity */ public String getText() { return text; } /** * sets the value of the entity if it is not defined yet otherwise an * UnsupportedOperationException is thrown as this class is * read only. * * @param text * DOCUMENT ME! * * @throws UnsupportedOperationException * DOCUMENT ME! */ public void setText(String text) { if (this.text != null) { this.text = text; } else { throw new UnsupportedOperationException( "This Entity is read-only. " + "It cannot be modified"); } } protected Node createXPathResult(Element parent) { return new DefaultEntity(parent, getName(), getText()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/DefaultEntity.java0000644000175000017500000000772210242120012021753 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import org.dom4j.Element; /** *

* DefaultEntity is the default Entity implementation. It is a * doubly linked node which supports the parent relationship and can be modified * in place. *

* * @author James Strachan * @version $Revision: 1.11 $ */ public class DefaultEntity extends FlyweightEntity { /** The parent of this node */ private Element parent; /** * Creates the Entity with the specified name * * @param name * is the name of the entity */ public DefaultEntity(String name) { super(name); } /** * Creates the Entity with the specified name and text. * * @param name * is the name of the entity * @param text * is the text of the entity */ public DefaultEntity(String name, String text) { super(name, text); } /** * Creates the Entity with the specified name and text. * * @param parent * is the parent element * @param name * is the name of the entity * @param text * is the text of the entity */ public DefaultEntity(Element parent, String name, String text) { super(name, text); this.parent = parent; } public void setName(String name) { this.name = name; } public void setText(String text) { this.text = text; } public Element getParent() { return parent; } public void setParent(Element parent) { this.parent = parent; } public boolean supportsParent() { return true; } public boolean isReadOnly() { return false; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/DefaultDocumentType.java0000644000175000017500000001255010242117777023142 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.util.List; /** *

* DefaultDocumentType is the DOM4J default implementation of an * XML document type. *

* * @author James Strachan * @version $Revision: 1.10 $ */ public class DefaultDocumentType extends AbstractDocumentType { /** The root element name of the document typ */ protected String elementName; /** Holds value of property publicID. */ private String publicID; /** Holds value of property systemID. */ private String systemID; /** The internal DTD declarations */ private List internalDeclarations; /** The external DTD declarations */ private List externalDeclarations; public DefaultDocumentType() { } /** *

* This will create a new DocumentType with a reference to * the external DTD *

* * @param elementName * is the root element name of the document type * @param systemID * is the system ID of the external DTD */ public DefaultDocumentType(String elementName, String systemID) { this.elementName = elementName; this.systemID = systemID; } /** *

* This will create a new DocumentType with a reference to * the external DTD *

* * @param elementName * is the root element name of the document type * @param publicID * is the public ID of the DTD * @param systemID * is the system ID of the DTD */ public DefaultDocumentType(String elementName, String publicID, String systemID) { this.elementName = elementName; this.publicID = publicID; this.systemID = systemID; } public String getElementName() { return elementName; } public void setElementName(String elementName) { this.elementName = elementName; } /** * DOCUMENT ME! * * @return the public ID of the document type */ public String getPublicID() { return publicID; } /** * Sets the public ID of the document type * * @param publicID * DOCUMENT ME! */ public void setPublicID(String publicID) { this.publicID = publicID; } /** * DOCUMENT ME! * * @return the system ID of the document type */ public String getSystemID() { return systemID; } /** * Sets the system ID of the document type * * @param systemID * DOCUMENT ME! */ public void setSystemID(String systemID) { this.systemID = systemID; } public List getInternalDeclarations() { return internalDeclarations; } public void setInternalDeclarations(List internalDeclarations) { this.internalDeclarations = internalDeclarations; } public List getExternalDeclarations() { return externalDeclarations; } public void setExternalDeclarations(List externalDeclarations) { this.externalDeclarations = externalDeclarations; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/AbstractDocumentType.java0000644000175000017500000001420310242120012023266 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.List; import org.dom4j.DocumentType; import org.dom4j.Element; import org.dom4j.Visitor; /** *

* AbstractDocumentType is an abstract base class for tree * implementors to use for implementation inheritence. *

* * @author James Strachan * @version $Revision: 1.17 $ */ public abstract class AbstractDocumentType extends AbstractNode implements DocumentType { public AbstractDocumentType() { } public short getNodeType() { return DOCUMENT_TYPE_NODE; } public String getName() { return getElementName(); } public void setName(String name) { setElementName(name); } public String getPath(Element context) { // not available in XPath return ""; } public String getUniquePath(Element context) { // not available in XPath return ""; } /** * Returns the text format of the declarations if applicable, or the empty * String * * @return DOCUMENT ME! */ public String getText() { List list = getInternalDeclarations(); if ((list != null) && (list.size() > 0)) { StringBuffer buffer = new StringBuffer(); Iterator iter = list.iterator(); if (iter.hasNext()) { Object decl = iter.next(); buffer.append(decl.toString()); while (iter.hasNext()) { decl = iter.next(); buffer.append("\n"); buffer.append(decl.toString()); } } return buffer.toString(); } return ""; } public String toString() { return super.toString() + " [DocumentType: " + asXML() + "]"; } public String asXML() { StringBuffer buffer = new StringBuffer(" 0)) { buffer.append(" PUBLIC \""); buffer.append(publicID); buffer.append("\""); hasPublicID = true; } String systemID = getSystemID(); if ((systemID != null) && (systemID.length() > 0)) { if (!hasPublicID) { buffer.append(" SYSTEM"); } buffer.append(" \""); buffer.append(systemID); buffer.append("\""); } buffer.append(">"); return buffer.toString(); } public void write(Writer writer) throws IOException { writer.write(" 0)) { writer.write(" PUBLIC \""); writer.write(publicID); writer.write("\""); hasPublicID = true; } String systemID = getSystemID(); if ((systemID != null) && (systemID.length() > 0)) { if (!hasPublicID) { writer.write(" SYSTEM"); } writer.write(" \""); writer.write(systemID); writer.write("\""); } List list = getInternalDeclarations(); if ((list != null) && (list.size() > 0)) { writer.write(" ["); for (Iterator iter = list.iterator(); iter.hasNext();) { Object decl = iter.next(); writer.write("\n "); writer.write(decl.toString()); } writer.write("\n]"); } writer.write(">"); } public void accept(Visitor visitor) { visitor.visit(this); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/FlyweightProcessingInstruction.java0000644000175000017500000001124410242120021025425 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.util.Collections; import java.util.Map; import org.dom4j.Element; import org.dom4j.Node; /** *

* FlyweightProcessingInstruction is a Flyweight pattern * implementation of a singly linked, read-only XML Processing Instruction. *

* *

* This node could be shared across documents and elements though it does not * support the parent relationship. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public class FlyweightProcessingInstruction extends AbstractProcessingInstruction { /** The target of the PI */ protected String target; /** The values for the PI as a String */ protected String text; /** The values for the PI in name/value pairs */ protected Map values; /** * A default constructor for implementors to use. */ public FlyweightProcessingInstruction() { } /** *

* This will create a new PI with the given target and values *

* * @param target * is the name of the PI * @param values * is the Map of the values for the PI */ public FlyweightProcessingInstruction(String target, Map values) { this.target = target; this.values = values; this.text = toString(values); } /** *

* This will create a new PI with the given target and values *

* * @param target * is the name of the PI * @param text * is the values for the PI as text */ public FlyweightProcessingInstruction(String target, String text) { this.target = target; this.text = text; this.values = parseValues(text); } public String getTarget() { return target; } public void setTarget(String target) { throw new UnsupportedOperationException("This PI is read-only and " + "cannot be modified"); } public String getText() { return text; } public String getValue(String name) { String answer = (String) values.get(name); if (answer == null) { return ""; } return answer; } public Map getValues() { return Collections.unmodifiableMap(values); } protected Node createXPathResult(Element parent) { return new DefaultProcessingInstruction(parent, getTarget(), getText()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/DefaultText.java0000644000175000017500000000656210242120025021430 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import org.dom4j.Element; /** *

* DefaultText is the default Text implementation. It is a doubly * linked node which supports the parent relationship and can be modified in * place. *

* * @author James Strachan * @version $Revision: 1.11 $ */ public class DefaultText extends FlyweightText { /** The parent of this node */ private Element parent; /** * DOCUMENT ME! * * @param text * is the Text text */ public DefaultText(String text) { super(text); } /** * DOCUMENT ME! * * @param parent * is the parent element * @param text * is the Text text */ public DefaultText(Element parent, String text) { super(text); this.parent = parent; } public void setText(String text) { this.text = text; } public Element getParent() { return parent; } public void setParent(Element parent) { this.parent = parent; } public boolean supportsParent() { return true; } public boolean isReadOnly() { return false; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/DefaultCDATA.java0000644000175000017500000000657210242120006021320 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import org.dom4j.Element; /** *

* DefaultCDATA is the default CDATA implementation. It is a * doubly linked node which supports the parent relationship and can be modified * in place. *

* * @author James Strachan * @version $Revision: 1.12 $ */ public class DefaultCDATA extends FlyweightCDATA { /** The parent of this node */ private Element parent; /** * DOCUMENT ME! * * @param text * is the CDATA text */ public DefaultCDATA(String text) { super(text); } /** * DOCUMENT ME! * * @param parent * is the parent element * @param text * is the CDATA text */ public DefaultCDATA(Element parent, String text) { super(text); this.parent = parent; } public void setText(String text) { this.text = text; } public Element getParent() { return parent; } public void setParent(Element parent) { this.parent = parent; } public boolean supportsParent() { return true; } public boolean isReadOnly() { return false; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/ElementIterator.java0000644000175000017500000000572310242120022022275 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.util.Iterator; import org.dom4j.Element; /** *

* ElementIterator is a filtering {@link Iterator}which filters * out objects which do not implement the {@link Element}interface. *

* * @author James Strachan * @version $Revision: 1.8 $ * * @deprecated THIS CLASS WILL BE REMOVED IN dom4j-1.6 !! */ public class ElementIterator extends FilterIterator { public ElementIterator(Iterator proxy) { super(proxy); } /** * DOCUMENT ME! * * @param element * DOCUMENT ME! * * @return true if the given element implements the {@link Element} * interface */ protected boolean matches(Object element) { return element instanceof Element; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/AbstractCharacterData.java0000644000175000017500000000617110242120007023345 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import org.dom4j.CharacterData; import org.dom4j.Element; /** *

* AbstractCharacterData is an abstract base class for tree * implementors to use for implementation inheritence. *

* * @author James Strachan * @version $Revision: 1.12 $ */ public abstract class AbstractCharacterData extends AbstractNode implements CharacterData { public AbstractCharacterData() { } public String getPath(Element context) { Element parent = getParent(); return ((parent != null) && (parent != context)) ? (parent .getPath(context) + "/text()") : "text()"; } public String getUniquePath(Element context) { Element parent = getParent(); return ((parent != null) && (parent != context)) ? (parent .getUniquePath(context) + "/text()") : "text()"; } public void appendText(String text) { setText(getText() + text); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/AbstractProcessingInstruction.java0000644000175000017500000001620710242120017025237 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; import org.dom4j.Element; import org.dom4j.ProcessingInstruction; import org.dom4j.Visitor; /** *

* AbstractProcessingInstruction is an abstract base class for * tree implementors to use for implementation inheritence. *

* * @author James Strachan * @version $Revision: 1.17 $ */ public abstract class AbstractProcessingInstruction extends AbstractNode implements ProcessingInstruction { public AbstractProcessingInstruction() { } public short getNodeType() { return PROCESSING_INSTRUCTION_NODE; } public String getPath(Element context) { Element parent = getParent(); return ((parent != null) && (parent != context)) ? (parent .getPath(context) + "/processing-instruction()") : "processing-instruction()"; } public String getUniquePath(Element context) { Element parent = getParent(); return ((parent != null) && (parent != context)) ? (parent .getUniquePath(context) + "/processing-instruction()") : "processing-instruction()"; } public String toString() { return super.toString() + " [ProcessingInstruction: &" + getName() + ";]"; } public String asXML() { return ""; } public void write(Writer writer) throws IOException { writer.write(""); } public void accept(Visitor visitor) { visitor.visit(this); } public void setValue(String name, String value) { throw new UnsupportedOperationException("This PI is read-only and " + "cannot be modified"); } public void setValues(Map data) { throw new UnsupportedOperationException("This PI is read-only and " + "cannot be modified"); } public String getName() { return getTarget(); } public void setName(String name) { setTarget(name); } public boolean removeValue(String name) { return false; } // Helper methods /** *

* This will convert the Map to a string representation. *

* * @param values * is a Map of PI data to convert * * @return DOCUMENT ME! */ protected String toString(Map values) { StringBuffer buffer = new StringBuffer(); for (Iterator iter = values.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); String value = (String) entry.getValue(); buffer.append(name); buffer.append("=\""); buffer.append(value); buffer.append("\" "); } // remove the last space buffer.setLength(buffer.length() - 1); return buffer.toString(); } /** *

* Parses the raw data of PI as a Map. *

* * @param text * String PI data to parse * * @return DOCUMENT ME! */ protected Map parseValues(String text) { Map data = new HashMap(); StringTokenizer s = new StringTokenizer(text, " =\'\"", true); while (s.hasMoreTokens()) { String name = getName(s); if (s.hasMoreTokens()) { String value = getValue(s); data.put(name, value); } } return data; } private String getName(StringTokenizer tokenizer) { String token = tokenizer.nextToken(); StringBuffer name = new StringBuffer(token); while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); if (!token.equals("=")) { name.append(token); } else { break; } } return name.toString().trim(); } private String getValue(StringTokenizer tokenizer) { String token = tokenizer.nextToken(); StringBuffer value = new StringBuffer(); /* get the quote */ while (tokenizer.hasMoreTokens() && !token.equals("\'") && !token.equals("\"")) { token = tokenizer.nextToken(); } String quote = token; while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); if (!quote.equals(token)) { value.append(token); } else { break; } } return value.toString(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/AbstractBranch.java0000644000175000017500000003351710242120022022055 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import org.dom4j.Branch; import org.dom4j.Comment; import org.dom4j.Element; import org.dom4j.IllegalAddException; import org.dom4j.Namespace; import org.dom4j.Node; import org.dom4j.ProcessingInstruction; import org.dom4j.QName; /** *

* AbstractBranch is an abstract base class for tree implementors * to use for implementation inheritence. *

* * @author James Strachan * @version $Revision: 1.44 $ */ public abstract class AbstractBranch extends AbstractNode implements Branch { protected static final int DEFAULT_CONTENT_LIST_SIZE = 5; public AbstractBranch() { } public boolean isReadOnly() { return false; } public boolean hasContent() { return nodeCount() > 0; } public List content() { List backingList = contentList(); return new ContentListFacade(this, backingList); } public String getText() { List content = contentList(); if (content != null) { int size = content.size(); if (size >= 1) { Object first = content.get(0); String firstText = getContentAsText(first); if (size == 1) { // optimised to avoid StringBuffer creation return firstText; } else { StringBuffer buffer = new StringBuffer(firstText); for (int i = 1; i < size; i++) { Object node = content.get(i); buffer.append(getContentAsText(node)); } return buffer.toString(); } } } return ""; } /** * DOCUMENT ME! * * @param content * DOCUMENT ME! * * @return the text value of the given content object as text which returns * the text value of CDATA, Entity or Text nodes */ protected String getContentAsText(Object content) { if (content instanceof Node) { Node node = (Node) content; switch (node.getNodeType()) { case CDATA_SECTION_NODE: // case ENTITY_NODE: case ENTITY_REFERENCE_NODE: case TEXT_NODE: return node.getText(); default: break; } } else if (content instanceof String) { return (String) content; } return ""; } /** * DOCUMENT ME! * * @param content * DOCUMENT ME! * * @return the XPath defined string-value of the given content object */ protected String getContentAsStringValue(Object content) { if (content instanceof Node) { Node node = (Node) content; switch (node.getNodeType()) { case CDATA_SECTION_NODE: // case ENTITY_NODE: case ENTITY_REFERENCE_NODE: case TEXT_NODE: case ELEMENT_NODE: return node.getStringValue(); default: break; } } else if (content instanceof String) { return (String) content; } return ""; } public String getTextTrim() { String text = getText(); StringBuffer textContent = new StringBuffer(); StringTokenizer tokenizer = new StringTokenizer(text); while (tokenizer.hasMoreTokens()) { String str = tokenizer.nextToken(); textContent.append(str); if (tokenizer.hasMoreTokens()) { textContent.append(" "); // separator } } return textContent.toString(); } public void setProcessingInstructions(List listOfPIs) { for (Iterator iter = listOfPIs.iterator(); iter.hasNext();) { ProcessingInstruction pi = (ProcessingInstruction) iter.next(); addNode(pi); } } public Element addElement(String name) { Element node = getDocumentFactory().createElement(name); add(node); return node; } public Element addElement(String qualifiedName, String namespaceURI) { Element node = getDocumentFactory().createElement(qualifiedName, namespaceURI); add(node); return node; } public Element addElement(QName qname) { Element node = getDocumentFactory().createElement(qname); add(node); return node; } public Element addElement(String name, String prefix, String uri) { Namespace namespace = Namespace.get(prefix, uri); QName qName = getDocumentFactory().createQName(name, namespace); return addElement(qName); } // polymorphic node methods public void add(Node node) { switch (node.getNodeType()) { case ELEMENT_NODE: add((Element) node); break; case COMMENT_NODE: add((Comment) node); break; case PROCESSING_INSTRUCTION_NODE: add((ProcessingInstruction) node); break; default: invalidNodeTypeAddException(node); } } public boolean remove(Node node) { switch (node.getNodeType()) { case ELEMENT_NODE: return remove((Element) node); case COMMENT_NODE: return remove((Comment) node); case PROCESSING_INSTRUCTION_NODE: return remove((ProcessingInstruction) node); default: invalidNodeTypeAddException(node); return false; } } // typesafe versions using node classes public void add(Comment comment) { addNode(comment); } public void add(Element element) { addNode(element); } public void add(ProcessingInstruction pi) { addNode(pi); } public boolean remove(Comment comment) { return removeNode(comment); } public boolean remove(Element element) { return removeNode(element); } public boolean remove(ProcessingInstruction pi) { return removeNode(pi); } public Element elementByID(String elementID) { for (int i = 0, size = nodeCount(); i < size; i++) { Node node = node(i); if (node instanceof Element) { Element element = (Element) node; String id = elementID(element); if ((id != null) && id.equals(elementID)) { return element; } else { element = element.elementByID(elementID); if (element != null) { return element; } } } } return null; } public void appendContent(Branch branch) { for (int i = 0, size = branch.nodeCount(); i < size; i++) { Node node = branch.node(i); add((Node) node.clone()); } } public Node node(int index) { Object object = contentList().get(index); if (object instanceof Node) { return (Node) object; } if (object instanceof String) { return getDocumentFactory().createText(object.toString()); } return null; } public int nodeCount() { return contentList().size(); } public int indexOf(Node node) { return contentList().indexOf(node); } public Iterator nodeIterator() { return contentList().iterator(); } // Implementation methods /** * DOCUMENT ME! * * @param element * DOCUMENT ME! * * @return the ID of the given Element */ protected String elementID(Element element) { // XXX: there will be other ways of finding the ID // XXX: should probably have an IDResolver or something return element.attributeValue("ID"); } /** * DOCUMENT ME! * * @return the internal List used to manage the content */ protected abstract List contentList(); /** * A Factory Method pattern which creates a List implementation used to * store content * * @return DOCUMENT ME! */ protected List createContentList() { return new ArrayList(DEFAULT_CONTENT_LIST_SIZE); } /** * A Factory Method pattern which creates a List implementation used to * store content * * @param size * DOCUMENT ME! * * @return DOCUMENT ME! */ protected List createContentList(int size) { return new ArrayList(size); } /** * A Factory Method pattern which creates a BackedList implementation used * to store results of a filtered content query. * * @return DOCUMENT ME! */ protected BackedList createResultList() { return new BackedList(this, contentList()); } /** * A Factory Method pattern which creates a BackedList implementation which * contains a single result * * @param result * DOCUMENT ME! * * @return DOCUMENT ME! */ protected List createSingleResultList(Object result) { BackedList list = new BackedList(this, contentList(), 1); list.addLocal(result); return list; } /** * A Factory Method pattern which creates an empty a BackedList * implementation * * @return DOCUMENT ME! */ protected List createEmptyList() { return new BackedList(this, contentList(), 0); } protected abstract void addNode(Node node); protected abstract void addNode(int index, Node node); protected abstract boolean removeNode(Node node); /** * Called when a new child node has been added to me to allow any parent * relationships to be created or events to be fired. * * @param node * DOCUMENT ME! */ protected abstract void childAdded(Node node); /** * Called when a child node has been removed to allow any parent * relationships to be deleted or events to be fired. * * @param node * DOCUMENT ME! */ protected abstract void childRemoved(Node node); /** * Called when the given List content has been removed so each node should * have its parent and document relationships cleared */ protected void contentRemoved() { List content = contentList(); for (int i = 0, size = content.size(); i < size; i++) { Object object = content.get(i); if (object instanceof Node) { childRemoved((Node) object); } } } /** * Called when an invalid node has been added. Throws an {@link * IllegalAddException}. * * @param node * DOCUMENT ME! * * @throws IllegalAddException * DOCUMENT ME! */ protected void invalidNodeTypeAddException(Node node) { throw new IllegalAddException("Invalid node type. Cannot add node: " + node + " to this branch: " + this); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/AbstractText.java0000644000175000017500000000601710242120010021574 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.io.IOException; import java.io.Writer; import org.dom4j.Visitor; /** *

* AbstractText is an abstract base class for tree implementors * to use for implementation inheritence. *

* * @author James Strachan * @version $Revision: 1.10 $ */ public abstract class AbstractText extends AbstractCharacterData implements org.dom4j.Text { public AbstractText() { } public short getNodeType() { return TEXT_NODE; } public String toString() { return super.toString() + " [Text: \"" + getText() + "\"]"; } public String asXML() { return getText(); } public void write(Writer writer) throws IOException { writer.write(getText()); } public void accept(Visitor visitor) { visitor.visit(this); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/FlyweightAttribute.java0000644000175000017500000001006610242120022023014 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import org.dom4j.Namespace; import org.dom4j.QName; /** *

* FlyweightAttribute is a Flyweight pattern implementation of a * singly linked, read-only XML Attribute. *

* *

* This node could be shared across documents and elements though it does not * support the parent relationship. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public class FlyweightAttribute extends AbstractAttribute { /** The QName for this element */ private QName qname; /** The value of the Attribute */ protected String value; public FlyweightAttribute(QName qname) { this.qname = qname; } public FlyweightAttribute(QName qname, String value) { this.qname = qname; this.value = value; } /** * Creates the Attribute with the specified local name and * value. * * @param name * is the name of the attribute * @param value * is the value of the attribute */ public FlyweightAttribute(String name, String value) { this.qname = getDocumentFactory().createQName(name); this.value = value; } /** * Creates the Attribute with the specified local name, value * and Namespace. * * @param name * is the name of the attribute * @param value * is the value of the attribute * @param namespace * is the namespace of the attribute */ public FlyweightAttribute(String name, String value, Namespace namespace) { this.qname = getDocumentFactory().createQName(name, namespace); this.value = value; } public String getValue() { return value; } public QName getQName() { return qname; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/BaseElement.java0000644000175000017500000001334610242120014021357 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.util.List; import org.dom4j.Branch; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.QName; /** *

* BaseElement is a useful base class for implemementation * inheritence of an XML element. *

* * @author James Strachan * @version $Revision: 1.9 $ */ public class BaseElement extends AbstractElement { /** The QName for this element */ private QName qname; /** * Stores the parent branch of this node which is either a Document if this * element is the root element in a document, or another Element if it is a * child of the root document, or null if it has not been added to a * document yet. */ private Branch parentBranch; /** List of content nodes. */ protected List content; /** list of attributes */ protected List attributes; public BaseElement(String name) { this.qname = getDocumentFactory().createQName(name); } public BaseElement(QName qname) { this.qname = qname; } public BaseElement(String name, Namespace namespace) { this.qname = getDocumentFactory().createQName(name, namespace); } public Element getParent() { Element result = null; if (parentBranch instanceof Element) { result = (Element) parentBranch; } return result; } public void setParent(Element parent) { if (parentBranch instanceof Element || (parent != null)) { parentBranch = parent; } } public Document getDocument() { if (parentBranch instanceof Document) { return (Document) parentBranch; } else if (parentBranch instanceof Element) { Element parent = (Element) parentBranch; return parent.getDocument(); } return null; } public void setDocument(Document document) { if (parentBranch instanceof Document || (document != null)) { parentBranch = document; } } public boolean supportsParent() { return true; } public QName getQName() { return qname; } public void setQName(QName name) { this.qname = name; } public void clearContent() { contentList().clear(); } public void setContent(List content) { this.content = content; if (content instanceof ContentListFacade) { this.content = ((ContentListFacade) content).getBackingList(); } } public void setAttributes(List attributes) { this.attributes = attributes; if (attributes instanceof ContentListFacade) { this.attributes = ((ContentListFacade) attributes).getBackingList(); } } // Implementation methods // ------------------------------------------------------------------------- protected List contentList() { if (content == null) { content = createContentList(); } return content; } protected List attributeList() { if (attributes == null) { attributes = createAttributeList(); } return attributes; } protected List attributeList(int size) { if (attributes == null) { attributes = createAttributeList(size); } return attributes; } protected void setAttributeList(List attributeList) { this.attributes = attributeList; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/NamespaceStack.java0000644000175000017500000003502210242120012022046 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.dom4j.DocumentFactory; import org.dom4j.Namespace; import org.dom4j.QName; /** * NamespaceStack implements a stack of namespaces and optionally maintains a * cache of all the fully qualified names (QName) which are in * scope. This is useful when building or navigating a dom4j document. * * @author James Strachan * @version $Revision: 1.13 $ */ public class NamespaceStack { /** The factory used to create new Namespace instances */ private DocumentFactory documentFactory; /** The Stack of namespaces */ private ArrayList namespaceStack = new ArrayList(); /** The cache of qualifiedNames to QNames per namespace context */ private ArrayList namespaceCacheList = new ArrayList(); /** * A cache of current namespace context cache of mapping from qualifiedName * to QName */ private Map currentNamespaceCache; /** * A cache of mapping from qualifiedName to QName before any namespaces are * declared */ private Map rootNamespaceCache = new HashMap(); /** Caches the default namespace defined via xmlns="" */ private Namespace defaultNamespace; public NamespaceStack() { this.documentFactory = DocumentFactory.getInstance(); } public NamespaceStack(DocumentFactory documentFactory) { this.documentFactory = documentFactory; } /** * Pushes the given namespace onto the stack so that its prefix becomes * available. * * @param namespace * is the Namespace to add to the stack. */ public void push(Namespace namespace) { namespaceStack.add(namespace); namespaceCacheList.add(null); currentNamespaceCache = null; String prefix = namespace.getPrefix(); if ((prefix == null) || (prefix.length() == 0)) { defaultNamespace = namespace; } } /** * Pops the most recently used Namespace from the stack * * @return Namespace popped from the stack */ public Namespace pop() { return remove(namespaceStack.size() - 1); } /** * DOCUMENT ME! * * @return the number of namespaces on the stackce stack. */ public int size() { return namespaceStack.size(); } /** * Clears the stack */ public void clear() { namespaceStack.clear(); namespaceCacheList.clear(); rootNamespaceCache.clear(); currentNamespaceCache = null; } /** * DOCUMENT ME! * * @param index * DOCUMENT ME! * * @return the namespace at the specified index on the stack */ public Namespace getNamespace(int index) { return (Namespace) namespaceStack.get(index); } /** * DOCUMENT ME! * * @param prefix * DOCUMENT ME! * * @return the namespace for the given prefix or null if it could not be * found. */ public Namespace getNamespaceForPrefix(String prefix) { if (prefix == null) { prefix = ""; } for (int i = namespaceStack.size() - 1; i >= 0; i--) { Namespace namespace = (Namespace) namespaceStack.get(i); if (prefix.equals(namespace.getPrefix())) { return namespace; } } return null; } /** * DOCUMENT ME! * * @param prefix * DOCUMENT ME! * * @return the URI for the given prefix or null if it could not be found. */ public String getURI(String prefix) { Namespace namespace = getNamespaceForPrefix(prefix); return (namespace != null) ? namespace.getURI() : null; } /** * DOCUMENT ME! * * @param namespace * DOCUMENT ME! * * @return true if the given prefix is in the stack. */ public boolean contains(Namespace namespace) { String prefix = namespace.getPrefix(); Namespace current = null; if ((prefix == null) || (prefix.length() == 0)) { current = getDefaultNamespace(); } else { current = getNamespaceForPrefix(prefix); } if (current == null) { return false; } if (current == namespace) { return true; } return namespace.getURI().equals(current.getURI()); } public QName getQName(String namespaceURI, String localName, String qualifiedName) { if (localName == null) { localName = qualifiedName; } else if (qualifiedName == null) { qualifiedName = localName; } if (namespaceURI == null) { namespaceURI = ""; } String prefix = ""; int index = qualifiedName.indexOf(":"); if (index > 0) { prefix = qualifiedName.substring(0, index); if (localName.trim().length() == 0) { localName = qualifiedName.substring(index + 1); } } else if (localName.trim().length() == 0) { localName = qualifiedName; } Namespace namespace = createNamespace(prefix, namespaceURI); return pushQName(localName, qualifiedName, namespace, prefix); } public QName getAttributeQName(String namespaceURI, String localName, String qualifiedName) { if (qualifiedName == null) { qualifiedName = localName; } Map map = getNamespaceCache(); QName answer = (QName) map.get(qualifiedName); if (answer != null) { return answer; } if (localName == null) { localName = qualifiedName; } if (namespaceURI == null) { namespaceURI = ""; } Namespace namespace = null; String prefix = ""; int index = qualifiedName.indexOf(":"); if (index > 0) { prefix = qualifiedName.substring(0, index); namespace = createNamespace(prefix, namespaceURI); if (localName.trim().length() == 0) { localName = qualifiedName.substring(index + 1); } } else { // attributes with no prefix have no namespace namespace = Namespace.NO_NAMESPACE; if (localName.trim().length() == 0) { localName = qualifiedName; } } answer = pushQName(localName, qualifiedName, namespace, prefix); map.put(qualifiedName, answer); return answer; } /** * Adds a namepace to the stack with the given prefix and URI * * @param prefix * DOCUMENT ME! * @param uri * DOCUMENT ME! */ public void push(String prefix, String uri) { if (uri == null) { uri = ""; } Namespace namespace = createNamespace(prefix, uri); push(namespace); } /** * Adds a new namespace to the stack * * @param prefix * DOCUMENT ME! * @param uri * DOCUMENT ME! * * @return DOCUMENT ME! */ public Namespace addNamespace(String prefix, String uri) { Namespace namespace = createNamespace(prefix, uri); push(namespace); return namespace; } /** * Pops a namepace from the stack with the given prefix and URI * * @param prefix * DOCUMENT ME! * * @return DOCUMENT ME! */ public Namespace pop(String prefix) { if (prefix == null) { prefix = ""; } Namespace namespace = null; for (int i = namespaceStack.size() - 1; i >= 0; i--) { Namespace ns = (Namespace) namespaceStack.get(i); if (prefix.equals(ns.getPrefix())) { remove(i); namespace = ns; break; } } if (namespace == null) { System.out.println("Warning: missing namespace prefix ignored: " + prefix); } return namespace; } public String toString() { return super.toString() + " Stack: " + namespaceStack.toString(); } public DocumentFactory getDocumentFactory() { return documentFactory; } public void setDocumentFactory(DocumentFactory documentFactory) { this.documentFactory = documentFactory; } public Namespace getDefaultNamespace() { if (defaultNamespace == null) { defaultNamespace = findDefaultNamespace(); } return defaultNamespace; } // Implementation methods // ------------------------------------------------------------------------- /** * Adds the QName to the stack of available QNames * * @param localName * DOCUMENT ME! * @param qualifiedName * DOCUMENT ME! * @param namespace * DOCUMENT ME! * @param prefix * DOCUMENT ME! * * @return DOCUMENT ME! */ protected QName pushQName(String localName, String qualifiedName, Namespace namespace, String prefix) { if ((prefix == null) || (prefix.length() == 0)) { this.defaultNamespace = null; } return createQName(localName, qualifiedName, namespace); } /** * Factory method to creeate new QName instances. By default this method * interns the QName * * @param localName * DOCUMENT ME! * @param qualifiedName * DOCUMENT ME! * @param namespace * DOCUMENT ME! * * @return DOCUMENT ME! */ protected QName createQName(String localName, String qualifiedName, Namespace namespace) { return documentFactory.createQName(localName, namespace); } /** * Factory method to creeate new Namespace instances. By default this method * interns the Namespace * * @param prefix * DOCUMENT ME! * @param namespaceURI * DOCUMENT ME! * * @return DOCUMENT ME! */ protected Namespace createNamespace(String prefix, String namespaceURI) { return documentFactory.createNamespace(prefix, namespaceURI); } /** * Attempts to find the current default namespace on the stack right now or * returns null if one could not be found * * @return DOCUMENT ME! */ protected Namespace findDefaultNamespace() { for (int i = namespaceStack.size() - 1; i >= 0; i--) { Namespace namespace = (Namespace) namespaceStack.get(i); if (namespace != null) { String prefix = namespace.getPrefix(); if ((prefix == null) || (namespace.getPrefix().length() == 0)) { return namespace; } } } return null; } /** * Removes the namespace at the given index of the stack * * @param index * DOCUMENT ME! * * @return DOCUMENT ME! */ protected Namespace remove(int index) { Namespace namespace = (Namespace) namespaceStack.remove(index); namespaceCacheList.remove(index); defaultNamespace = null; currentNamespaceCache = null; return namespace; } protected Map getNamespaceCache() { if (currentNamespaceCache == null) { int index = namespaceStack.size() - 1; if (index < 0) { currentNamespaceCache = rootNamespaceCache; } else { currentNamespaceCache = (Map) namespaceCacheList.get(index); if (currentNamespaceCache == null) { currentNamespaceCache = new HashMap(); namespaceCacheList.set(index, currentNamespaceCache); } } } return currentNamespaceCache; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/ContentListFacade.java0000644000175000017500000001451210242120007022523 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.util.AbstractList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.dom4j.IllegalAddException; import org.dom4j.Node; /** *

* ContentListFacade represents a facade of the content of a * {@link org.dom4j.Branch} which is returned via calls to the {@link * org.dom4j.Branch#content} method to allow users to modify the content of a * {@link org.dom4j.Branch} directly using the {@link List} interface. This list * is backed by the branch such that changes to the list will be reflected in * the branch and changes to the branch will be reflected in this list. *

* * @author James Strachan * @version $Revision: 1.11 $ */ public class ContentListFacade extends AbstractList { /** The content of the Branch which is modified if I am modified */ private List branchContent; /** The AbstractBranch instance which owns the content */ private AbstractBranch branch; public ContentListFacade(AbstractBranch branch, List branchContent) { this.branch = branch; this.branchContent = branchContent; } public boolean add(Object object) { branch.childAdded(asNode(object)); return branchContent.add(object); } public void add(int index, Object object) { branch.childAdded(asNode(object)); branchContent.add(index, object); } public Object set(int index, Object object) { branch.childAdded(asNode(object)); return branchContent.set(index, object); } public boolean remove(Object object) { branch.childRemoved(asNode(object)); return branchContent.remove(object); } public Object remove(int index) { Object object = branchContent.remove(index); if (object != null) { branch.childRemoved(asNode(object)); } return object; } public boolean addAll(Collection collection) { int count = branchContent.size(); for (Iterator iter = collection.iterator(); iter.hasNext(); count++) { add(iter.next()); } return count == branchContent.size(); } public boolean addAll(int index, Collection collection) { int count = branchContent.size(); for (Iterator iter = collection.iterator(); iter.hasNext(); count--) { add(index++, iter.next()); } return count == branchContent.size(); } public void clear() { for (Iterator iter = iterator(); iter.hasNext();) { Object object = iter.next(); branch.childRemoved(asNode(object)); } branchContent.clear(); } public boolean removeAll(Collection c) { for (Iterator iter = c.iterator(); iter.hasNext();) { Object object = iter.next(); branch.childRemoved(asNode(object)); } return branchContent.removeAll(c); } public int size() { return branchContent.size(); } public boolean isEmpty() { return branchContent.isEmpty(); } public boolean contains(Object o) { return branchContent.contains(o); } public Object[] toArray() { return branchContent.toArray(); } public Object[] toArray(Object[] a) { return branchContent.toArray(a); } public boolean containsAll(Collection c) { return branchContent.containsAll(c); } public Object get(int index) { return branchContent.get(index); } public int indexOf(Object o) { return branchContent.indexOf(o); } public int lastIndexOf(Object o) { return branchContent.lastIndexOf(o); } protected Node asNode(Object object) { if (object instanceof Node) { return (Node) object; } else { throw new IllegalAddException( "This list must contain instances of " + "Node. Invalid type: " + object); } } protected List getBackingList() { return branchContent; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/DefaultAttribute.java0000644000175000017500000001124710242120021022437 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.QName; /** *

* DefaultAttribute implements a doubly linked node which * supports the parent relationship and is mutable. *

* * @author James Strachan * @version $Revision: 1.13 $ */ public class DefaultAttribute extends FlyweightAttribute { /** The parent of this node */ private Element parent; public DefaultAttribute(QName qname) { super(qname); } public DefaultAttribute(QName qname, String value) { super(qname, value); } public DefaultAttribute(Element parent, QName qname, String value) { super(qname, value); this.parent = parent; } /** * Creates the Attribute with the specified local name and * value. * * @param name * is the name of the attribute * @param value * is the value of the attribute */ public DefaultAttribute(String name, String value) { super(name, value); } /** * Creates the Attribute with the specified local name, value * and Namespace. * * @param name * is the name of the attribute * @param value * is the value of the attribute * @param namespace * is the namespace of the attribute */ public DefaultAttribute(String name, String value, Namespace namespace) { super(name, value, namespace); } /** * Creates the Attribute with the specified local name, value * and Namespace. * * @param parent * is the parent element * @param name * is the name of the attribute * @param value * is the value of the attribute * @param namespace * is the namespace of the attribute */ public DefaultAttribute(Element parent, String name, String value, Namespace namespace) { super(name, value, namespace); this.parent = parent; } public void setValue(String value) { this.value = value; } public Element getParent() { return parent; } public void setParent(Element parent) { this.parent = parent; } public boolean supportsParent() { return true; } public boolean isReadOnly() { return false; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/AbstractComment.java0000644000175000017500000000716310242120004022260 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.io.IOException; import java.io.Writer; import org.dom4j.Comment; import org.dom4j.Element; import org.dom4j.Visitor; /** *

* AbstractComment is an abstract base class for tree * implementors to use for implementation inheritence. *

* * @author James Strachan * @version $Revision: 1.13 $ */ public abstract class AbstractComment extends AbstractCharacterData implements Comment { public AbstractComment() { } public short getNodeType() { return COMMENT_NODE; } public String getPath(Element context) { Element parent = getParent(); return ((parent != null) && (parent != context)) ? (parent .getPath(context) + "/comment()") : "comment()"; } public String getUniquePath(Element context) { Element parent = getParent(); return ((parent != null) && (parent != context)) ? (parent .getUniquePath(context) + "/comment()") : "comment()"; } public String toString() { return super.toString() + " [Comment: \"" + getText() + "\"]"; } public String asXML() { return ""; } public void write(Writer writer) throws IOException { writer.write(""); } public void accept(Visitor visitor) { visitor.visit(this); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/AbstractElement.java0000644000175000017500000013424610242120017022256 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import org.dom4j.Attribute; import org.dom4j.CDATA; import org.dom4j.CharacterData; import org.dom4j.Comment; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.Entity; import org.dom4j.IllegalAddException; import org.dom4j.Namespace; import org.dom4j.Node; import org.dom4j.ProcessingInstruction; import org.dom4j.QName; import org.dom4j.Text; import org.dom4j.Visitor; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import org.xml.sax.Attributes; /** *

* AbstractElement is an abstract base class for tree * implementors to use for implementation inheritence. *

* * @author James Strachan * @version $Revision: 1.80 $ */ public abstract class AbstractElement extends AbstractBranch implements org.dom4j.Element { /** The DocumentFactory instance used by default */ private static final DocumentFactory DOCUMENT_FACTORY = DocumentFactory .getInstance(); protected static final List EMPTY_LIST = Collections.EMPTY_LIST; protected static final Iterator EMPTY_ITERATOR = EMPTY_LIST.iterator(); protected static final boolean VERBOSE_TOSTRING = false; protected static final boolean USE_STRINGVALUE_SEPARATOR = false; public AbstractElement() { } public short getNodeType() { return ELEMENT_NODE; } public boolean isRootElement() { Document document = getDocument(); if (document != null) { Element root = document.getRootElement(); if (root == this) { return true; } } return false; } public void setName(String name) { setQName(getDocumentFactory().createQName(name)); } public void setNamespace(Namespace namespace) { setQName(getDocumentFactory().createQName(getName(), namespace)); } /** * Returns the XPath expression to match this Elements name which is * getQualifiedName() if there is a namespace prefix defined or if no * namespace is present then it is getName() or if a namespace is defined * with no prefix then the expression is [name()='X'] where X = getName(). * * @return DOCUMENT ME! */ public String getXPathNameStep() { String uri = getNamespaceURI(); if ((uri == null) || (uri.length() == 0)) { return getName(); } String prefix = getNamespacePrefix(); if ((prefix == null) || (prefix.length() == 0)) { return "*[name()='" + getName() + "']"; } return getQualifiedName(); } public String getPath(Element context) { if (this == context) { return "."; } Element parent = getParent(); if (parent == null) { return "/" + getXPathNameStep(); } else if (parent == context) { return getXPathNameStep(); } return parent.getPath(context) + "/" + getXPathNameStep(); } public String getUniquePath(Element context) { Element parent = getParent(); if (parent == null) { return "/" + getXPathNameStep(); } StringBuffer buffer = new StringBuffer(); if (parent != context) { buffer.append(parent.getUniquePath(context)); buffer.append("/"); } buffer.append(getXPathNameStep()); List mySiblings = parent.elements(getQName()); if (mySiblings.size() > 1) { int idx = mySiblings.indexOf(this); if (idx >= 0) { buffer.append("["); buffer.append(Integer.toString(++idx)); buffer.append("]"); } } return buffer.toString(); } public String asXML() { try { StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, new OutputFormat()); writer.write(this); writer.flush(); return out.toString(); } catch (IOException e) { throw new RuntimeException("IOException while generating " + "textual representation: " + e.getMessage()); } } public void write(Writer out) throws IOException { XMLWriter writer = new XMLWriter(out, new OutputFormat()); writer.write(this); } /** *

* accept method is the Visitor Pattern * method. *

* * @param visitor * Visitor is the visitor. */ public void accept(Visitor visitor) { visitor.visit(this); // visit attributes for (int i = 0, size = attributeCount(); i < size; i++) { Attribute attribute = attribute(i); visitor.visit(attribute); } // visit content for (int i = 0, size = nodeCount(); i < size; i++) { Node node = node(i); node.accept(visitor); } } public String toString() { String uri = getNamespaceURI(); if ((uri != null) && (uri.length() > 0)) { if (VERBOSE_TOSTRING) { return super.toString() + " [Element: <" + getQualifiedName() + " uri: " + uri + " attributes: " + attributeList() + " content: " + contentList() + " />]"; } else { return super.toString() + " [Element: <" + getQualifiedName() + " uri: " + uri + " attributes: " + attributeList() + "/>]"; } } else { if (VERBOSE_TOSTRING) { return super.toString() + " [Element: <" + getQualifiedName() + " attributes: " + attributeList() + " content: " + contentList() + " />]"; } else { return super.toString() + " [Element: <" + getQualifiedName() + " attributes: " + attributeList() + "/>]"; } } } // QName methods // ------------------------------------------------------------------------- public Namespace getNamespace() { return getQName().getNamespace(); } public String getName() { return getQName().getName(); } public String getNamespacePrefix() { return getQName().getNamespacePrefix(); } public String getNamespaceURI() { return getQName().getNamespaceURI(); } public String getQualifiedName() { return getQName().getQualifiedName(); } public Object getData() { return getText(); } public void setData(Object data) { // ignore this method } // Node methods // ------------------------------------------------------------------------- public Node node(int index) { if (index >= 0) { List list = contentList(); if (index >= list.size()) { return null; } Object node = list.get(index); if (node != null) { if (node instanceof Node) { return (Node) node; } else { return getDocumentFactory().createText(node.toString()); } } } return null; } public int indexOf(Node node) { return contentList().indexOf(node); } public int nodeCount() { return contentList().size(); } public Iterator nodeIterator() { return contentList().iterator(); } // Element methods // ------------------------------------------------------------------------- public Element element(String name) { List list = contentList(); int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Element) { Element element = (Element) object; if (name.equals(element.getName())) { return element; } } } return null; } public Element element(QName qName) { List list = contentList(); int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Element) { Element element = (Element) object; if (qName.equals(element.getQName())) { return element; } } } return null; } public Element element(String name, Namespace namespace) { return element(getDocumentFactory().createQName(name, namespace)); } public List elements() { List list = contentList(); BackedList answer = createResultList(); int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Element) { answer.addLocal(object); } } return answer; } public List elements(String name) { List list = contentList(); BackedList answer = createResultList(); int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Element) { Element element = (Element) object; if (name.equals(element.getName())) { answer.addLocal(element); } } } return answer; } public List elements(QName qName) { List list = contentList(); BackedList answer = createResultList(); int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Element) { Element element = (Element) object; if (qName.equals(element.getQName())) { answer.addLocal(element); } } } return answer; } public List elements(String name, Namespace namespace) { return elements(getDocumentFactory().createQName(name, namespace)); } public Iterator elementIterator() { List list = elements(); return list.iterator(); } public Iterator elementIterator(String name) { List list = elements(name); return list.iterator(); } public Iterator elementIterator(QName qName) { List list = elements(qName); return list.iterator(); } public Iterator elementIterator(String name, Namespace ns) { return elementIterator(getDocumentFactory().createQName(name, ns)); } // Attribute methods // ------------------------------------------------------------------------- public List attributes() { return new ContentListFacade(this, attributeList()); } public Iterator attributeIterator() { return attributeList().iterator(); } public Attribute attribute(int index) { return (Attribute) attributeList().get(index); } public int attributeCount() { return attributeList().size(); } public Attribute attribute(String name) { List list = attributeList(); int size = list.size(); for (int i = 0; i < size; i++) { Attribute attribute = (Attribute) list.get(i); if (name.equals(attribute.getName())) { return attribute; } } return null; } public Attribute attribute(QName qName) { List list = attributeList(); int size = list.size(); for (int i = 0; i < size; i++) { Attribute attribute = (Attribute) list.get(i); if (qName.equals(attribute.getQName())) { return attribute; } } return null; } public Attribute attribute(String name, Namespace namespace) { return attribute(getDocumentFactory().createQName(name, namespace)); } /** * This method provides a more optimal way of setting all the attributes on * an Element particularly for use in {@link org.dom4j.io.SAXReader}. * * @param attributes * DOCUMENT ME! * @param namespaceStack * DOCUMENT ME! * @param noNamespaceAttributes * DOCUMENT ME! */ public void setAttributes(Attributes attributes, NamespaceStack namespaceStack, boolean noNamespaceAttributes) { // now lets add all attribute values int size = attributes.getLength(); if (size > 0) { DocumentFactory factory = getDocumentFactory(); if (size == 1) { // allow lazy construction of the List of Attributes String name = attributes.getQName(0); if (noNamespaceAttributes || !name.startsWith("xmlns")) { String attributeURI = attributes.getURI(0); String attributeLocalName = attributes.getLocalName(0); String attributeValue = attributes.getValue(0); QName attributeQName = namespaceStack.getAttributeQName( attributeURI, attributeLocalName, name); add(factory.createAttribute(this, attributeQName, attributeValue)); } } else { List list = attributeList(size); list.clear(); for (int i = 0; i < size; i++) { // optimised to avoid the call to attribute(QName) to // lookup an attribute for a given QName String attributeName = attributes.getQName(i); if (noNamespaceAttributes || !attributeName.startsWith("xmlns")) { String attributeURI = attributes.getURI(i); String attributeLocalName = attributes.getLocalName(i); String attributeValue = attributes.getValue(i); QName attributeQName = namespaceStack .getAttributeQName(attributeURI, attributeLocalName, attributeName); Attribute attribute = factory.createAttribute(this, attributeQName, attributeValue); list.add(attribute); childAdded(attribute); } } } } } public String attributeValue(String name) { Attribute attrib = attribute(name); if (attrib == null) { return null; } else { return attrib.getValue(); } } public String attributeValue(QName qName) { Attribute attrib = attribute(qName); if (attrib == null) { return null; } else { return attrib.getValue(); } } public String attributeValue(String name, String defaultValue) { String answer = attributeValue(name); return (answer != null) ? answer : defaultValue; } public String attributeValue(QName qName, String defaultValue) { String answer = attributeValue(qName); return (answer != null) ? answer : defaultValue; } /** * DOCUMENT ME! * * @param name * DOCUMENT ME! * @param value * DOCUMENT ME! * * @deprecated As of version 0.5. Please use {@link * #addAttribute(String,String)} instead. WILL BE REMOVED IN * dom4j-1.6 !! */ public void setAttributeValue(String name, String value) { addAttribute(name, value); } /** * DOCUMENT ME! * * @param qName * DOCUMENT ME! * @param value * DOCUMENT ME! * * @deprecated As of version 0.5. Please use {@link * #addAttribute(String,String)} instead. WILL BE REMOVED IN * dom4j-1.6 !! */ public void setAttributeValue(QName qName, String value) { addAttribute(qName, value); } public void add(Attribute attribute) { if (attribute.getParent() != null) { String message = "The Attribute already has an existing parent \"" + attribute.getParent().getQualifiedName() + "\""; throw new IllegalAddException(this, attribute, message); } if (attribute.getValue() == null) { // try remove a previous attribute with the same // name since adding an attribute with a null value // is equivalent to removing it. Attribute oldAttribute = attribute(attribute.getQName()); if (oldAttribute != null) { remove(oldAttribute); } } else { attributeList().add(attribute); childAdded(attribute); } } public boolean remove(Attribute attribute) { List list = attributeList(); boolean answer = list.remove(attribute); if (answer) { childRemoved(attribute); } else { // we may have a copy of the attribute Attribute copy = attribute(attribute.getQName()); if (copy != null) { list.remove(copy); answer = true; } } return answer; } // Processing instruction API // ------------------------------------------------------------------------- public List processingInstructions() { List list = contentList(); BackedList answer = createResultList(); int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof ProcessingInstruction) { answer.addLocal(object); } } return answer; } public List processingInstructions(String target) { List list = contentList(); BackedList answer = createResultList(); int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof ProcessingInstruction) { ProcessingInstruction pi = (ProcessingInstruction) object; if (target.equals(pi.getName())) { answer.addLocal(pi); } } } return answer; } public ProcessingInstruction processingInstruction(String target) { List list = contentList(); int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof ProcessingInstruction) { ProcessingInstruction pi = (ProcessingInstruction) object; if (target.equals(pi.getName())) { return pi; } } } return null; } public boolean removeProcessingInstruction(String target) { List list = contentList(); for (Iterator iter = list.iterator(); iter.hasNext();) { Object object = iter.next(); if (object instanceof ProcessingInstruction) { ProcessingInstruction pi = (ProcessingInstruction) object; if (target.equals(pi.getName())) { iter.remove(); return true; } } } return false; } // Content Model methods // ------------------------------------------------------------------------- public Node getXPathResult(int index) { Node answer = node(index); if ((answer != null) && !answer.supportsParent()) { return answer.asXPathResult(this); } return answer; } public Element addAttribute(String name, String value) { // adding a null value is equivalent to removing the attribute Attribute attribute = attribute(name); if (value != null) { if (attribute == null) { add(getDocumentFactory().createAttribute(this, name, value)); } else if (attribute.isReadOnly()) { remove(attribute); add(getDocumentFactory().createAttribute(this, name, value)); } else { attribute.setValue(value); } } else if (attribute != null) { remove(attribute); } return this; } public Element addAttribute(QName qName, String value) { // adding a null value is equivalent to removing the attribute Attribute attribute = attribute(qName); if (value != null) { if (attribute == null) { add(getDocumentFactory().createAttribute(this, qName, value)); } else if (attribute.isReadOnly()) { remove(attribute); add(getDocumentFactory().createAttribute(this, qName, value)); } else { attribute.setValue(value); } } else if (attribute != null) { remove(attribute); } return this; } public Element addCDATA(String cdata) { CDATA node = getDocumentFactory().createCDATA(cdata); addNewNode(node); return this; } public Element addComment(String comment) { Comment node = getDocumentFactory().createComment(comment); addNewNode(node); return this; } public Element addElement(String name) { DocumentFactory factory = getDocumentFactory(); int index = name.indexOf(":"); String prefix = ""; String localName = name; Namespace namespace = null; if (index > 0) { prefix = name.substring(0, index); localName = name.substring(index + 1); namespace = getNamespaceForPrefix(prefix); if (namespace == null) { throw new IllegalAddException("No such namespace prefix: " + prefix + " is in scope on: " + this + " so cannot add element: " + name); } } else { namespace = getNamespaceForPrefix(""); } Element node; if (namespace != null) { QName qname = factory.createQName(localName, namespace); node = factory.createElement(qname); } else { node = factory.createElement(name); } addNewNode(node); return node; } public Element addEntity(String name, String text) { Entity node = getDocumentFactory().createEntity(name, text); addNewNode(node); return this; } public Element addNamespace(String prefix, String uri) { Namespace node = getDocumentFactory().createNamespace(prefix, uri); addNewNode(node); return this; } public Element addProcessingInstruction(String target, String data) { ProcessingInstruction node = getDocumentFactory() .createProcessingInstruction(target, data); addNewNode(node); return this; } public Element addProcessingInstruction(String target, Map data) { ProcessingInstruction node = getDocumentFactory() .createProcessingInstruction(target, data); addNewNode(node); return this; } public Element addText(String text) { Text node = getDocumentFactory().createText(text); addNewNode(node); return this; } // polymorphic node methods public void add(Node node) { switch (node.getNodeType()) { case ELEMENT_NODE: add((Element) node); break; case ATTRIBUTE_NODE: add((Attribute) node); break; case TEXT_NODE: add((Text) node); break; case CDATA_SECTION_NODE: add((CDATA) node); break; case ENTITY_REFERENCE_NODE: add((Entity) node); break; case PROCESSING_INSTRUCTION_NODE: add((ProcessingInstruction) node); break; case COMMENT_NODE: add((Comment) node); break; /* * XXXX: to do! case DOCUMENT_TYPE_NODE: add((DocumentType) node); * break; */ case NAMESPACE_NODE: add((Namespace) node); break; default: invalidNodeTypeAddException(node); } } public boolean remove(Node node) { switch (node.getNodeType()) { case ELEMENT_NODE: return remove((Element) node); case ATTRIBUTE_NODE: return remove((Attribute) node); case TEXT_NODE: return remove((Text) node); case CDATA_SECTION_NODE: return remove((CDATA) node); case ENTITY_REFERENCE_NODE: return remove((Entity) node); case PROCESSING_INSTRUCTION_NODE: return remove((ProcessingInstruction) node); case COMMENT_NODE: return remove((Comment) node); /* * case DOCUMENT_TYPE_NODE: return remove((DocumentType) node); */ case NAMESPACE_NODE: return remove((Namespace) node); default: return false; } } // typesafe versions using node classes public void add(CDATA cdata) { addNode(cdata); } public void add(Comment comment) { addNode(comment); } public void add(Element element) { addNode(element); } public void add(Entity entity) { addNode(entity); } public void add(Namespace namespace) { addNode(namespace); } public void add(ProcessingInstruction pi) { addNode(pi); } public void add(Text text) { addNode(text); } public boolean remove(CDATA cdata) { return removeNode(cdata); } public boolean remove(Comment comment) { return removeNode(comment); } public boolean remove(Element element) { return removeNode(element); } public boolean remove(Entity entity) { return removeNode(entity); } public boolean remove(Namespace namespace) { return removeNode(namespace); } public boolean remove(ProcessingInstruction pi) { return removeNode(pi); } public boolean remove(Text text) { return removeNode(text); } // Helper methods // ------------------------------------------------------------------------- public boolean hasMixedContent() { List content = contentList(); if ((content == null) || content.isEmpty() || (content.size() < 2)) { return false; } Class prevClass = null; for (Iterator iter = content.iterator(); iter.hasNext();) { Object object = iter.next(); Class newClass = object.getClass(); if (newClass != prevClass) { if (prevClass != null) { return true; } prevClass = newClass; } } return false; } public boolean isTextOnly() { List content = contentList(); if ((content == null) || content.isEmpty()) { return true; } for (Iterator iter = content.iterator(); iter.hasNext();) { Object object = iter.next(); if (!(object instanceof CharacterData) && !(object instanceof String)) { return false; } } return true; } public void setText(String text) { /* remove all text nodes */ List allContent = contentList(); if (allContent != null) { Iterator it = allContent.iterator(); while (it.hasNext()) { Node node = (Node) it.next(); switch (node.getNodeType()) { case CDATA_SECTION_NODE: // case ENTITY_NODE: case ENTITY_REFERENCE_NODE: case TEXT_NODE: it.remove(); default: break; } } } addText(text); } public String getStringValue() { List list = contentList(); int size = list.size(); if (size > 0) { if (size == 1) { // optimised to avoid StringBuffer creation return getContentAsStringValue(list.get(0)); } else { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < size; i++) { Object node = list.get(i); String string = getContentAsStringValue(node); if (string.length() > 0) { if (USE_STRINGVALUE_SEPARATOR) { if (buffer.length() > 0) { buffer.append(' '); } } buffer.append(string); } } return buffer.toString(); } } return ""; } /** * Puts all Text nodes in the full depth of the sub-tree * underneath this Node, including attribute nodes, into a * "normal" form where only structure (e.g., elements, comments, processing * instructions, CDATA sections, and entity references) separates * Text nodes, i.e., there are neither adjacent * Text nodes nor empty Text nodes. This can * be used to ensure that the DOM view of a document is the same as if it * were saved and re-loaded, and is useful when operations (such as XPointer * lookups) that depend on a particular document tree structure are to be * used.In cases where the document contains CDATASections, * the normalize operation alone may not be sufficient, since XPointers do * not differentiate between Text nodes and * CDATASection nodes. * * @since DOM Level 2 */ public void normalize() { List content = contentList(); Text previousText = null; int i = 0; while (i < content.size()) { Node node = (Node) content.get(i); if (node instanceof Text) { Text text = (Text) node; if (previousText != null) { previousText.appendText(text.getText()); remove(text); } else { String value = text.getText(); // only remove empty Text nodes, not whitespace nodes // if ( value == null || value.trim().length() <= 0 ) { if ((value == null) || (value.length() <= 0)) { remove(text); } else { previousText = text; i++; } } } else { if (node instanceof Element) { Element element = (Element) node; element.normalize(); } previousText = null; i++; } } } public String elementText(String name) { Element element = element(name); return (element != null) ? element.getText() : null; } public String elementText(QName qName) { Element element = element(qName); return (element != null) ? element.getText() : null; } public String elementTextTrim(String name) { Element element = element(name); return (element != null) ? element.getTextTrim() : null; } public String elementTextTrim(QName qName) { Element element = element(qName); return (element != null) ? element.getTextTrim() : null; } // add to me content from another element // analagous to the addAll(collection) methods in Java 2 collections public void appendAttributes(Element element) { for (int i = 0, size = element.attributeCount(); i < size; i++) { Attribute attribute = element.attribute(i); if (attribute.supportsParent()) { addAttribute(attribute.getQName(), attribute.getValue()); } else { add(attribute); } } } /** *

* This returns a deep clone of this element. The new element is detached * from its parent, and getParent() on the clone will return null. *

* * @return the clone of this element */ /* * public Object clone() { Element clone = createElement(getQName()); * clone.appendAttributes(this); clone.appendContent(this); return clone; } */ public Element createCopy() { Element clone = createElement(getQName()); clone.appendAttributes(this); clone.appendContent(this); return clone; } public Element createCopy(String name) { Element clone = createElement(name); clone.appendAttributes(this); clone.appendContent(this); return clone; } public Element createCopy(QName qName) { Element clone = createElement(qName); clone.appendAttributes(this); clone.appendContent(this); return clone; } public QName getQName(String qualifiedName) { String prefix = ""; String localName = qualifiedName; int index = qualifiedName.indexOf(":"); if (index > 0) { prefix = qualifiedName.substring(0, index); localName = qualifiedName.substring(index + 1); } Namespace namespace = getNamespaceForPrefix(prefix); if (namespace != null) { return getDocumentFactory().createQName(localName, namespace); } else { return getDocumentFactory().createQName(localName); } } public Namespace getNamespaceForPrefix(String prefix) { if (prefix == null) { prefix = ""; } if (prefix.equals(getNamespacePrefix())) { return getNamespace(); } else if (prefix.equals("xml")) { return Namespace.XML_NAMESPACE; } else { List list = contentList(); int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Namespace) { Namespace namespace = (Namespace) object; if (prefix.equals(namespace.getPrefix())) { return namespace; } } } } Element parent = getParent(); if (parent != null) { Namespace answer = parent.getNamespaceForPrefix(prefix); if (answer != null) { return answer; } } if ((prefix == null) || (prefix.length() <= 0)) { return Namespace.NO_NAMESPACE; } return null; } public Namespace getNamespaceForURI(String uri) { if ((uri == null) || (uri.length() <= 0)) { return Namespace.NO_NAMESPACE; } else if (uri.equals(getNamespaceURI())) { return getNamespace(); } else { List list = contentList(); int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Namespace) { Namespace namespace = (Namespace) object; if (uri.equals(namespace.getURI())) { return namespace; } } } return null; } } public List getNamespacesForURI(String uri) { BackedList answer = createResultList(); // if (getNamespaceURI().equals(uri)) { // // answer.addLocal(getNamespace()); // // } List list = contentList(); int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if ((object instanceof Namespace) && ((Namespace) object).getURI().equals(uri)) { answer.addLocal(object); } } return answer; } public List declaredNamespaces() { BackedList answer = createResultList(); // if (getNamespaceURI().length() > 0) { // // answer.addLocal(getNamespace()); // // } // List list = contentList(); int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Namespace) { answer.addLocal(object); } } return answer; } public List additionalNamespaces() { List list = contentList(); int size = list.size(); BackedList answer = createResultList(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Namespace) { Namespace namespace = (Namespace) object; if (!namespace.equals(getNamespace())) { answer.addLocal(namespace); } } } return answer; } public List additionalNamespaces(String defaultNamespaceURI) { List list = contentList(); BackedList answer = createResultList(); int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Namespace) { Namespace namespace = (Namespace) object; if (!defaultNamespaceURI.equals(namespace.getURI())) { answer.addLocal(namespace); } } } return answer; } // Implementation helper methods // ------------------------------------------------------------------------- /** * Ensures that the list of attributes has the given size * * @param minCapacity * DOCUMENT ME! */ public void ensureAttributesCapacity(int minCapacity) { if (minCapacity > 1) { List list = attributeList(); if (list instanceof ArrayList) { ArrayList arrayList = (ArrayList) list; arrayList.ensureCapacity(minCapacity); } } } // Implementation methods // ------------------------------------------------------------------------- protected Element createElement(String name) { return getDocumentFactory().createElement(name); } protected Element createElement(QName qName) { return getDocumentFactory().createElement(qName); } protected void addNode(Node node) { if (node.getParent() != null) { // XXX: could clone here String message = "The Node already has an existing parent of \"" + node.getParent().getQualifiedName() + "\""; throw new IllegalAddException(this, node, message); } addNewNode(node); } protected void addNode(int index, Node node) { if (node.getParent() != null) { // XXX: could clone here String message = "The Node already has an existing parent of \"" + node.getParent().getQualifiedName() + "\""; throw new IllegalAddException(this, node, message); } addNewNode(index, node); } /** * Like addNode() but does not require a parent check * * @param node * DOCUMENT ME! */ protected void addNewNode(Node node) { contentList().add(node); childAdded(node); } protected void addNewNode(int index, Node node) { contentList().add(index, node); childAdded(node); } protected boolean removeNode(Node node) { boolean answer = contentList().remove(node); if (answer) { childRemoved(node); } return answer; } /** * Called when a new child node is added to create any parent relationships * * @param node * DOCUMENT ME! */ protected void childAdded(Node node) { if (node != null) { node.setParent(this); } } protected void childRemoved(Node node) { if (node != null) { node.setParent(null); node.setDocument(null); } } /** * DOCUMENT ME! * * @return the internal List used to store attributes or creates one if one * is not available */ protected abstract List attributeList(); /** * DOCUMENT ME! * * @param attributeCount * DOCUMENT ME! * * @return the internal List used to store attributes or creates one with * the specified size if one is not available */ protected abstract List attributeList(int attributeCount); protected DocumentFactory getDocumentFactory() { QName qName = getQName(); // QName might be null as we might not have been constructed yet if (qName != null) { DocumentFactory factory = qName.getDocumentFactory(); if (factory != null) { return factory; } } return DOCUMENT_FACTORY; } /** * A Factory Method pattern which creates a List implementation used to * store attributes * * @return DOCUMENT ME! */ protected List createAttributeList() { return createAttributeList(DEFAULT_CONTENT_LIST_SIZE); } /** * A Factory Method pattern which creates a List implementation used to * store attributes * * @param size * DOCUMENT ME! * * @return DOCUMENT ME! */ protected List createAttributeList(int size) { return new ArrayList(size); } protected Iterator createSingleIterator(Object result) { return new SingleIterator(result); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/BackedList.java0000644000175000017500000001530310242117777021221 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.dom4j.IllegalAddException; import org.dom4j.Node; /** *

* BackedList represents a list of content of a {@link * org.dom4j.Branch}. Changes to the list will be reflected in the branch, * though changes to the branch will not be reflected in this list. *

* * @author James Strachan * @version $Revision: 1.14 $ */ public class BackedList extends ArrayList { /** The content of the Branch which is modified if I am modified */ private List branchContent; /** The AbstractBranch instance which owns the content */ private AbstractBranch branch; public BackedList(AbstractBranch branch, List branchContent) { this(branch, branchContent, branchContent.size()); } public BackedList(AbstractBranch branch, List branchContent, int capacity) { super(capacity); this.branch = branch; this.branchContent = branchContent; } public BackedList(AbstractBranch branch, List branchContent, List initialContent) { super(initialContent); this.branch = branch; this.branchContent = branchContent; } public boolean add(Object object) { branch.addNode(asNode(object)); return super.add(object); } public void add(int index, Object object) { int size = size(); if (index < 0) { throw new IndexOutOfBoundsException("Index value: " + index + " is less than zero"); } else if (index > size) { throw new IndexOutOfBoundsException("Index value: " + index + " cannot be greater than " + "the size: " + size); } int realIndex; if (size == 0) { realIndex = branchContent.size(); } else if (index < size) { realIndex = branchContent.indexOf(get(index)); } else { realIndex = branchContent.indexOf(get(size - 1)) + 1; } branch.addNode(realIndex, asNode(object)); super.add(index, object); } public Object set(int index, Object object) { int realIndex = branchContent.indexOf(get(index)); if (realIndex < 0) { realIndex = (index == 0) ? 0 : Integer.MAX_VALUE; } if (realIndex < branchContent.size()) { branch.removeNode(asNode(get(index))); branch.addNode(realIndex, asNode(object)); } else { branch.removeNode(asNode(get(index))); branch.addNode(asNode(object)); } branch.childAdded(asNode(object)); return super.set(index, object); } public boolean remove(Object object) { branch.removeNode(asNode(object)); return super.remove(object); } public Object remove(int index) { Object object = super.remove(index); if (object != null) { branch.removeNode(asNode(object)); } return object; } public boolean addAll(Collection collection) { ensureCapacity(size() + collection.size()); int count = size(); for (Iterator iter = collection.iterator(); iter.hasNext(); count--) { add(iter.next()); } return count != 0; } public boolean addAll(int index, Collection collection) { ensureCapacity(size() + collection.size()); int count = size(); for (Iterator iter = collection.iterator(); iter.hasNext(); count--) { add(index++, iter.next()); } return count != 0; } public void clear() { for (Iterator iter = iterator(); iter.hasNext();) { Object object = iter.next(); branchContent.remove(object); branch.childRemoved(asNode(object)); } super.clear(); } /** * Performs a local addition which is not forward through to the Branch or * backing list * * @param object * DOCUMENT ME! */ public void addLocal(Object object) { super.add(object); } protected Node asNode(Object object) { if (object instanceof Node) { return (Node) object; } else { throw new IllegalAddException("This list must contain instances " + "of Node. Invalid type: " + object); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/AbstractCDATA.java0000644000175000017500000000663410242120005021475 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import org.dom4j.CDATA; import org.dom4j.Visitor; /** *

* AbstractCDATA is an abstract base class for tree implementors * to use for implementation inheritence. *

* * @author James Strachan * @version $Revision: 1.12 $ */ public abstract class AbstractCDATA extends AbstractCharacterData implements CDATA { public AbstractCDATA() { } public short getNodeType() { return CDATA_SECTION_NODE; } public String toString() { return super.toString() + " [CDATA: \"" + getText() + "\"]"; } public String asXML() { StringWriter writer = new StringWriter(); try { write(writer); } catch (IOException e) { // will not happen since we are using a StringWriter! } return writer.toString(); } public void write(Writer writer) throws IOException { writer.write(""); } public void accept(Visitor visitor) { visitor.visit(this); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/AbstractDocument.java0000644000175000017500000002113210242120006022426 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.Iterator; import java.util.List; import java.util.Map; import org.dom4j.Comment; import org.dom4j.Document; import org.dom4j.DocumentType; import org.dom4j.Element; import org.dom4j.IllegalAddException; import org.dom4j.Node; import org.dom4j.ProcessingInstruction; import org.dom4j.QName; import org.dom4j.Text; import org.dom4j.Visitor; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; /** *

* AbstractDocument is an abstract base class for tree * implementors to use for implementation inheritence. *

* * @author James Strachan * @version $Revision: 1.33 $ */ public abstract class AbstractDocument extends AbstractBranch implements Document { /** The encoding of this document as stated in the XML declaration */ protected String encoding; public AbstractDocument() { } public short getNodeType() { return DOCUMENT_NODE; } public String getPath(Element context) { return "/"; } public String getUniquePath(Element context) { return "/"; } public Document getDocument() { return this; } public String getXMLEncoding() { return null; } public String getStringValue() { Element root = getRootElement(); return (root != null) ? root.getStringValue() : ""; } public String asXML() { OutputFormat format = new OutputFormat(); format.setEncoding(encoding); try { StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, format); writer.write(this); writer.flush(); return out.toString(); } catch (IOException e) { throw new RuntimeException("IOException while generating textual " + "representation: " + e.getMessage()); } } public void write(Writer out) throws IOException { OutputFormat format = new OutputFormat(); format.setEncoding(encoding); XMLWriter writer = new XMLWriter(out, format); writer.write(this); } /** *

* accept method is the Visitor Pattern * method. *

* * @param visitor * Visitor is the visitor. */ public void accept(Visitor visitor) { visitor.visit(this); DocumentType docType = getDocType(); if (docType != null) { visitor.visit(docType); } // visit content List content = content(); if (content != null) { for (Iterator iter = content.iterator(); iter.hasNext();) { Object object = iter.next(); if (object instanceof String) { Text text = getDocumentFactory() .createText((String) object); visitor.visit(text); } else { Node node = (Node) object; node.accept(visitor); } } } } public String toString() { return super.toString() + " [Document: name " + getName() + "]"; } public void normalize() { Element element = getRootElement(); if (element != null) { element.normalize(); } } public Document addComment(String comment) { Comment node = getDocumentFactory().createComment(comment); add(node); return this; } public Document addProcessingInstruction(String target, String data) { ProcessingInstruction node = getDocumentFactory() .createProcessingInstruction(target, data); add(node); return this; } public Document addProcessingInstruction(String target, Map data) { ProcessingInstruction node = getDocumentFactory() .createProcessingInstruction(target, data); add(node); return this; } public Element addElement(String name) { Element element = getDocumentFactory().createElement(name); add(element); return element; } public Element addElement(String qualifiedName, String namespaceURI) { Element element = getDocumentFactory().createElement(qualifiedName, namespaceURI); add(element); return element; } public Element addElement(QName qName) { Element element = getDocumentFactory().createElement(qName); add(element); return element; } public void setRootElement(Element rootElement) { clearContent(); if (rootElement != null) { super.add(rootElement); rootElementAdded(rootElement); } } public void add(Element element) { checkAddElementAllowed(element); super.add(element); rootElementAdded(element); } public boolean remove(Element element) { boolean answer = super.remove(element); Element root = getRootElement(); if ((root != null) && answer) { setRootElement(null); } element.setDocument(null); return answer; } public Node asXPathResult(Element parent) { return this; } protected void childAdded(Node node) { if (node != null) { node.setDocument(this); } } protected void childRemoved(Node node) { if (node != null) { node.setDocument(null); } } protected void checkAddElementAllowed(Element element) { Element root = getRootElement(); if (root != null) { throw new IllegalAddException(this, element, "Cannot add another element to this " + "Document as it already has a root " + "element of: " + root.getQualifiedName()); } } /** * Called to set the root element variable * * @param rootElement * DOCUMENT ME! */ protected abstract void rootElementAdded(Element rootElement); public void setXMLEncoding(String enc) { this.encoding = enc; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/QNameCache.java0000644000175000017500000002210110242120014021105 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import org.dom4j.DocumentFactory; import org.dom4j.Namespace; import org.dom4j.QName; /** *

* QNameCache caches instances of QName for reuse * both across documents and within documents. *

< < < < < < < QNameCache.java * * @author James Strachan * @version $Revision: 1.16 $ ======= * * @author James Strachan * @version $Revision: 1.16 $ >>>>>>> 1.15 */ public class QNameCache { /** Cache of {@link QName}instances with no namespace */ protected Map noNamespaceCache = Collections .synchronizedMap(new WeakHashMap()); /** * Cache of {@link Map}instances indexed by namespace which contain caches * of {@link QName}for each name */ protected Map namespaceCache = Collections .synchronizedMap(new WeakHashMap()); /** * The document factory associated with new QNames instances in this cache * or null if no instances should be associated by default */ private DocumentFactory documentFactory; public QNameCache() { } public QNameCache(DocumentFactory documentFactory) { this.documentFactory = documentFactory; } /** * Returns a list of all the QName instances currently used * * @return DOCUMENT ME! */ public List getQNames() { List answer = new ArrayList(); answer.addAll(noNamespaceCache.values()); for (Iterator it = namespaceCache.values().iterator(); it.hasNext();) { Map map = (Map) it.next(); answer.addAll(map.values()); } return answer; } /** * DOCUMENT ME! * * @param name * DOCUMENT ME! * * @return the QName for the given name and no namepsace */ public QName get(String name) { QName answer = null; if (name != null) { answer = (QName) noNamespaceCache.get(name); } else { name = ""; } if (answer == null) { answer = createQName(name); answer.setDocumentFactory(documentFactory); noNamespaceCache.put(name, answer); } return answer; } /** * DOCUMENT ME! * * @param name * DOCUMENT ME! * @param namespace * DOCUMENT ME! * * @return the QName for the given local name and namepsace */ public QName get(String name, Namespace namespace) { Map cache = getNamespaceCache(namespace); QName answer = null; if (name != null) { answer = (QName) cache.get(name); } else { name = ""; } if (answer == null) { answer = createQName(name, namespace); answer.setDocumentFactory(documentFactory); cache.put(name, answer); } return answer; } /** * DOCUMENT ME! * * @param localName * DOCUMENT ME! * @param namespace * DOCUMENT ME! * @param qName * DOCUMENT ME! * * @return the QName for the given local name, qualified name and namepsace */ public QName get(String localName, Namespace namespace, String qName) { Map cache = getNamespaceCache(namespace); QName answer = null; if (localName != null) { answer = (QName) cache.get(localName); } else { localName = ""; } if (answer == null) { answer = createQName(localName, namespace, qName); answer.setDocumentFactory(documentFactory); cache.put(localName, answer); } return answer; } public QName get(String qualifiedName, String uri) { int index = qualifiedName.indexOf(':'); if (index < 0) { return get(qualifiedName, Namespace.get(uri)); } else { String name = qualifiedName.substring(index + 1); String prefix = qualifiedName.substring(0, index); return get(name, Namespace.get(prefix, uri)); } } /** * DOCUMENT ME! * * @param qname * DOCUMENT ME! * * @return the cached QName instance if there is one or adds the given qname * to the cache if not */ public QName intern(QName qname) { return get(qname.getName(), qname.getNamespace(), qname .getQualifiedName()); } /** * DOCUMENT ME! * * @param namespace * DOCUMENT ME! * * @return the cache for the given namespace. If one does not currently * exist it is created. */ protected Map getNamespaceCache(Namespace namespace) { if (namespace == Namespace.NO_NAMESPACE) { return noNamespaceCache; } Map answer = null; if (namespace != null) { answer = (Map) namespaceCache.get(namespace); } if (answer == null) { answer = createMap(); namespaceCache.put(namespace, answer); } return answer; } /** * A factory method * * @return a newly created {@link Map}instance. */ protected Map createMap() { return Collections.synchronizedMap(new HashMap()); } /** * Factory method to create a new QName object which can be overloaded to * create derived QName instances * * @param name * DOCUMENT ME! * * @return DOCUMENT ME! */ protected QName createQName(String name) { return new QName(name); } /** * Factory method to create a new QName object which can be overloaded to * create derived QName instances * * @param name * DOCUMENT ME! * @param namespace * DOCUMENT ME! * * @return DOCUMENT ME! */ protected QName createQName(String name, Namespace namespace) { return new QName(name, namespace); } /** * Factory method to create a new QName object which can be overloaded to * create derived QName instances * * @param name * DOCUMENT ME! * @param namespace * DOCUMENT ME! * @param qualifiedName * DOCUMENT ME! * * @return DOCUMENT ME! */ protected QName createQName(String name, Namespace namespace, String qualifiedName) { return new QName(name, namespace, qualifiedName); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */dom4j-1.6.1/src/java/org/dom4j/tree/FilterIterator.java0000644000175000017500000001025410242120020022122 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.util.Iterator; import java.util.NoSuchElementException; /** *

* FilterIterator is an abstract base class which is useful for * implementors of {@link Iterator}which filter an existing iterator. *

* * @author James Strachan * @version $Revision: 1.10 $ * * @deprecated THIS CLASS WILL BE REMOVED IN dom4j-1.6 !! */ public abstract class FilterIterator implements Iterator { protected Iterator proxy; private Object next; private boolean first = true; public FilterIterator(Iterator proxy) { this.proxy = proxy; } public boolean hasNext() { if (first) { next = findNext(); first = false; } return next != null; } public Object next() throws NoSuchElementException { if (!hasNext()) { throw new NoSuchElementException(); } Object answer = this.next; this.next = findNext(); return answer; } /** * Always throws UnsupportedOperationException as this class does look-ahead * with its internal iterator. * * @throws UnsupportedOperationException * always */ public void remove() { throw new UnsupportedOperationException(); } /** * Filter method to perform some matching on the given element. * * @param element * DOCUMENT ME! * * @return true if the given element matches the filter and should be appear * in the iteration */ protected abstract boolean matches(Object element); protected Object findNext() { if (proxy != null) { while (proxy.hasNext()) { Object nextObject = proxy.next(); if ((nextObject != null) && matches(nextObject)) { return nextObject; } } proxy = null; } return null; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/ElementQNameIterator.java0000644000175000017500000000645210242120013023217 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.util.Iterator; import org.dom4j.Element; import org.dom4j.QName; /** *

* ElementQNameIterator is a filtering {@link Iterator}which * filters out objects which do not implement the {@link Element}interface and * are not of the correct fully qualified element name. *

* * @author James Strachan * @version $Revision: 1.7 $ * * @deprecated THIS CLASS WILL BE REMOVED IN dom4j-1.6 !! */ public class ElementQNameIterator extends FilterIterator { private QName qName; public ElementQNameIterator(Iterator proxy, QName qName) { super(proxy); this.qName = qName; } /** * DOCUMENT ME! * * @param object * DOCUMENT ME! * * @return true if the given element implements the {@link Element} * interface and matches the given {@link QName} */ protected boolean matches(Object object) { if (object instanceof Element) { Element element = (Element) object; return qName.equals(element.getQName()); } return false; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/FlyweightCDATA.java0000644000175000017500000000611110242120015021663 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import org.dom4j.CDATA; import org.dom4j.Element; import org.dom4j.Node; /** *

* FlyweightCDATA is a Flyweight pattern implementation of a * singly linked, read-only XML CDATA. *

* *

* This node could be shared across documents and elements though it does not * support the parent relationship. *

* * @author James Strachan * @version $Revision: 1.8 $ */ public class FlyweightCDATA extends AbstractCDATA implements CDATA { /** Text of the CDATA node */ protected String text; /** * DOCUMENT ME! * * @param text * is the CDATA text */ public FlyweightCDATA(String text) { this.text = text; } public String getText() { return text; } protected Node createXPathResult(Element parent) { return new DefaultCDATA(parent, getText()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/FlyweightComment.java0000644000175000017500000000613510242120007022460 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import org.dom4j.Comment; import org.dom4j.Element; import org.dom4j.Node; /** *

* FlyweightComment is a Flyweight pattern implementation of a * singly linked, read-only XML Comment. *

* *

* This node could be shared across documents and elements though it does not * support the parent relationship. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public class FlyweightComment extends AbstractComment implements Comment { /** Text of the Comment node */ protected String text; /** * DOCUMENT ME! * * @param text * is the Comment text */ public FlyweightComment(String text) { this.text = text; } public String getText() { return text; } protected Node createXPathResult(Element parent) { return new DefaultComment(parent, getText()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/DefaultElement.java0000644000175000017500000007425210242120023022074 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Branch; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.IllegalAddException; import org.dom4j.Namespace; import org.dom4j.Node; import org.dom4j.ProcessingInstruction; import org.dom4j.QName; /** *

* DefaultElement is the default DOM4J default implementation of * an XML element. *

* * @author James Strachan * @version $Revision: 1.59 $ */ public class DefaultElement extends AbstractElement { /** The DocumentFactory instance used by default */ private static final transient DocumentFactory DOCUMENT_FACTORY = DocumentFactory.getInstance(); /** The QName for this element */ private QName qname; /** * Stores the parent branch of this node which is either a Document if this * element is the root element in a document, or another Element if it is a * child of the root document, or null if it has not been added to a * document yet. */ private Branch parentBranch; /** * Stores null for no content, a Node for a single content node or a List * for multiple content nodes. The List will be lazily constructed when * required. */ private Object content; /** Lazily constructes list of attributes */ private Object attributes; public DefaultElement(String name) { this.qname = DOCUMENT_FACTORY.createQName(name); } public DefaultElement(QName qname) { this.qname = qname; } public DefaultElement(QName qname, int attributeCount) { this.qname = qname; if (attributeCount > 1) { this.attributes = new ArrayList(attributeCount); } } public DefaultElement(String name, Namespace namespace) { this.qname = DOCUMENT_FACTORY.createQName(name, namespace); } public Element getParent() { Element result = null; if (parentBranch instanceof Element) { result = (Element) parentBranch; } return result; } public void setParent(Element parent) { if (parentBranch instanceof Element || (parent != null)) { parentBranch = parent; } } public Document getDocument() { if (parentBranch instanceof Document) { return (Document) parentBranch; } else if (parentBranch instanceof Element) { Element parent = (Element) parentBranch; return parent.getDocument(); } return null; } public void setDocument(Document document) { if (parentBranch instanceof Document || (document != null)) { parentBranch = document; } } public boolean supportsParent() { return true; } public QName getQName() { return qname; } public void setQName(QName name) { this.qname = name; } public String getText() { final Object contentShadow = content; if (contentShadow instanceof List) { return super.getText(); } else { if (contentShadow != null) { return getContentAsText(contentShadow); } else { return ""; } } } public String getStringValue() { final Object contentShadow = content; if (contentShadow instanceof List) { List list = (List) contentShadow; int size = list.size(); if (size > 0) { if (size == 1) { // optimised to avoid StringBuffer creation return getContentAsStringValue(list.get(0)); } else { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < size; i++) { Object node = list.get(i); String string = getContentAsStringValue(node); if (string.length() > 0) { if (USE_STRINGVALUE_SEPARATOR) { if (buffer.length() > 0) { buffer.append(' '); } } buffer.append(string); } } return buffer.toString(); } } } else { if (contentShadow != null) { return getContentAsStringValue(contentShadow); } } return ""; } public Object clone() { DefaultElement answer = (DefaultElement) super.clone(); if (answer != this) { answer.content = null; answer.attributes = null; answer.appendAttributes(this); answer.appendContent(this); } return answer; } public Namespace getNamespaceForPrefix(String prefix) { if (prefix == null) { prefix = ""; } if (prefix.equals(getNamespacePrefix())) { return getNamespace(); } else if (prefix.equals("xml")) { return Namespace.XML_NAMESPACE; } else { final Object contentShadow = content; if (contentShadow instanceof List) { List list = (List) contentShadow; int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Namespace) { Namespace namespace = (Namespace) object; if (prefix.equals(namespace.getPrefix())) { return namespace; } } } } else if (contentShadow instanceof Namespace) { Namespace namespace = (Namespace) contentShadow; if (prefix.equals(namespace.getPrefix())) { return namespace; } } } Element parent = getParent(); if (parent != null) { Namespace answer = parent.getNamespaceForPrefix(prefix); if (answer != null) { return answer; } } if ((prefix == null) || (prefix.length() <= 0)) { return Namespace.NO_NAMESPACE; } return null; } public Namespace getNamespaceForURI(String uri) { if ((uri == null) || (uri.length() <= 0)) { return Namespace.NO_NAMESPACE; } else if (uri.equals(getNamespaceURI())) { return getNamespace(); } else { final Object contentShadow = content; if (contentShadow instanceof List) { List list = (List) contentShadow; int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Namespace) { Namespace namespace = (Namespace) object; if (uri.equals(namespace.getURI())) { return namespace; } } } } else if (contentShadow instanceof Namespace) { Namespace namespace = (Namespace) contentShadow; if (uri.equals(namespace.getURI())) { return namespace; } } Element parent = getParent(); if (parent != null) { return parent.getNamespaceForURI(uri); } return null; } } public List declaredNamespaces() { BackedList answer = createResultList(); // if (getNamespaceURI().length() > 0) { // // answer.addLocal(getNamespace()); // // } final Object contentShadow = content; if (contentShadow instanceof List) { List list = (List) contentShadow; int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Namespace) { answer.addLocal(object); } } } else { if (contentShadow instanceof Namespace) { answer.addLocal(contentShadow); } } return answer; } public List additionalNamespaces() { final Object contentShadow = content; if (contentShadow instanceof List) { List list = (List) contentShadow; int size = list.size(); BackedList answer = createResultList(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Namespace) { Namespace namespace = (Namespace) object; if (!namespace.equals(getNamespace())) { answer.addLocal(namespace); } } } return answer; } else { if (contentShadow instanceof Namespace) { Namespace namespace = (Namespace) contentShadow; if (namespace.equals(getNamespace())) { return createEmptyList(); } return createSingleResultList(namespace); } else { return createEmptyList(); } } } public List additionalNamespaces(String defaultNamespaceURI) { final Object contentShadow = content; if (contentShadow instanceof List) { List list = (List) contentShadow; BackedList answer = createResultList(); int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Namespace) { Namespace namespace = (Namespace) object; if (!defaultNamespaceURI.equals(namespace.getURI())) { answer.addLocal(namespace); } } } return answer; } else { if (contentShadow instanceof Namespace) { Namespace namespace = (Namespace) contentShadow; if (!defaultNamespaceURI.equals(namespace.getURI())) { return createSingleResultList(namespace); } } } return createEmptyList(); } // Processing instruction API public List processingInstructions() { final Object contentShadow = content; if (contentShadow instanceof List) { List list = (List) contentShadow; BackedList answer = createResultList(); int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof ProcessingInstruction) { answer.addLocal(object); } } return answer; } else { if (contentShadow instanceof ProcessingInstruction) { return createSingleResultList(contentShadow); } return createEmptyList(); } } public List processingInstructions(String target) { final Object shadow = content; if (shadow instanceof List) { List list = (List) shadow; BackedList answer = createResultList(); int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof ProcessingInstruction) { ProcessingInstruction pi = (ProcessingInstruction) object; if (target.equals(pi.getName())) { answer.addLocal(pi); } } } return answer; } else { if (shadow instanceof ProcessingInstruction) { ProcessingInstruction pi = (ProcessingInstruction) shadow; if (target.equals(pi.getName())) { return createSingleResultList(pi); } } return createEmptyList(); } } public ProcessingInstruction processingInstruction(String target) { final Object shadow = content; if (shadow instanceof List) { List list = (List) shadow; int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof ProcessingInstruction) { ProcessingInstruction pi = (ProcessingInstruction) object; if (target.equals(pi.getName())) { return pi; } } } } else { if (shadow instanceof ProcessingInstruction) { ProcessingInstruction pi = (ProcessingInstruction) shadow; if (target.equals(pi.getName())) { return pi; } } } return null; } public boolean removeProcessingInstruction(String target) { final Object shadow = content; if (shadow instanceof List) { List list = (List) shadow; for (Iterator iter = list.iterator(); iter.hasNext();) { Object object = iter.next(); if (object instanceof ProcessingInstruction) { ProcessingInstruction pi = (ProcessingInstruction) object; if (target.equals(pi.getName())) { iter.remove(); return true; } } } } else { if (shadow instanceof ProcessingInstruction) { ProcessingInstruction pi = (ProcessingInstruction) shadow; if (target.equals(pi.getName())) { this.content = null; return true; } } } return false; } public Element element(String name) { final Object contentShadow = content; if (contentShadow instanceof List) { List list = (List) contentShadow; int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Element) { Element element = (Element) object; if (name.equals(element.getName())) { return element; } } } } else { if (contentShadow instanceof Element) { Element element = (Element) contentShadow; if (name.equals(element.getName())) { return element; } } } return null; } public Element element(QName qName) { final Object contentShadow = content; if (contentShadow instanceof List) { List list = (List) contentShadow; int size = list.size(); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Element) { Element element = (Element) object; if (qName.equals(element.getQName())) { return element; } } } } else { if (contentShadow instanceof Element) { Element element = (Element) contentShadow; if (qName.equals(element.getQName())) { return element; } } } return null; } public Element element(String name, Namespace namespace) { return element(getDocumentFactory().createQName(name, namespace)); } public void setContent(List content) { contentRemoved(); if (content instanceof ContentListFacade) { content = ((ContentListFacade) content).getBackingList(); } if (content == null) { this.content = null; } else { int size = content.size(); List newContent = createContentList(size); for (int i = 0; i < size; i++) { Object object = content.get(i); if (object instanceof Node) { Node node = (Node) object; Element parent = node.getParent(); if ((parent != null) && (parent != this)) { node = (Node) node.clone(); } newContent.add(node); childAdded(node); } else if (object != null) { String text = object.toString(); Node node = getDocumentFactory().createText(text); newContent.add(node); childAdded(node); } } this.content = newContent; } } public void clearContent() { if (content != null) { contentRemoved(); content = null; } } public Node node(int index) { if (index >= 0) { final Object contentShadow = content; Object node; if (contentShadow instanceof List) { List list = (List) contentShadow; if (index >= list.size()) { return null; } node = list.get(index); } else { node = (index == 0) ? contentShadow : null; } if (node != null) { if (node instanceof Node) { return (Node) node; } else { return new DefaultText(node.toString()); } } } return null; } public int indexOf(Node node) { final Object contentShadow = content; if (contentShadow instanceof List) { List list = (List) contentShadow; return list.indexOf(node); } else { if ((contentShadow != null) && contentShadow.equals(node)) { return 0; } else { return -1; } } } public int nodeCount() { final Object contentShadow = content; if (contentShadow instanceof List) { List list = (List) contentShadow; return list.size(); } else { return (contentShadow != null) ? 1 : 0; } } public Iterator nodeIterator() { final Object contentShadow = content; if (contentShadow instanceof List) { List list = (List) contentShadow; return list.iterator(); } else { if (contentShadow != null) { return createSingleIterator(contentShadow); } else { return EMPTY_ITERATOR; } } } public List attributes() { return new ContentListFacade(this, attributeList()); } public void setAttributes(List attributes) { if (attributes instanceof ContentListFacade) { attributes = ((ContentListFacade) attributes).getBackingList(); } this.attributes = attributes; } public Iterator attributeIterator() { final Object attributesShadow = this.attributes; if (attributesShadow instanceof List) { List list = (List) attributesShadow; return list.iterator(); } else if (attributesShadow != null) { return createSingleIterator(attributesShadow); } else { return EMPTY_ITERATOR; } } public Attribute attribute(int index) { final Object attributesShadow = this.attributes; if (attributesShadow instanceof List) { List list = (List) attributesShadow; return (Attribute) list.get(index); } else if ((attributesShadow != null) && (index == 0)) { return (Attribute) attributesShadow; } else { return null; } } public int attributeCount() { final Object attributesShadow = this.attributes; if (attributesShadow instanceof List) { List list = (List) attributesShadow; return list.size(); } else { return (attributesShadow != null) ? 1 : 0; } } public Attribute attribute(String name) { final Object attributesShadow = this.attributes; if (attributesShadow instanceof List) { List list = (List) attributesShadow; int size = list.size(); for (int i = 0; i < size; i++) { Attribute attribute = (Attribute) list.get(i); if (name.equals(attribute.getName())) { return attribute; } } } else if (attributesShadow != null) { Attribute attribute = (Attribute) attributesShadow; if (name.equals(attribute.getName())) { return attribute; } } return null; } public Attribute attribute(QName qName) { final Object attributesShadow = this.attributes; if (attributesShadow instanceof List) { List list = (List) attributesShadow; int size = list.size(); for (int i = 0; i < size; i++) { Attribute attribute = (Attribute) list.get(i); if (qName.equals(attribute.getQName())) { return attribute; } } } else if (attributesShadow != null) { Attribute attribute = (Attribute) attributesShadow; if (qName.equals(attribute.getQName())) { return attribute; } } return null; } public Attribute attribute(String name, Namespace namespace) { return attribute(getDocumentFactory().createQName(name, namespace)); } public void add(Attribute attribute) { if (attribute.getParent() != null) { String message = "The Attribute already has an existing parent \"" + attribute.getParent().getQualifiedName() + "\""; throw new IllegalAddException(this, attribute, message); } if (attribute.getValue() == null) { // try remove a previous attribute with the same // name since adding an attribute with a null value // is equivalent to removing it. Attribute oldAttribute = attribute(attribute.getQName()); if (oldAttribute != null) { remove(oldAttribute); } } else { if (attributes == null) { attributes = attribute; } else { attributeList().add(attribute); } childAdded(attribute); } } public boolean remove(Attribute attribute) { boolean answer = false; final Object attributesShadow = this.attributes; if (attributesShadow instanceof List) { List list = (List) attributesShadow; answer = list.remove(attribute); if (!answer) { // we may have a copy of the attribute Attribute copy = attribute(attribute.getQName()); if (copy != null) { list.remove(copy); answer = true; } } } else if (attributesShadow != null) { if (attribute.equals(attributesShadow)) { this.attributes = null; answer = true; } else { // we may have a copy of the attribute Attribute other = (Attribute) attributesShadow; if (attribute.getQName().equals(other.getQName())) { attributes = null; answer = true; } } } if (answer) { childRemoved(attribute); } return answer; } // Implementation methods // ------------------------------------------------------------------------- protected void addNewNode(Node node) { final Object contentShadow = content; if (contentShadow == null) { this.content = node; } else { if (contentShadow instanceof List) { List list = (List) contentShadow; list.add(node); } else { List list = createContentList(); list.add(contentShadow); list.add(node); this.content = list; } } childAdded(node); } protected boolean removeNode(Node node) { boolean answer = false; final Object contentShadow = content; if (contentShadow != null) { if (contentShadow == node) { this.content = null; answer = true; } else if (contentShadow instanceof List) { List list = (List) contentShadow; answer = list.remove(node); } } if (answer) { childRemoved(node); } return answer; } protected List contentList() { final Object contentShadow = content; if (contentShadow instanceof List) { return (List) contentShadow; } else { List list = createContentList(); if (contentShadow != null) { list.add(contentShadow); } this.content = list; return list; } } protected List attributeList() { final Object attributesShadow = this.attributes; if (attributesShadow instanceof List) { return (List) attributesShadow; } else if (attributesShadow != null) { List list = createAttributeList(); list.add(attributesShadow); this.attributes = list; return list; } else { List list = createAttributeList(); this.attributes = list; return list; } } protected List attributeList(int size) { final Object attributesShadow = this.attributes; if (attributesShadow instanceof List) { return (List) attributesShadow; } else if (attributesShadow != null) { List list = createAttributeList(size); list.add(attributesShadow); this.attributes = list; return list; } else { List list = createAttributeList(size); this.attributes = list; return list; } } protected void setAttributeList(List attributeList) { this.attributes = attributeList; } protected DocumentFactory getDocumentFactory() { DocumentFactory factory = qname.getDocumentFactory(); return (factory != null) ? factory : DOCUMENT_FACTORY; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/ElementNameIterator.java0000644000175000017500000000632710242120003023076 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.util.Iterator; import org.dom4j.Element; /** *

* ElementNameIterator is a filtering {@link Iterator}which * filters out objects which do not implement the {@link Element}interface and * are not of the correct element name. *

* * @author James Strachan * @version $Revision: 1.11 $ * * @deprecated THIS CLASS WILL BE REMOVED IN dom4j-1.6 !! */ public class ElementNameIterator extends FilterIterator { private String name; public ElementNameIterator(Iterator proxy, String name) { super(proxy); this.name = name; } /** * DOCUMENT ME! * * @param object * DOCUMENT ME! * * @return true if the given element implements the {@link Element} * interface */ protected boolean matches(Object object) { if (object instanceof Element) { Element element = (Element) object; return name.equals(element.getName()); } return false; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/DefaultDocument.java0000644000175000017500000002560310242120017022260 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.DocumentType; import org.dom4j.Element; import org.dom4j.IllegalAddException; import org.dom4j.Node; import org.dom4j.ProcessingInstruction; import org.xml.sax.EntityResolver; /** *

* DefaultDocument is the default DOM4J default implementation of * an XML document. *

* * @author James Strachan * @version $Revision: 1.34 $ */ public class DefaultDocument extends AbstractDocument { protected static final List EMPTY_LIST = Collections.EMPTY_LIST; protected static final Iterator EMPTY_ITERATOR = EMPTY_LIST.iterator(); /** The name of the document */ private String name; /** The root element of this document */ private Element rootElement; /** * Store the contents of the document as a lazily created List */ private List content; /** The document type for this document */ private DocumentType docType; /** The document factory used by default */ private DocumentFactory documentFactory = DocumentFactory.getInstance(); /** The resolver of URIs */ private transient EntityResolver entityResolver; public DefaultDocument() { } public DefaultDocument(String name) { this.name = name; } public DefaultDocument(Element rootElement) { this.rootElement = rootElement; } public DefaultDocument(DocumentType docType) { this.docType = docType; } public DefaultDocument(Element rootElement, DocumentType docType) { this.rootElement = rootElement; this.docType = docType; } public DefaultDocument(String name, Element rootElement, DocumentType docType) { this.name = name; this.rootElement = rootElement; this.docType = docType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Element getRootElement() { return rootElement; } public DocumentType getDocType() { return docType; } public void setDocType(DocumentType docType) { this.docType = docType; } public Document addDocType(String docTypeName, String publicId, String systemId) { setDocType(getDocumentFactory().createDocType(docTypeName, publicId, systemId)); return this; } public String getXMLEncoding() { return encoding; } public EntityResolver getEntityResolver() { return entityResolver; } public void setEntityResolver(EntityResolver entityResolver) { this.entityResolver = entityResolver; } public Object clone() { DefaultDocument document = (DefaultDocument) super.clone(); document.rootElement = null; document.content = null; document.appendContent(this); return document; } public List processingInstructions() { List source = contentList(); List answer = createResultList(); int size = source.size(); for (int i = 0; i < size; i++) { Object object = source.get(i); if (object instanceof ProcessingInstruction) { answer.add(object); } } return answer; } public List processingInstructions(String target) { List source = contentList(); List answer = createResultList(); int size = source.size(); for (int i = 0; i < size; i++) { Object object = source.get(i); if (object instanceof ProcessingInstruction) { ProcessingInstruction pi = (ProcessingInstruction) object; if (target.equals(pi.getName())) { answer.add(pi); } } } return answer; } public ProcessingInstruction processingInstruction(String target) { List source = contentList(); int size = source.size(); for (int i = 0; i < size; i++) { Object object = source.get(i); if (object instanceof ProcessingInstruction) { ProcessingInstruction pi = (ProcessingInstruction) object; if (target.equals(pi.getName())) { return pi; } } } return null; } public boolean removeProcessingInstruction(String target) { List source = contentList(); for (Iterator iter = source.iterator(); iter.hasNext();) { Object object = iter.next(); if (object instanceof ProcessingInstruction) { ProcessingInstruction pi = (ProcessingInstruction) object; if (target.equals(pi.getName())) { iter.remove(); return true; } } } return false; } public void setContent(List content) { rootElement = null; contentRemoved(); if (content instanceof ContentListFacade) { content = ((ContentListFacade) content).getBackingList(); } if (content == null) { this.content = null; } else { int size = content.size(); List newContent = createContentList(size); for (int i = 0; i < size; i++) { Object object = content.get(i); if (object instanceof Node) { Node node = (Node) object; Document doc = node.getDocument(); if ((doc != null) && (doc != this)) { node = (Node) node.clone(); } if (node instanceof Element) { if (rootElement == null) { rootElement = (Element) node; } else { throw new IllegalAddException( "A document may only " + "contain one root " + "element: " + content); } } newContent.add(node); childAdded(node); } } this.content = newContent; } } public void clearContent() { contentRemoved(); content = null; rootElement = null; } public void setDocumentFactory(DocumentFactory documentFactory) { this.documentFactory = documentFactory; } // Implementation methods // ------------------------------------------------------------------------- protected List contentList() { if (content == null) { content = createContentList(); if (rootElement != null) { content.add(rootElement); } } return content; } protected void addNode(Node node) { if (node != null) { Document document = node.getDocument(); if ((document != null) && (document != this)) { // XXX: could clone here String message = "The Node already has an existing document: " + document; throw new IllegalAddException(this, node, message); } contentList().add(node); childAdded(node); } } protected void addNode(int index, Node node) { if (node != null) { Document document = node.getDocument(); if ((document != null) && (document != this)) { // XXX: could clone here String message = "The Node already has an existing document: " + document; throw new IllegalAddException(this, node, message); } contentList().add(index, node); childAdded(node); } } protected boolean removeNode(Node node) { if (node == rootElement) { rootElement = null; } if (contentList().remove(node)) { childRemoved(node); return true; } return false; } protected void rootElementAdded(Element element) { this.rootElement = element; element.setDocument(this); } protected DocumentFactory getDocumentFactory() { return documentFactory; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/tree/package.html0000644000175000017500000000040510242120006020602 0ustar ebourgebourg

Contains the default implementations of the dom4j Document Object Model together with some helpful base classes for those wishing to implement their own document object model.

dom4j-1.6.1/src/java/org/dom4j/swing/0000755000175000017500000000000012133227266016533 5ustar ebourgebourgdom4j-1.6.1/src/java/org/dom4j/swing/XMLTableModel.java0000644000175000017500000001442110242120010021743 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.swing; import java.util.List; import javax.swing.table.AbstractTableModel; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.XPath; /** *

* XMLTableDefinition repro. *

* * @author James Strachan * @version $Revision: 1.8 $ */ public class XMLTableModel extends AbstractTableModel { /** Holds value of property definition. */ private XMLTableDefinition definition; /** Holds value of property source. */ private Object source; /** The rows evaluated from the row XPath expression */ private List rows; /** * Creates a TableModel from an XML table definition document and an XML * source * * @param tableDefinition * DOCUMENT ME! * @param source * DOCUMENT ME! */ public XMLTableModel(Element tableDefinition, Object source) { this(XMLTableDefinition.load(tableDefinition), source); } /** * Creates a TableModel from an XML table definition document and an XML * source * * @param tableDefinition * DOCUMENT ME! * @param source * DOCUMENT ME! */ public XMLTableModel(Document tableDefinition, Object source) { this(XMLTableDefinition.load(tableDefinition), source); } public XMLTableModel(XMLTableDefinition definition, Object source) { this.definition = definition; this.source = source; } public Object getRowValue(int rowIndex) { return getRows().get(rowIndex); } public List getRows() { if (rows == null) { rows = definition.getRowXPath().selectNodes(source); } return rows; } // TableModel interface // ------------------------------------------------------------------------- public Class getColumnClass(int columnIndex) { return definition.getColumnClass(columnIndex); } public int getColumnCount() { return definition.getColumnCount(); } public String getColumnName(int columnIndex) { XPath xpath = definition.getColumnNameXPath(columnIndex); if (xpath != null) { System.out.println("Evaluating column xpath: " + xpath + " value: " + xpath.valueOf(source)); return xpath.valueOf(source); } return definition.getColumnName(columnIndex); } public Object getValueAt(int rowIndex, int columnIndex) { try { Object row = getRowValue(rowIndex); return definition.getValueAt(row, columnIndex); } catch (Exception e) { handleException(e); return null; } } public int getRowCount() { return getRows().size(); } // Properties // ------------------------------------------------------------------------- /** * Getter for property definition. * * @return Value of property definition. */ public XMLTableDefinition getDefinition() { return definition; } /** * Setter for property definition. * * @param definition * New value of property definition. */ public void setDefinition(XMLTableDefinition definition) { this.definition = definition; } /** * Getter for the XML source, which is usually a Node or List of nodes. * * @return Value of property source. */ public Object getSource() { return source; } /** * Setter for the XML source, which is usually a Node or List of nodes. * * @param source * New value of property source. */ public void setSource(Object source) { this.source = source; this.rows = null; } // Implementation methods // ------------------------------------------------------------------------- protected void handleException(Exception e) { // #### should use jakarta commons-logging System.out.println("Caught: " + e); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/swing/DocumentTreeModel.java0000644000175000017500000000656310242120004022744 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.swing; import javax.swing.tree.DefaultTreeModel; import org.dom4j.Document; /** *

* DocumentTreeModel implements a Swing TreeModel for a dom4j XML * Document. *

* * @author James Strachan * @author Jakob Jenkov * @version $Revision: 1.7 $ */ public class DocumentTreeModel extends DefaultTreeModel { /** The document for this model */ protected Document document; public DocumentTreeModel(Document document) { super(new BranchTreeNode(document)); this.document = document; } // Properties // ------------------------------------------------------------------------- /** * DOCUMENT ME! * * @return the Document instance that this * TreeModel is based on */ public Document getDocument() { return document; } /** * Sets the Document instance that this * TreeModel is based on * * @param document * DOCUMENT ME! */ public void setDocument(Document document) { this.document = document; setRoot(new BranchTreeNode(document)); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/swing/XMLTableDefinition.java0000644000175000017500000002377010242120013023005 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.swing; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.XPath; import org.jaxen.VariableContext; /** *

* XMLTableDefinition represents a table definition based on * XPath expression evaluated on an XML document. *

* * @author James Strachan * @version $Revision: 1.8 $ */ public class XMLTableDefinition implements Serializable, VariableContext { /** Holds value of property rowXPath. */ private XPath rowXPath; /** The columns to display in this table */ private List columns = new ArrayList(); /** integer index array cache */ private XMLTableColumnDefinition[] columnArray; /** name index cache */ private Map columnNameIndex; /** for cross-row variables */ private VariableContext variableContext; /** stores the current row value for the variableContext */ private Object rowValue; public XMLTableDefinition() { } /** * Loads an XML table definition from an XML definition document * * @param definition * DOCUMENT ME! * * @return DOCUMENT ME! */ public static XMLTableDefinition load(Document definition) { return load(definition.getRootElement()); } /** * Loads an XML table definition from an XML definition document * * @param definition * DOCUMENT ME! * * @return DOCUMENT ME! */ public static XMLTableDefinition load(Element definition) { XMLTableDefinition answer = new XMLTableDefinition(); answer.setRowExpression(definition.attributeValue("select")); for (Iterator iter = definition.elementIterator("column"); iter .hasNext();) { Element element = (Element) iter.next(); String expression = element.attributeValue("select"); String name = element.getText(); String typeName = element.attributeValue("type", "string"); String columnXPath = element.attributeValue("columnNameXPath"); int type = XMLTableColumnDefinition.parseType(typeName); if (columnXPath != null) { answer.addColumnWithXPathName(columnXPath, expression, type); } else { answer.addColumn(name, expression, type); } } return answer; } public Class getColumnClass(int columnIndex) { return getColumn(columnIndex).getColumnClass(); } public int getColumnCount() { return columns.size(); } /** * DOCUMENT ME! * * @param columnIndex * DOCUMENT ME! * * @return the static column name. This is used if there is no * columnNameXPath */ public String getColumnName(int columnIndex) { return getColumn(columnIndex).getName(); } /** * DOCUMENT ME! * * @param columnIndex * DOCUMENT ME! * * @return the XPath expression used to evaluate the value of cells in this * column */ public XPath getColumnXPath(int columnIndex) { return getColumn(columnIndex).getXPath(); } /** * DOCUMENT ME! * * @param columnIndex * DOCUMENT ME! * * @return the XPath expresssion used to create the column name, if there is * one or null if there is no XPath expression to name the column. */ public XPath getColumnNameXPath(int columnIndex) { return getColumn(columnIndex).getColumnNameXPath(); } public synchronized Object getValueAt(Object row, int columnIndex) { XMLTableColumnDefinition column = getColumn(columnIndex); Object answer = null; synchronized (this) { this.rowValue = row; answer = column.getValue(row); this.rowValue = null; } return answer; } public void addColumn(String name, String expression) { addColumn(name, expression, XMLTableColumnDefinition.OBJECT_TYPE); } public void addColumn(String name, String expression, int type) { XPath xpath = createColumnXPath(expression); addColumn(new XMLTableColumnDefinition(name, xpath, type)); } public void addColumnWithXPathName(String columnNameXPathExpression, String expression, int type) { XPath columnNameXPath = createColumnXPath(columnNameXPathExpression); XPath xpath = createColumnXPath(expression); addColumn(new XMLTableColumnDefinition(columnNameXPath, xpath, type)); } public void addStringColumn(String name, String expression) { addColumn(name, expression, XMLTableColumnDefinition.STRING_TYPE); } public void addNumberColumn(String name, String expression) { addColumn(name, expression, XMLTableColumnDefinition.NUMBER_TYPE); } public void addColumn(XMLTableColumnDefinition column) { clearCaches(); columns.add(column); } public void removeColumn(XMLTableColumnDefinition column) { clearCaches(); columns.remove(column); } public void clear() { clearCaches(); columns.clear(); } public XMLTableColumnDefinition getColumn(int index) { if (columnArray == null) { columnArray = new XMLTableColumnDefinition[columns.size()]; columns.toArray(columnArray); } return columnArray[index]; } public XMLTableColumnDefinition getColumn(String columnName) { if (columnNameIndex == null) { columnNameIndex = new HashMap(); for (Iterator it = columns.iterator(); it.hasNext();) { XMLTableColumnDefinition column = (XMLTableColumnDefinition) it .next(); columnNameIndex.put(column.getName(), column); } } return (XMLTableColumnDefinition) columnNameIndex.get(columnName); } /** * Getter for property rowXPath. * * @return Value of property rowXPath. */ public XPath getRowXPath() { return rowXPath; } /** * Setter for property rowXPath. * * @param rowXPath * New value of property rowXPath. */ public void setRowXPath(XPath rowXPath) { this.rowXPath = rowXPath; } public void setRowExpression(String xpath) { setRowXPath(createXPath(xpath)); } // VariableContext interface // ------------------------------------------------------------------------- public Object getVariableValue(String namespaceURI, String prefix, String localName) { XMLTableColumnDefinition column = getColumn(localName); if (column != null) { return column.getValue(rowValue); } return null; } // Implementation methods // ------------------------------------------------------------------------- protected XPath createXPath(String expression) { return DocumentHelper.createXPath(expression); } protected XPath createColumnXPath(String expression) { XPath xpath = createXPath(expression); // associate my variable context xpath.setVariableContext(this); return xpath; } protected void clearCaches() { columnArray = null; columnNameIndex = null; } protected void handleException(Exception e) { // #### should use jakarta commons-logging System.out.println("Caught: " + e); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/swing/XMLTableColumnDefinition.java0000644000175000017500000001535710242120011024163 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.swing; import java.io.Serializable; import org.dom4j.DocumentHelper; import org.dom4j.Node; import org.dom4j.XPath; /** *

* XMLTableColumnDefinition a column within a table definition. *

* * @author James Strachan * @version $Revision: 1.10 $ */ public class XMLTableColumnDefinition implements Serializable { public static final int OBJECT_TYPE = 0; public static final int STRING_TYPE = 1; public static final int NUMBER_TYPE = 2; public static final int NODE_TYPE = 3; /** Holds value of property type. */ private int type; /** Holds value of property name. */ private String name; /** Holds value of property xpath. */ private XPath xpath; /** Holds the XPath used for the column name */ private XPath columnNameXPath; public XMLTableColumnDefinition() { } public XMLTableColumnDefinition(String name, String expression, int type) { this.name = name; this.type = type; this.xpath = createXPath(expression); } public XMLTableColumnDefinition(String name, XPath xpath, int type) { this.name = name; this.xpath = xpath; this.type = type; } public XMLTableColumnDefinition(XPath columnXPath, XPath xpath, int type) { this.xpath = xpath; this.columnNameXPath = columnXPath; this.type = type; } public static int parseType(String typeName) { if ((typeName != null) && (typeName.length() > 0)) { if (typeName.equals("string")) { return STRING_TYPE; } else if (typeName.equals("number")) { return NUMBER_TYPE; } else if (typeName.equals("node")) { return NODE_TYPE; } } return OBJECT_TYPE; } public Class getColumnClass() { switch (type) { case STRING_TYPE: return String.class; case NUMBER_TYPE: return Number.class; case NODE_TYPE: return Node.class; default: return Object.class; } } public Object getValue(Object row) { switch (type) { case STRING_TYPE: return xpath.valueOf(row); case NUMBER_TYPE: return xpath.numberValueOf(row); case NODE_TYPE: return xpath.selectSingleNode(row); default: return xpath.evaluate(row); } } // Properties // ------------------------------------------------------------------------- /** * Getter for property type. * * @return Value of property type. */ public int getType() { return type; } /** * Setter for property type. * * @param type * New value of property type. */ public void setType(int type) { this.type = type; } /** * Getter for property name. * * @return Value of property name. */ public String getName() { return name; } /** * Setter for property name. * * @param name * New value of property name. */ public void setName(String name) { this.name = name; } /** * Getter for property xpath. * * @return Value of property xpath. */ public XPath getXPath() { return xpath; } /** * Setter for property xpath. * * @param xPath * New value of property xpath. */ public void setXPath(XPath xPath) { this.xpath = xPath; } /** * DOCUMENT ME! * * @return the XPath used to create the column name */ public XPath getColumnNameXPath() { return columnNameXPath; } /** * Setter for property columnNameXPath. * * @param columnNameXPath * New value of property xpath. */ public void setColumnNameXPath(XPath columnNameXPath) { this.columnNameXPath = columnNameXPath; } // Implementation methods // ------------------------------------------------------------------------- protected XPath createXPath(String expression) { return DocumentHelper.createXPath(expression); } protected void handleException(Exception e) { // #### should use jakarta commons-logging System.out.println("Caught: " + e); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/swing/BranchTreeNode.java0000644000175000017500000001367110242120016022211 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.swing; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import javax.swing.tree.TreeNode; import org.dom4j.Branch; import org.dom4j.CharacterData; import org.dom4j.Node; /** *

* BranchTreeNode implements the Swing TreeNode interface to bind * dom4j XML Branch nodes (i.e. Document and Element nodes) to a Swing * TreeModel. *

* * @author James Strachan * @author Jakob Jenkov * @version $Revision: 1.10 $ */ public class BranchTreeNode extends LeafTreeNode { /** Stores the child tree nodes */ protected List children; public BranchTreeNode() { } public BranchTreeNode(Branch xmlNode) { super(xmlNode); } public BranchTreeNode(TreeNode parent, Branch xmlNode) { super(parent, xmlNode); } // TreeNode methods // ------------------------------------------------------------------------- public Enumeration children() { return new Enumeration() { private int index = -1; public boolean hasMoreElements() { return (index + 1) < getChildCount(); } public Object nextElement() { return getChildAt(++index); } }; } public boolean getAllowsChildren() { return true; } public TreeNode getChildAt(int childIndex) { return (TreeNode) getChildList().get(childIndex); } public int getChildCount() { return getChildList().size(); } public int getIndex(TreeNode node) { return getChildList().indexOf(node); } public boolean isLeaf() { return getXmlBranch().nodeCount() <= 0; } public String toString() { return xmlNode.getName(); } // Implementation methods // ------------------------------------------------------------------------- /** * Uses Lazy Initialization pattern to create a List of children * * @return DOCUMENT ME! */ protected List getChildList() { // for now lets just create the children once, the first time they // are asked for. // XXXX - we may wish to detect inconsistencies here.... if (children == null) { children = createChildList(); } return children; } /** * Factory method to create List of children TreeNodes * * @return DOCUMENT ME! */ protected List createChildList() { // add attributes and content as children? Branch branch = getXmlBranch(); int size = branch.nodeCount(); List childList = new ArrayList(size); for (int i = 0; i < size; i++) { Node node = branch.node(i); // ignore whitespace text nodes if (node instanceof CharacterData) { String text = node.getText(); if (text == null) { continue; } text = text.trim(); if (text.length() <= 0) { continue; } } childList.add(createChildTreeNode(node)); } return childList; } /** * Factory method to create child tree nodes for a given XML node type * * @param xmlNode * DOCUMENT ME! * * @return DOCUMENT ME! */ protected TreeNode createChildTreeNode(Node xmlNode) { if (xmlNode instanceof Branch) { return new BranchTreeNode(this, (Branch) xmlNode); } else { return new LeafTreeNode(this, xmlNode); } } protected Branch getXmlBranch() { return (Branch) xmlNode; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/swing/LeafTreeNode.java0000644000175000017500000001060310242120020021646 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.swing; import java.util.Enumeration; import javax.swing.tree.TreeNode; import org.dom4j.Node; /** *

* LeafTreeNode implements the Swing TreeNode interface to bind a * leaf XML nodes to a Swing TreeModel. *

* * @author James Strachan * @author Jakob Jenkov * @version $Revision: 1.7 $ */ public class LeafTreeNode implements TreeNode { protected static final Enumeration EMPTY_ENUMERATION = new Enumeration() { public boolean hasMoreElements() { return false; } public Object nextElement() { return null; } }; /** The parent node of this TreeNode */ private TreeNode parent; /** The dom4j Node which contains the */ protected Node xmlNode; public LeafTreeNode() { } public LeafTreeNode(Node xmlNode) { this.xmlNode = xmlNode; } public LeafTreeNode(TreeNode parent, Node xmlNode) { this.parent = parent; this.xmlNode = xmlNode; } // TreeNode methods // ------------------------------------------------------------------------- public Enumeration children() { return EMPTY_ENUMERATION; } public boolean getAllowsChildren() { return false; } public TreeNode getChildAt(int childIndex) { return null; } public int getChildCount() { return 0; } public int getIndex(TreeNode node) { return -1; } public TreeNode getParent() { return parent; } public boolean isLeaf() { return true; } public String toString() { // should maybe do things differently based on content? String text = xmlNode.getText(); return (text != null) ? text.trim() : ""; } // Properties // ------------------------------------------------------------------------- /** * Sets the parent of this node but doesn't change the parents children * * @param parent * DOCUMENT ME! */ public void setParent(LeafTreeNode parent) { this.parent = parent; } public Node getXmlNode() { return xmlNode; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/swing/package.html0000644000175000017500000000030310242120001020762 0ustar ebourgebourg

A collection of adapters to allow easy integration with dom4j XML documents and Swing such as TreeModels and TableModels.

dom4j-1.6.1/src/java/org/dom4j/Branch.java0000644000175000017500000003060110242120011017417 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import java.util.Iterator; import java.util.List; /** *

* Branch interface defines the common behaviour for Nodes which * can contain child nodes (content) such as XML elements and documents. This * interface allows both elements and documents to be treated in a polymorphic * manner when changing or navigating child nodes (content). *

* * @author James Strachan * @version $Revision: 1.32 $ */ public interface Branch extends Node { /** * Returns the Node at the specified index position. * * @param index * the index of the node to return. * * @return the Node at the specified position. * * @throws IndexOutOfBoundsException * if the index is out of range (index < 0 || index >= * {@link Branch#nodeCount()}). */ Node node(int index) throws IndexOutOfBoundsException; /** * Returns the index of the given node if it is a child node of this branch * or -1 if the given node is not a child node. * * @param node * the content child node to find. * * @return the index of the given node starting at 0 or -1 if the node is * not a child node of this branch */ int indexOf(Node node); /** * Returns the number of Node instances that this branch * contains. * * @return the number of nodes this branch contains */ int nodeCount(); /** * Returns the element of the given ID attribute value. If this tree is * capable of understanding which attribute value should be used for the ID * then it should be used, otherwise this method should return null. * * @param elementID * DOCUMENT ME! * * @return DOCUMENT ME! */ Element elementByID(String elementID); /** *

* Returns the content nodes of this branch as a backed {@link List}so that * the content of this branch may be modified directly using the * {@link List}interface. The List is backed by the * Branch so that changes to the list are reflected in the * branch and vice versa. *

* * @return the nodes that this branch contains as a List */ List content(); /** * Returns an iterator through the content nodes of this branch * * @return an iterator through the content nodes of this branch */ Iterator nodeIterator(); /** * Sets the contents of this branch as a List of * Node instances. * * @param content * is the list of nodes to use as the content for this branch. */ void setContent(List content); /** * Appends the content of the given branch to this branch instance. This * method behaves like the {@link * java.util.Collection#addAll(java.util.Collection)} method. * * @param branch * is the branch whose content will be added to me. */ void appendContent(Branch branch); /** * Clears the content for this branch, removing any Node * instances this branch may contain. */ void clearContent(); /** *

* Returns a list of all the processing instructions in this branch. The * list is backed by this branch so that changes to the list will be * reflected in the branch but the reverse is not the case. *

* * @return a backed list of the processing instructions */ List processingInstructions(); /** *

* Returns a list of the processing instructions for the given target. The * list is backed by this branch so that changes to the list will be * reflected in the branch but the reverse is not the case. *

* * @param target * DOCUMENT ME! * * @return a backed list of the processing instructions */ List processingInstructions(String target); /** * DOCUMENT ME! * * @param target * DOCUMENT ME! * * @return the processing instruction for the given target */ ProcessingInstruction processingInstruction(String target); /** * Sets all the processing instructions for this branch * * @param listOfPIs * DOCUMENT ME! */ void setProcessingInstructions(List listOfPIs); /** * Adds a new Element node with the given name to this branch * and returns a reference to the new node. * * @param name * is the name for the Element node. * * @return the newly added Element node. */ Element addElement(String name); /** * Adds a new Element node with the given {@link QName}to * this branch and returns a reference to the new node. * * @param qname * is the qualified name for the Element node. * * @return the newly added Element node. */ Element addElement(QName qname); /** * Adds a new Element node with the given qualified name and * namespace URI to this branch and returns a reference to the new node. * * @param qualifiedName * is the fully qualified name of the Element * @param namespaceURI * is the URI of the namespace to use * * @return the newly added Element node. */ Element addElement(String qualifiedName, String namespaceURI); /** * Removes the processing instruction for the given target if it exists * * @param target * DOCUMENT ME! * * @return true if a processing instruction was removed else false */ boolean removeProcessingInstruction(String target); /** * Adds the given Node or throws {@link IllegalAddException} * if the given node is not of a valid type. This is a polymorphic method * which will call the typesafe method for the node type such as * add(Element) or add(Comment). * * @param node * is the given node to add */ void add(Node node); /** * Adds the given Comment to this branch. If the given node * already has a parent defined then an IllegalAddException * will be thrown. * * @param comment * is the comment to be added */ void add(Comment comment); /** * Adds the given Element to this branch. If the given node * already has a parent defined then an IllegalAddException * will be thrown. * * @param element * is the element to be added */ void add(Element element); /** * Adds the given ProcessingInstruction to this branch. If * the given node already has a parent defined then an * IllegalAddException will be thrown. * * @param pi * is the processing instruction to be added */ void add(ProcessingInstruction pi); /** * Removes the given Node if the node is an immediate child * of this branch. If the given node is not an immediate child of this * branch then the {@link Node#detach()}method should be used instead. This * is a polymorphic method which will call the typesafe method for the node * type such as remove(Element) or remove(Comment). * * @param node * is the given node to be removed * * @return true if the node was removed */ boolean remove(Node node); /** * Removes the given Comment if the node is an immediate * child of this branch. If the given node is not an immediate child of this * branch then the {@link Node#detach()}method should be used instead. * * @param comment * is the comment to be removed * * @return true if the comment was removed */ boolean remove(Comment comment); /** * Removes the given Element if the node is an immediate * child of this branch. If the given node is not an immediate child of this * branch then the {@link Node#detach()}method should be used instead. * * @param element * is the element to be removed * * @return true if the element was removed */ boolean remove(Element element); /** * Removes the given ProcessingInstruction if the node is an * immediate child of this branch. If the given node is not an immediate * child of this branch then the {@link Node#detach()}method should be used * instead. * * @param pi * is the processing instruction to be removed * * @return true if the processing instruction was removed */ boolean remove(ProcessingInstruction pi); /** * Puts all Text nodes in the full depth of the sub-tree * underneath this Node, including attribute nodes, into a * "normal" form where only structure (e.g., elements, comments, processing * instructions, CDATA sections, and entity references) separates * Text nodes, i.e., there are neither adjacent * Text nodes nor empty Text nodes. This can * be used to ensure that the DOM view of a document is the same as if it * were saved and re-loaded, and is useful when operations (such as XPointer * lookups) that depend on a particular document tree structure are to be * used.In cases where the document contains CDATASections, * the normalize operation alone may not be sufficient, since XPointers do * not differentiate between Text nodes and * CDATASection nodes. * * @since DOM Level 2 */ void normalize(); } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/xpp/0000755000175000017500000000000012133227266016213 5ustar ebourgebourgdom4j-1.6.1/src/java/org/dom4j/xpp/ProxyXmlStartTag.java0000644000175000017500000002376410242120017022327 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpp; import java.util.ArrayList; import java.util.Iterator; import org.dom4j.Attribute; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.QName; import org.dom4j.tree.AbstractElement; import org.gjt.xpp.XmlPullParserException; import org.gjt.xpp.XmlStartTag; /** * ProxyXmlStartTag implements the XPP XmlSmartTag * interface while creating a dom4j Element underneath. * * @author James Strachan * @author Maarten Coene * @author Wolfgang Baer */ public class ProxyXmlStartTag implements XmlStartTag { /** The element being constructed */ private Element element; /** The factory used to create new elements */ private DocumentFactory factory = DocumentFactory.getInstance(); public ProxyXmlStartTag() { } public ProxyXmlStartTag(Element element) { this.element = element; } // XmlStartTag interface // ------------------------------------------------------------------------- public void resetStartTag() { this.element = null; } public int getAttributeCount() { return (element != null) ? element.attributeCount() : 0; } public String getAttributeNamespaceUri(int index) { if (element != null) { Attribute attribute = element.attribute(index); if (attribute != null) { return attribute.getNamespaceURI(); } } return null; } public String getAttributeLocalName(int index) { if (element != null) { Attribute attribute = element.attribute(index); if (attribute != null) { return attribute.getName(); } } return null; } public String getAttributePrefix(int index) { if (element != null) { Attribute attribute = element.attribute(index); if (attribute != null) { String prefix = attribute.getNamespacePrefix(); if ((prefix != null) && (prefix.length() > 0)) { return prefix; } } } return null; } public String getAttributeRawName(int index) { if (element != null) { Attribute attribute = element.attribute(index); if (attribute != null) { return attribute.getQualifiedName(); } } return null; } public String getAttributeValue(int index) { if (element != null) { Attribute attribute = element.attribute(index); if (attribute != null) { return attribute.getValue(); } } return null; } public String getAttributeValueFromRawName(String rawName) { if (element != null) { for (Iterator iter = element.attributeIterator(); iter.hasNext();) { Attribute attribute = (Attribute) iter.next(); if (rawName.equals(attribute.getQualifiedName())) { return attribute.getValue(); } } } return null; } public String getAttributeValueFromName(String namespaceURI, String localName) { if (element != null) { for (Iterator iter = element.attributeIterator(); iter.hasNext();) { Attribute attribute = (Attribute) iter.next(); if (namespaceURI.equals(attribute.getNamespaceURI()) && localName.equals(attribute.getName())) { return attribute.getValue(); } } } return null; } public boolean isAttributeNamespaceDeclaration(int index) { if (element != null) { Attribute attribute = element.attribute(index); if (attribute != null) { return "xmlns".equals(attribute.getNamespacePrefix()); } } return false; } /** * parameters modeled after SAX2 attribute approach * * @param namespaceURI DOCUMENT ME! * @param localName DOCUMENT ME! * @param rawName DOCUMENT ME! * @param value DOCUMENT ME! * * @throws XmlPullParserException DOCUMENT ME! */ public void addAttribute(String namespaceURI, String localName, String rawName, String value) throws XmlPullParserException { QName qname = QName.get(rawName, namespaceURI); element.addAttribute(qname, value); } public void addAttribute(String namespaceURI, String localName, String rawName, String value, boolean isNamespaceDeclaration) throws XmlPullParserException { if (isNamespaceDeclaration) { String prefix = ""; int idx = rawName.indexOf(':'); if (idx > 0) { prefix = rawName.substring(0, idx); } element.addNamespace(prefix, namespaceURI); } else { QName qname = QName.get(rawName, namespaceURI); element.addAttribute(qname, value); } } public void ensureAttributesCapacity(int minCapacity) throws XmlPullParserException { if (element instanceof AbstractElement) { AbstractElement elementImpl = (AbstractElement) element; elementImpl.ensureAttributesCapacity(minCapacity); } } /** * Remove all atributes. * * @deprecated Use {@link #removeAttributes()} instead. */ public void removeAtttributes() throws XmlPullParserException { removeAttributes(); } public void removeAttributes() throws XmlPullParserException { if (element != null) { element.setAttributes(new ArrayList()); // ##### FIXME // adding this method would be nice... // element.clearAttributes(); } } public String getLocalName() { return element.getName(); } public String getNamespaceUri() { return element.getNamespaceURI(); } public String getPrefix() { return element.getNamespacePrefix(); } public String getRawName() { return element.getQualifiedName(); } public void modifyTag(String namespaceURI, String lName, String rawName) { this.element = factory.createElement(rawName, namespaceURI); } public void resetTag() { this.element = null; } public boolean removeAttributeByName(String namespaceURI, String localName) throws XmlPullParserException { if (element != null) { QName qname = QName.get(localName, namespaceURI); Attribute attribute = element.attribute(qname); return element.remove(attribute); } return false; } public boolean removeAttributeByRawName(String rawName) throws XmlPullParserException { if (element != null) { Attribute attribute = null; Iterator it = element.attributeIterator(); while (it.hasNext()) { Attribute current = (Attribute) it.next(); if (current.getQualifiedName().equals(rawName)) { attribute = current; break; } } return element.remove(attribute); } return false; } // Properties // ------------------------------------------------------------------------- public DocumentFactory getDocumentFactory() { return factory; } public void setDocumentFactory(DocumentFactory documentFactory) { this.factory = documentFactory; } public Element getElement() { return element; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/xpp/package.html0000644000175000017500000000040310242120010020443 0ustar ebourgebourg org.dom4j.xpp :: package.html

Provides implementation classes to cleanly integrate dom4j with the XML Pull Parser XPP

dom4j-1.6.1/src/java/org/dom4j/ElementPath.java0000644000175000017500000001004610242120000020427 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; /** * This interface is used by {@link ElementHandler}instances to retrieve * information about the current path hierarchy they are to process. It's * primary use is to retrieve the current {@link Element}being processed. * * @author Dave White * @version $Revision: 1.6 $ */ public interface ElementPath { /** * DOCUMENT ME! * * @return the number of elements in the path */ int size(); /** * DOCUMENT ME! * * @param depth * DOCUMENT ME! * * @return the element at the specified depth index, 0 = root element */ Element getElement(int depth); /** * DOCUMENT ME! * * @return the path as a string */ String getPath(); /** * DOCUMENT ME! * * @return the current element */ Element getCurrent(); /** * Adds the ElementHandler to be called when the specified * path is encounted. The path can be either an absolute path (i.e. prefixed * with "/") or a relative path (i.e. assummed to be a child of the current * path as retrieved by getPath . * * @param path * is the path to be handled * @param handler * is the ElementHandler to be called by the event * based processor. */ void addHandler(String path, ElementHandler handler); /** * Removes the ElementHandler from the event based processor, * for the specified path. The path can be either an absolute path (i.e. * prefixed with "/") or a relative path (i.e. assummed to be a child of the * current path as retrieved by getPath . * * @param path * is the path to remove the ElementHandler for. */ void removeHandler(String path); } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/InvalidXPathException.java0000644000175000017500000000563010242120025022445 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; /** *

* InvalidXPathException is thrown when an invalid XPath * expression is used to traverse an XML document *

* * @version $Revision: 1.6.2.1 $ */ public class InvalidXPathException extends IllegalArgumentException { /** The serialVersionUID. */ private static final long serialVersionUID = 3257009869058881592L; public InvalidXPathException(String xpath) { super("Invalid XPath expression: " + xpath); } public InvalidXPathException(String xpath, String reason) { super("Invalid XPath expression: " + xpath + " " + reason); } public InvalidXPathException(String xpath, Throwable t) { super("Invalid XPath expression: '" + xpath + "'. Caused by: " + t.getMessage()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/jaxb/0000755000175000017500000000000012133227266016330 5ustar ebourgebourgdom4j-1.6.1/src/java/org/dom4j/jaxb/JAXBWriter.java0000644000175000017500000002603310242120013021075 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.jaxb; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import javax.xml.bind.JAXBException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import org.xml.sax.SAXException; /** * Writes {@link javax.xml.bind.Element}objects to an XML stream. {@link * javax.xml.bind.Element} instances can be created using the ObjectFactory that * is generated by the JAXB compiler. * * @author Wonne Keysers (Realsoftware.be) * * @see org.dom4j.io.XMLWriter * @see javax.xml.bind.JAXBContext */ public class JAXBWriter extends JAXBSupport { private XMLWriter xmlWriter; private OutputFormat outputFormat; /** * Creates a new JAXBWriter for the given JAXB context path. This is the * Java package where JAXB can find the generated XML classes. This package * MUST contain jaxb.properties! * * @param contextPath * JAXB context path to be used * * @see javax.xml.bind.JAXBContext */ public JAXBWriter(String contextPath) { super(contextPath); outputFormat = new OutputFormat(); } /** * Creates a new JAXBWriter for the given JAXB context path. The specied * {@link org.dom4j.io.OutputFormat}will be used for writing the XML * stream. * * @param contextPath * JAXB context path to be used * @param outputFormat * the DOM4J {@link org.dom4j.io.OutputFormat}to be used * * @see javax.xml.bind.JAXBContext */ public JAXBWriter(String contextPath, OutputFormat outputFormat) { super(contextPath); this.outputFormat = outputFormat; } /** * Creates a new JAXBWriter for the given JAXB context path, using the * specified {@link java.lang.Classloader}. (This is the Java package where * JAXB can find the generated XML classes. This package MUST contain * jaxb.properties!) * * @param contextPath * JAXB context path to be used * @param classloader * the classloader to be used for loading JAXB * * @see javax.xml.bind.JAXBContext */ public JAXBWriter(String contextPath, ClassLoader classloader) { super(contextPath, classloader); } /** * Creates a new JAXBWriter for the given JAXB context path, using the * specified {@link java.lang.Classloader}. The specied {@link * org.dom4j.io.OutputFormat} will be used while writing the XML stream. * * @param contextPath * JAXB context path to be used * @param classloader * the class loader to be used to load JAXB * @param outputFormat * the DOM4J {@link org.dom4j.io.OutputFormat}to be used * * @see javax.xml.bind.JAXBContext */ public JAXBWriter(String contextPath, ClassLoader classloader, OutputFormat outputFormat) { super(contextPath, classloader); this.outputFormat = outputFormat; } /** * Returns the OutputFormat that will be used when writing the XML stream. * * @return Returns the output format. */ public OutputFormat getOutputFormat() { return outputFormat; } /** * Defines to write the resulting output to the specified {@link * java.io.File}. * * @param file * file to write to * * @throws IOException * when the file cannot be found */ public void setOutput(File file) throws IOException { getWriter().setOutputStream(new FileOutputStream(file)); } /** * Defines to write the resulting output to the specified {@link * java.io.OutputStream} * * @param outputStream * outputStream to write to. * * @throws IOException * DOCUMENT ME! */ public void setOutput(OutputStream outputStream) throws IOException { getWriter().setOutputStream(outputStream); } /** * Defines to write the resulting output to the specified {@link Writer}. * * @param writer * writer to write to * * @throws IOException */ public void setOutput(Writer writer) throws IOException { getWriter().setWriter(writer); } /** * Start a document by writing the initial XML declaration to the output. * This must be done prior to writing any other elements. * * @throws IOException * if an error occured while writing the output * @throws SAXException * thrown by the underlying SAX driver */ public void startDocument() throws IOException, SAXException { getWriter().startDocument(); } /** * Stop writing the document to the output. This must be done when all other * elements are finished. * * @throws IOException * if an error occured while writing the output * @throws SAXException * thrown by the underlying SAX driver */ public void endDocument() throws IOException, SAXException { getWriter().endDocument(); } /** * Writes the specified {@link javax.xml.bind.Element}to the document. * {@link javax.xml.bind.Element}instances can be created using the * ObjectFactory that is generated by the JAXB compiler. * * @param jaxbObject * * @throws IOException * if an error occured while writing the output * @throws JAXBException * when an error occured while marshalling the jaxbObject */ public void write(javax.xml.bind.Element jaxbObject) throws IOException, JAXBException { getWriter().write(marshal(jaxbObject)); } /** * Writes the closing tag of the specified {@link javax.xml.bind.Element}to * the document. This method can be used for writing {@link * javax.xml.bind.Element} instances can be created using the ObjectFactory * that is generated by the JAXB compiler. * * @param jaxbObject * the JAXB element to write * * @throws IOException * if an error occured while writing the output * @throws JAXBException * when an error occured while marshalling the jaxbObject */ public void writeClose(javax.xml.bind.Element jaxbObject) throws IOException, JAXBException { getWriter().writeClose(marshal(jaxbObject)); } /** * Writes the opening tag of the specified {@link javax.xml.bind.Element}to * the document. {@link javax.xml.bind.Element}instances can be created * using the ObjectFactory that is generated by the JAXB compiler. * * @param jaxbObject * the JAXB element to write * * @throws IOException * if an error occured while writing the output * @throws JAXBException * when an error occured while marshalling the jaxbObject */ public void writeOpen(javax.xml.bind.Element jaxbObject) throws IOException, JAXBException { getWriter().writeOpen(marshal(jaxbObject)); } /** * Writes the specified {@link org.dom4j.Element}to the document. * * @param element * the {@link org.dom4j.Element}to write * * @throws IOException * if an error occured while writing the output */ public void writeElement(Element element) throws IOException { getWriter().write(element); } /** * Writes the closing tag of the specified {@link org.dom4j.Element}to the * document. * * @param element * the {@link org.dom4j.Element}to write * * @throws IOException * if an error occured while writing the output */ public void writeCloseElement(Element element) throws IOException { getWriter().writeClose(element); } /** * Writes the opening tag of the specified {@link org.dom4j.Element}to the * document. * * @param element * the {@link org.dom4j.Element}to write * * @throws IOException * if an error occured while writing the output */ public void writeOpenElement(Element element) throws IOException { getWriter().writeOpen(element); } private XMLWriter getWriter() throws IOException { if (xmlWriter == null) { if (this.outputFormat != null) { xmlWriter = new XMLWriter(outputFormat); } else { xmlWriter = new XMLWriter(); } } return xmlWriter; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/jaxb/JAXBReader.java0000644000175000017500000003341510242120006021027 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.jaxb; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.nio.charset.Charset; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.ElementHandler; import org.dom4j.ElementPath; import org.dom4j.io.SAXReader; import org.xml.sax.InputSource; /** * Reads an XML document and creates a DOM4J tree from SAX parsing events. * {@link JAXBObjectHandler}objects can be registered to automatically receive * unmarshalled XML fragments. Registered {@linkorg.dom4j.ElementHandler} * implementations are notified when a certain element path is encountered * * @author Wonne Keysers (Realsoftware.be) * * @see org.dom4j.io.SAXReader * @see javax.xml.bind.JAXBContext */ public class JAXBReader extends JAXBSupport { private SAXReader reader; private boolean pruneElements; /** * Creates a new JAXBReader for the given JAXB context path. This is the * Java package where JAXB can find the generated XML classes. This package * MUST contain jaxb.properties! * * @param contextPath * context path to be used * * @see javax.xml.bind.JAXBContext */ public JAXBReader(String contextPath) { super(contextPath); } /** * Creates a new JAXBReader for the given JAXB context path, using the * specified {@link java.lang.Classloader}. This is the Java package where * JAXB can find the generated XML classes. This package MUST contain * jaxb.properties! * * @param contextPath * to be used * @param classloader * to be used * * @see javax.xml.bind.JAXBContext */ public JAXBReader(String contextPath, ClassLoader classloader) { super(contextPath, classloader); } /** * Parses the specified {@link java.io.File} * * @param source * the file to parse * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing */ public Document read(File source) throws DocumentException { return getReader().read(source); } /** * Parses the specified {@link java.io.File}, using the given {@link * java.nio.charset.Charset}. * * @param file * the file to parse * @param charset * the charset to be used * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing */ public Document read(File file, Charset charset) throws DocumentException { try { Reader xmlReader = new InputStreamReader(new FileInputStream(file), charset); return getReader().read(xmlReader); } catch (JAXBRuntimeException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } catch (FileNotFoundException ex) { throw new DocumentException(ex.getMessage(), ex); } } /** * Parses the specified {@link org.xml.sax.InputSource} * * @param source * the source to parse * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing */ public Document read(InputSource source) throws DocumentException { try { return getReader().read(source); } catch (JAXBRuntimeException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Parses the specified {@link java.io.InputStream} * * @param source * the input stream to parse * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing */ public Document read(InputStream source) throws DocumentException { try { return getReader().read(source); } catch (JAXBRuntimeException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Parses the specified {@link java.io.InputStream} * * @param source * the input stream to parse * @param systemId * is the URI for the input * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing */ public Document read(InputStream source, String systemId) throws DocumentException { try { return getReader().read(source); } catch (JAXBRuntimeException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Parses the specified {@link java.io.Reader} * * @param source * the input reader to use * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing */ public Document read(Reader source) throws DocumentException { try { return getReader().read(source); } catch (JAXBRuntimeException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Parses the specified {@link java.io.Reader} * * @param source * the input reader to parse * @param systemId * is the URI for the input * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing */ public Document read(Reader source, String systemId) throws DocumentException { try { return getReader().read(source); } catch (JAXBRuntimeException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Parses the the given URL or filename. * * @param source * the location to parse * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing */ public Document read(String source) throws DocumentException { try { return getReader().read(source); } catch (JAXBRuntimeException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Parses the the given URL. * * @param source * the URL to parse * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing */ public Document read(URL source) throws DocumentException { try { return getReader().read(source); } catch (JAXBRuntimeException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Registers a {@link JAXBObjectHandler}that will be supplied with the * unmarshalled representation of the xml fragment whenever the specified * path is encounted. * * @param path * the path to listen for * @param handler * the handler to be notified */ public void addObjectHandler(String path, JAXBObjectHandler handler) { ElementHandler eHandler = new UnmarshalElementHandler(this, handler); getReader().addHandler(path, eHandler); } /** * Removes the {@link JAXBObjectHandler}from the event based processor, for * the specified element path. * * @param path * The path to remove the {@link JAXBObjectHandler}for */ public void removeObjectHandler(String path) { getReader().removeHandler(path); } /** * Adds the ElementHandler to be called when the specified * path is encounted. * * @param path * is the path to be handled * @param handler * is the ElementHandler to be called by the event * based processor. */ public void addHandler(String path, ElementHandler handler) { getReader().addHandler(path, handler); } /** * Removes the ElementHandler from the event based processor, * for the specified path. * * @param path * is the path to remove the ElementHandler for. */ public void removeHandler(String path) { getReader().removeHandler(path); } /** * Removes all registered {@link JAXBObjectHandler}and {@link * org.dom4j.ElementHandler} instances from the event based processor. */ public void resetHandlers() { getReader().resetHandlers(); } /** * When 'true', the DOM4J document will not be kept in memory while parsing. * * @return Returns the pruneElements. */ public boolean isPruneElements() { return pruneElements; } /** * Set to true when DOM4J elements must immediately be pruned from the tree. * The {@link Document}will not be available afterwards! * * @param pruneElements */ public void setPruneElements(boolean pruneElements) { this.pruneElements = pruneElements; if (pruneElements) { getReader().setDefaultHandler(new PruningElementHandler()); } } private SAXReader getReader() { if (reader == null) { reader = new SAXReader(); } return reader; } private class UnmarshalElementHandler implements ElementHandler { private JAXBReader jaxbReader; private JAXBObjectHandler handler; public UnmarshalElementHandler(JAXBReader documentReader, JAXBObjectHandler handler) { this.jaxbReader = documentReader; this.handler = handler; } public void onStart(ElementPath elementPath) { } public void onEnd(ElementPath elementPath) { try { org.dom4j.Element elem = elementPath.getCurrent(); javax.xml.bind.Element jaxbObject = (javax.xml.bind.Element) jaxbReader.unmarshal(elem); if (jaxbReader.isPruneElements()) { elem.detach(); } handler.handleObject(jaxbObject); } catch (Exception ex) { throw new JAXBRuntimeException(ex); } } } private class PruningElementHandler implements ElementHandler { public PruningElementHandler() { } public void onStart(ElementPath parm1) { } public void onEnd(ElementPath elementPath) { Element elem = elementPath.getCurrent(); elem.detach(); elem = null; } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/jaxb/JAXBSupport.java0000644000175000017500000001167710242120016021310 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.jaxb; import java.io.StringReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import org.dom4j.dom.DOMDocument; /** * DOCUMENT ME! * * @author Wonne Keysers (Realsoftware.be) */ abstract class JAXBSupport { private String contextPath; private ClassLoader classloader; private JAXBContext jaxbContext; private Marshaller marshaller; private Unmarshaller unmarshaller; public JAXBSupport(String contextPath) { this.contextPath = contextPath; } public JAXBSupport(String contextPath, ClassLoader classloader) { this.contextPath = contextPath; this.classloader = classloader; } /** * Marshals the given {@link javax.xml.bind.Element}in to its DOM4J * counterpart. * * @param element * JAXB Element to be marshalled * * @return the marshalled DOM4J {@link org.dom4j.Element} * * @throws JAXBException * when an error occurs */ protected org.dom4j.Element marshal(javax.xml.bind.Element element) throws JAXBException { DOMDocument doc = new DOMDocument(); getMarshaller().marshal(element, doc); return doc.getRootElement(); } /** * Unmarshalls the specified DOM4J {@link org.dom4j.Element}into a {@link * javax.xml.bind.Element} * * @param element * the DOM4J element to unmarshall * * @return the unmarshalled JAXB object * * @throws JAXBException * when an error occurs */ protected javax.xml.bind.Element unmarshal(org.dom4j.Element element) throws JAXBException { Source source = new StreamSource(new StringReader(element.asXML())); return (javax.xml.bind.Element) getUnmarshaller().unmarshal(source); } private Marshaller getMarshaller() throws JAXBException { if (marshaller == null) { marshaller = getContext().createMarshaller(); } return marshaller; } private Unmarshaller getUnmarshaller() throws JAXBException { if (unmarshaller == null) { unmarshaller = getContext().createUnmarshaller(); } return unmarshaller; } private JAXBContext getContext() throws JAXBException { if (jaxbContext == null) { if (classloader == null) { jaxbContext = JAXBContext.newInstance(contextPath); } else { jaxbContext = JAXBContext.newInstance(contextPath, classloader); } } return jaxbContext; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/jaxb/JAXBModifier.java0000644000175000017500000004322410242120007021363 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.jaxb; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URL; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.ElementModifier; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXModifier; import org.dom4j.io.XMLWriter; import org.xml.sax.InputSource; /** * Reads an XML document using SAX and writes its content to the provided * {@link org.dom4j.io.XMLWriter}. Modifications must be provided by {@link * org.dom4j.jaxb.JAXBObjectModifier} objects, which are called prior to writing * the XML fragment they are registered for. * * @author Wonne Keysers (Realsoftware.be) * * @see org.dom4j.io.SAXModifier */ public class JAXBModifier extends JAXBSupport { private SAXModifier modifier; private XMLWriter xmlWriter; private boolean pruneElements; private OutputFormat outputFormat; private HashMap modifiers = new HashMap(); /** * Creates a new JAXBModifier for the given JAXB context path. This is the * Java package where JAXB can find the generated XML classes. This package * MUST contain jaxb.properties! * * @param contextPath * JAXB context path to be used * * @see javax.xml.bind.JAXBContext */ public JAXBModifier(String contextPath) { super(contextPath); this.outputFormat = new OutputFormat(); } /** * Creates a new JAXBModifier for the given JAXB context path, using the * given {@link java.lang.ClassLoader}. This is the Java package where JAXB * can find the generated XML classes. This package MUST contain * jaxb.properties! * * @param contextPath * JAXB context path to be used * @param classloader * the classloader to use * * @see javax.xml.bind.JAXBContext */ public JAXBModifier(String contextPath, ClassLoader classloader) { super(contextPath, classloader); this.outputFormat = new OutputFormat(); } /** * Creates a new JAXBModifier for the given JAXB context path. The specified * {@link org.dom4j.io.OutputFormat}will be used while writing the XML * stream. * * @param contextPath * JAXB context path to be used * @param outputFormat * the DOM4J {@link org.dom4j.io.OutputFormat}to be used * * @see javax.xml.bind.JAXBContext */ public JAXBModifier(String contextPath, OutputFormat outputFormat) { super(contextPath); this.outputFormat = outputFormat; } /** * Creates a new JAXBModifier for the given JAXB context path, using the * specified {@link java.lang.Classloader}. The specified {@link * org.dom4j.io.OutputFormat} will be used while writing the XML stream. * * @param contextPath * JAXB context path to be used * @param classloader * the class loader to be used to load JAXB * @param outputFormat * the DOM4J {@link org.dom4j.io.OutputFormat}to be used * * @see javax.xml.bind.JAXBContext */ public JAXBModifier(String contextPath, ClassLoader classloader, OutputFormat outputFormat) { super(contextPath, classloader); this.outputFormat = outputFormat; } /** * Parses the specified {@link java.io.File}with SAX * * @param source * the file to parse * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing * @throws IOException * when an error occurs while writing to the {@link * org.dom4j.io.XMLWriter} */ public Document modify(File source) throws DocumentException, IOException { return installModifier().modify(source); } /** * Parses the specified {@link java.io.File}with SAX, using the given * {@link java.nio.charset.Charset}. * * @param source * the file to parse * @param charset * the character set to use * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing * @throws IOException * when an error occurs while writing to the {@link * org.dom4j.io.XMLWriter} */ public Document modify(File source, Charset charset) throws DocumentException, IOException { try { Reader reader = new InputStreamReader(new FileInputStream(source), charset); return installModifier().modify(reader); } catch (JAXBRuntimeException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } catch (FileNotFoundException ex) { throw new DocumentException(ex.getMessage(), ex); } } /** * Parses the specified {@link org.xml.sax.InputSource}with SAX. * * @param source * the input source to parse * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing * @throws IOException * when an error occurs while writing to the {@link * org.dom4j.io.XMLWriter} */ public Document modify(InputSource source) throws DocumentException, IOException { try { return installModifier().modify(source); } catch (JAXBRuntimeException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Parses the specified {@link java.io.InputStream}with SAX. * * @param source * the inputstream to parse * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing * @throws IOException * when an error occurs while writing to the {@link * org.dom4j.io.XMLWriter} */ public Document modify(InputStream source) throws DocumentException, IOException { try { return installModifier().modify(source); } catch (JAXBRuntimeException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Parses the specified {@link java.io.InputStream}with SAX. * * @param source * the inputstream to parse * @param systemId * the URI of the given inputstream * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing * @throws IOException * when an error occurs while writing to the {@link * org.dom4j.io.XMLWriter} */ public Document modify(InputStream source, String systemId) throws DocumentException, IOException { try { return installModifier().modify(source); } catch (JAXBRuntimeException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Parses the specified {@link java.io.Reader}with SAX. * * @param r * the reader to use for parsing * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing * @throws IOException * when an error occurs while writing to the {@link * org.dom4j.io.XMLWriter} */ public Document modify(Reader r) throws DocumentException, IOException { try { return installModifier().modify(r); } catch (JAXBRuntimeException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Parses the specified {@link java.io.Reader}with SAX. * * @param source * the reader to parse * @param systemId * the URI of the given reader * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing * @throws IOException * when an error occurs while writing to the {@link * org.dom4j.io.XMLWriter} */ public Document modify(Reader source, String systemId) throws DocumentException, IOException { try { return installModifier().modify(source); } catch (JAXBRuntimeException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Parses the the given URL or filename. * * @param url * the URL or filename to parse * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing * @throws IOException * when an error occurs while writing to the {@link * org.dom4j.io.XMLWriter} */ public Document modify(String url) throws DocumentException, IOException { try { return installModifier().modify(url); } catch (JAXBRuntimeException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Parses the the given URL. * * @param source * the URL to parse * * @return the resulting DOM4J document * * @throws DocumentException * when an error occurs while parsing * @throws IOException * when an error occurs while writing to the {@link * org.dom4j.io.XMLWriter} */ public Document modify(URL source) throws DocumentException, IOException { try { return installModifier().modify(source); } catch (JAXBRuntimeException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Sets the Output to write the (modified) xml document to. * * @param file * the {@link java.io.File}to write to * * @throws IOException * when the file cannot be found or when the outputformat */ public void setOutput(File file) throws IOException { createXMLWriter().setOutputStream(new FileOutputStream(file)); } /** * Sets the Output to write the (modified) xml document to. * * @param outputStream * the {@link java.io.OutputStream}to write to * * @throws IOException * when an error occurs */ public void setOutput(OutputStream outputStream) throws IOException { createXMLWriter().setOutputStream(outputStream); } /** * Sets the Output to write the (modified) xml document to. * * @param writer * the {@link java.io.Writer}to write to * * @throws IOException * when an error occurs */ public void setOutput(Writer writer) throws IOException { createXMLWriter().setWriter(writer); } /** * Adds the {@link JAXBObjectModifier}to be called when the specified xml * path is encounted while parsing the source. * * @param path * the element path to listen for * @param mod * the modifier to register */ public void addObjectModifier(String path, JAXBObjectModifier mod) { modifiers.put(path, mod); } /** * Removes the {@link JAXBObjectModifier}from the event based processor, * for the specified element path. * * @param path * the xml path to remove the modifier for */ public void removeObjectModifier(String path) { modifiers.remove(path); getModifier().removeModifier(path); } /** * Removes all registered {@link JAXBObjectModifier}instances from the * event based processor. */ public void resetObjectModifiers() { modifiers.clear(); getModifier().resetModifiers(); } /** * Returns true when the modified {@link org.dom4j.Document}is not kept in * memory. * * @return Returns true if elements are pruned. */ public boolean isPruneElements() { return pruneElements; } /** * Define whether the modified {@link org.dom4j.Document}must only be * written to the output and pruned from the DOM4J tree. * * @param pruneElements * When true, elements will not be kept in memory */ public void setPruneElements(boolean pruneElements) { this.pruneElements = pruneElements; } private SAXModifier installModifier() throws IOException { modifier = new SAXModifier(isPruneElements()); modifier.resetModifiers(); Iterator modifierIt = modifiers.entrySet().iterator(); while (modifierIt.hasNext()) { Map.Entry entry = (Map.Entry) modifierIt.next(); ElementModifier mod = new JAXBElementModifier(this, (JAXBObjectModifier) entry.getValue()); getModifier().addModifier((String) entry.getKey(), mod); } modifier.setXMLWriter(getXMLWriter()); return modifier; } private SAXModifier getModifier() { if (this.modifier == null) { modifier = new SAXModifier(isPruneElements()); } return modifier; } private XMLWriter getXMLWriter() { return xmlWriter; } private XMLWriter createXMLWriter() throws IOException { if (this.xmlWriter == null) { xmlWriter = new XMLWriter(outputFormat); } return xmlWriter; } private class JAXBElementModifier implements ElementModifier { private JAXBModifier jaxbModifier; private JAXBObjectModifier objectModifier; public JAXBElementModifier(JAXBModifier jaxbModifier, JAXBObjectModifier objectModifier) { this.jaxbModifier = jaxbModifier; this.objectModifier = objectModifier; } public org.dom4j.Element modifyElement(org.dom4j.Element element) throws Exception { javax.xml.bind.Element originalObject = jaxbModifier .unmarshal(element); javax.xml.bind.Element modifiedObject = objectModifier .modifyObject(originalObject); return jaxbModifier.marshal(modifiedObject); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/jaxb/JAXBObjectModifier.java0000644000175000017500000000625610242120012022512 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.jaxb; import javax.xml.bind.Element; /** * JAXBObjectHandler implementations can be registered with the {@link * JAXBModifier} in order to change unmarshalled XML fragments. * * @author Wonne Keysers (Realsoftware.be) */ public interface JAXBObjectModifier { /** * Called when the {@link JAXBModifier}has finished parsing the xml path * the handler was registered for. The provided object is the unmarshalled * representation of the XML fragment. It can be casted to the appropriate * implementation class that is generated by the JAXB compiler.
* The modified JAXB element that returns from this method will be * marshalled by the {@link JAXBModifier}and put in the DOM4J tree. * * @param jaxbElement * the JAXB object to be modified * * @return the modified JAXB object, or null when it must be removed. * * @throws Exception * possibly thrown by the implementation. */ Element modifyObject(Element jaxbElement) throws Exception; } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/jaxb/JAXBObjectHandler.java0000644000175000017500000000567510242117776022364 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.jaxb; import javax.xml.bind.Element; /** * JAXBObjectHandler implementations can be registered with the JAXB Reader in * order to receive unmarshalled XML fragments. * * @author Wonne Keysers (Realsoftware.be) */ public interface JAXBObjectHandler { /** * Called when the {@link JAXBReader}has finished parsing the xml path the * handler was registered for. The provided object is the unmarshalled * representation of the XML path. It can be casted to the appropriate * implementation class that is generated by the JAXB compiler. * * @param jaxbElement * the unmarshalled JAXB object to handle * * @throws Exception * of any kind, thrown by the implementation */ void handleObject(Element jaxbElement) throws Exception; } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/jaxb/JAXBRuntimeException.java0000644000175000017500000000515510242120022023125 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.jaxb; /** * Exception internally thrown by the JAXBReader classes. This is a * RuntimeException since the {@link org.dom4j.ElementHandler}methods do not * throw Exceptions. * * @author Wonne Keysers (Realsoftware.be) */ class JAXBRuntimeException extends RuntimeException { /** * DOCUMENT ME! * * @param cause * The causing {@link java.lang.Throwable} */ protected JAXBRuntimeException(Throwable cause) { super(cause); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/Element.java0000644000175000017500000007071710242120003017630 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import java.util.Iterator; import java.util.List; import java.util.Map; /** *

* Element interface defines an XML element. An element can have * declared namespaces, attributes, child nodes and textual content. *

* *

* Some of this interface is optional. Some implementations may be read-only and * not support being modified. Some implementations may not support the parent * relationship and methods such as {@link #getParent}or {@link#getDocument}. *

* * @author James Strachan * @version $Revision: 1.47 $ */ public interface Element extends Branch { // Name and namespace related methods // ------------------------------------------------------------------------- /** *

* Returns the QName of this element which represents the * local name, the qualified name and the Namespace. *

* * @return the QName associated with this element */ QName getQName(); /** *

* Sets the QName of this element which represents the local * name, the qualified name and the Namespace. *

* * @param qname * is the QName to be associated with this element */ void setQName(QName qname); /** *

* Returns the Namespace of this element if one exists * otherwise Namespace.NO_NAMESPACE is returned. *

* * @return the Namespace associated with this element */ Namespace getNamespace(); /** *

* Returns the QName for the given qualified name, using the * namespace URI in scope for the given prefix of the qualified name or the * default namespace if the qualified name has no prefix. *

* * @param qualifiedName * DOCUMENT ME! * * @return the QName for the given qualified name */ QName getQName(String qualifiedName); /** *

* Returns the Namespace which is mapped to the given prefix * or null if it could not be found. *

* * @param prefix * DOCUMENT ME! * * @return the Namespace associated with the given prefix */ Namespace getNamespaceForPrefix(String prefix); /** *

* Returns the Namespace which is mapped to the given URI or * null if it could not be found. If there is more than one * Namespace mapped to the URI, which of them will be * returned is undetermined. *

* * @param uri * DOCUMENT ME! * * @return the Namespace associated with the given URI */ Namespace getNamespaceForURI(String uri); /** *

* Returns the all namespaces which are mapped to the given URI or an empty * list if no such namespaces could be found. *

* * @param uri * DOCUMENT ME! * * @return the namespaces associated with the given URI * * @since 1.5 */ List getNamespacesForURI(String uri); /** *

* Returns the namespace prefix of this element if one exists otherwise an * empty String is returned. *

* * @return the prefix of the Namespace of this element or an * empty String */ String getNamespacePrefix(); /** *

* Returns the URI mapped to the namespace of this element if one exists * otherwise an empty String is returned. *

* * @return the URI for the Namespace of this element or an * empty String */ String getNamespaceURI(); /** *

* Returns the fully qualified name of this element. This will be the same * as the value returned from {@link #getName}if this element has no * namespace attached to this element or an expression of the form * *

     * getNamespacePrefix() + ":" + getName()
     * 
* * will be returned. *

* * @return the fully qualified name of the element. */ String getQualifiedName(); /** *

* Returns any additional namespaces declarations for this element other * than namespace returned via the {@link #getNamespace()}method. If no * additional namespace declarations are present for this element then an * empty list will be returned. The list is backed by the element such that * changes to the list will be reflected in the element though the reverse * is not the case. *

* * @return a list of any additional namespace declarations. */ List additionalNamespaces(); /** *

* Returns all the namespaces declared by this element. If no namespaces are * declared for this element then an empty list will be returned. The list * is backed by the element such that changes to the list will be reflected * in the element though the reverse is not the case. *

* * @return a list of namespaces declared for this element. */ List declaredNamespaces(); // Builder methods // ------------------------------------------------------------------------- /** *

* Adds the attribute value of the given local name. If an attribute already * exists for the given name it will be replaced. Attributes with null * values are silently ignored. If the value of the attribute is null then * this method call will remove any attributes with the given name. *

* * @param name * is the name of the attribute whose value is to be added or * updated * @param value * is the attribute's value * * @return this Element instance. */ Element addAttribute(String name, String value); /** *

* Adds the attribute value of the given fully qualified name. If an * attribute already exists for the given name it will be replaced. * Attributes with null values are silently ignored. If the value of the * attribute is null then this method call will remove any attributes with * the given name. *

* * @param qName * is the fully qualified name of the attribute whose value is to * be added or updated * @param value * is the attribute's value * * @return this Element instance. */ Element addAttribute(QName qName, String value); /** * Adds a new Comment node with the given text to this * element. * * @param comment * is the text for the Comment node. * * @return this Element instance. */ Element addComment(String comment); /** * Adds a new CDATA node with the given text to this element. * * @param cdata * is the text for the CDATA node. * * @return this Element instance. */ Element addCDATA(String cdata); /** * Adds a new Entity node with the given name and text to * this element and returns a reference to the new node. * * @param name * is the name for the Entity node. * @param text * is the text for the Entity node. * * @return this Element instance. */ Element addEntity(String name, String text); /** * Adds a namespace to this element for use by its child content * * @param prefix * is the prefix to use, which should not be null or blank * @param uri * is the namespace URI * * @return this Element instance. */ Element addNamespace(String prefix, String uri); /** * Adds a processing instruction for the given target * * @param target * is the target of the processing instruction * @param text * is the textual data (key/value pairs) of the processing * instruction * * @return this Element instance. */ Element addProcessingInstruction(String target, String text); /** * Adds a processing instruction for the given target * * @param target * is the target of the processing instruction * @param data * is a Map of the key / value pairs of the processing * instruction * * @return this Element instance. */ Element addProcessingInstruction(String target, Map data); /** * Adds a new Text node with the given text to this element. * * @param text * is the text for the Text node. * * @return this Element instance. */ Element addText(String text); // Typesafe modifying methods // ------------------------------------------------------------------------- /** * Adds the given Attribute to this element. If the given * node already has a parent defined then an * IllegalAddException will be thrown. Attributes with null * values are silently ignored. * *

* If the value of the attribute is null then this method call will remove * any attributes with the QName of this attribute. *

* * @param attribute * is the attribute to be added */ void add(Attribute attribute); /** * Adds the given CDATA to this element. If the given node * already has a parent defined then an IllegalAddException * will be thrown. * * @param cdata * is the CDATA to be added */ void add(CDATA cdata); /** * Adds the given Entity to this element. If the given node * already has a parent defined then an IllegalAddException * will be thrown. * * @param entity * is the entity to be added */ void add(Entity entity); /** * Adds the given Text to this element. If the given node * already has a parent defined then an IllegalAddException * will be thrown. * * @param text * is the text to be added */ void add(Text text); /** * Adds the given Namespace to this element. If the given * node already has a parent defined then an * IllegalAddException will be thrown. * * @param namespace * is the namespace to be added */ void add(Namespace namespace); /** * Removes the given Attribute from this element. * * @param attribute * is the attribute to be removed * * @return true if the attribute was removed */ boolean remove(Attribute attribute); /** * Removes the given CDATA if the node is an immediate child * of this element. If the given node is not an immediate child of this * element then the {@link Node#detach()}method should be used instead. * * @param cdata * is the CDATA to be removed * * @return true if the cdata was removed */ boolean remove(CDATA cdata); /** * Removes the given Entity if the node is an immediate child * of this element. If the given node is not an immediate child of this * element then the {@link Node#detach()}method should be used instead. * * @param entity * is the entity to be removed * * @return true if the entity was removed */ boolean remove(Entity entity); /** * Removes the given Namespace if the node is an immediate * child of this element. If the given node is not an immediate child of * this element then the {@link Node#detach()}method should be used * instead. * * @param namespace * is the namespace to be removed * * @return true if the namespace was removed */ boolean remove(Namespace namespace); /** * Removes the given Text if the node is an immediate child * of this element. If the given node is not an immediate child of this * element then the {@link Node#detach()}method should be used instead. * * @param text * is the text to be removed * * @return true if the text was removed */ boolean remove(Text text); // Text methods // ------------------------------------------------------------------------- /** * Returns the text value of this element without recursing through child * elements. This method iterates through all {@link Text},{@link CDATA} * and {@link Entity}nodes that this element contains and appends the text * values together. * * @return the textual content of this Element. Child elements are not * navigated. This method does not return null; */ String getText(); /** * DOCUMENT ME! * * @return the trimmed text value where whitespace is trimmed and normalised * into single spaces. This method does not return null. */ String getTextTrim(); /** * Returns the XPath string-value of this node. The behaviour of this method * is defined in the XPath * specification . This method returns the string-value of all the * contained {@link Text},{@link CDATA},{@link Entity}and {@link * Element} nodes all appended together. * * @return the text from all the child Text and Element nodes appended * together. */ String getStringValue(); /** * Accesses the data of this element which may implement data typing * bindings such as XML Schema or Java Bean bindings or will return the same * value as {@link #getText} * * @return DOCUMENT ME! */ Object getData(); /** * Sets the data value of this element if this element supports data binding * or calls {@link #setText}if it doesn't * * @param data * DOCUMENT ME! */ void setData(Object data); // Attribute methods // ------------------------------------------------------------------------- /** *

* Returns the {@link Attribute}instances this element contains as a backed * {@link List}so that the attributes may be modified directly using the * {@link List}interface. The List is backed by the * Element so that changes to the list are reflected in the * element and vice versa. *

* * @return the attributes that this element contains as a List */ List attributes(); /** * Sets the attributes that this element contains * * @param attributes * DOCUMENT ME! */ void setAttributes(List attributes); /** * DOCUMENT ME! * * @return the number of attributes this element contains */ int attributeCount(); /** * DOCUMENT ME! * * @return an iterator over the attributes of this element */ Iterator attributeIterator(); /** * Returns the attribute at the specified indexGets the * * @param index * DOCUMENT ME! * * @return the attribute at the specified index where index >= 0 and * index < number of attributes or throws an * IndexOutOfBoundsException if the index is not within the * allowable range */ Attribute attribute(int index); /** * Returns the attribute with the given name * * @param name * DOCUMENT ME! * * @return the attribute for the given local name in any namespace. If there * are more than one attributes with the given local name in * different namespaces then the first one is returned. */ Attribute attribute(String name); /** * DOCUMENT ME! * * @param qName * is the fully qualified name * * @return the attribute for the given fully qualified name or null if it * could not be found. */ Attribute attribute(QName qName); /** *

* This returns the attribute value for the attribute with the given name * and any namespace or null if there is no such attribute or the empty * string if the attribute value is empty. *

* * @param name * is the name of the attribute value to be returnd * * @return the value of the attribute, null if the attribute does not exist * or the empty string */ String attributeValue(String name); /** *

* This returns the attribute value for the attribute with the given name * and any namespace or the default value if there is no such attribute * value. *

* * @param name * is the name of the attribute value to be returnd * @param defaultValue * is the default value to be returned if the attribute has no * value defined. * * @return the value of the attribute or the defaultValue if the attribute * has no value defined. */ String attributeValue(String name, String defaultValue); /** *

* This returns the attribute value for the attribute with the given fully * qualified name or null if there is no such attribute or the empty string * if the attribute value is empty. *

* * @param qName * is the fully qualified name * * @return the value of the attribute, null if the attribute does not exist * or the empty string */ String attributeValue(QName qName); /** *

* This returns the attribute value for the attribute with the given fully * qualified name or the default value if there is no such attribute value. *

* * @param qName * is the fully qualified name * @param defaultValue * is the default value to be returned if the attribute has no * value defined. * * @return the value of the attribute or the defaultValue if the attribute * has no value defined. */ String attributeValue(QName qName, String defaultValue); /** *

* Sets the attribute value of the given local name. *

* * @param name * is the name of the attribute whose value is to be added or * updated * @param value * is the attribute's value * * @deprecated As of version 0.5. Please use {@link * #addAttribute(String,String)} instead. WILL BE REMOVED IN * dom4j-1.6 !! */ void setAttributeValue(String name, String value); /** *

* Sets the attribute value of the given fully qualified name. *

* * @param qName * is the fully qualified name of the attribute whose value is to * be added or updated * @param value * is the attribute's value * * @deprecated As of version 0.5. Please use {@link * #addAttribute(QName,String)} instead. WILL BE REMOVED IN * dom4j-1.6 !! */ void setAttributeValue(QName qName, String value); // Content methods // ------------------------------------------------------------------------- /** * Returns the first element for the given local name and any namespace. * * @param name * DOCUMENT ME! * * @return the first element with the given local name */ Element element(String name); /** * Returns the first element for the given fully qualified name. * * @param qName * is the fully qualified name to search for * * @return the first element with the given fully qualified name */ Element element(QName qName); /** *

* Returns the elements contained in this element. If this element does not * contain any elements then this method returns an empty list. The list is * backed by the element such that changes to the list will be reflected in * the element though the reverse is not the case. *

* * @return a list of all the elements in this element. */ List elements(); /** *

* Returns the elements contained in this element with the given local name * and any namespace. If no elements are found then this method returns an * empty list. The list is backed by the element such that changes to the * list will be reflected in the element though the reverse is not the case. *

* * @param name * DOCUMENT ME! * * @return a list of all the elements in this element for the given local * name */ List elements(String name); /** *

* Returns the elements contained in this element with the given fully * qualified name. If no elements are found then this method returns an * empty list. The list is backed by the element such that changes to the * list will be reflected in the element though the reverse is not the case. *

* * @param qName * is the fully qualified name to search for * * @return a list of all the elements in this element for the given fully * qualified name. */ List elements(QName qName); /** * Returns an iterator over all this elements child elements. * * @return an iterator over the contained elements */ Iterator elementIterator(); /** * Returns an iterator over the elements contained in this element which * match the given local name and any namespace. * * @param name * DOCUMENT ME! * * @return an iterator over the contained elements matching the given local * name */ Iterator elementIterator(String name); /** * Returns an iterator over the elements contained in this element which * match the given fully qualified name. * * @param qName * is the fully qualified name to search for * * @return an iterator over the contained elements matching the given fully * qualified name */ Iterator elementIterator(QName qName); // Helper methods // ------------------------------------------------------------------------- /** * DOCUMENT ME! * * @return true if this element is the root element of a document and this * element supports the parent relationship else false. */ boolean isRootElement(); /** *

* Returns true if this Element has mixed content. Mixed * content means that an element contains both textual data and child * elements. *

* * @return true if this element contains mixed content. */ boolean hasMixedContent(); /** *

* Returns true if this Element has text only content. *

* * @return true if this element is empty or only contains text content. */ boolean isTextOnly(); /** * Appends the attributes of the given element to me. This method behaves * like the {@link java.util.Collection#addAll(java.util.Collection)} * method. * * @param element * is the element whose attributes will be added to me. */ void appendAttributes(Element element); /** *

* Creates a deep copy of this element The new element is detached from its * parent, and getParent() on the clone will return null. *

* * @return a new deep copy Element */ Element createCopy(); /** *

* Creates a deep copy of this element with the given local name The new * element is detached from its parent, and getParent() on the clone will * return null. *

* * @param name * DOCUMENT ME! * * @return a new deep copy Element */ Element createCopy(String name); /** *

* Creates a deep copy of this element with the given fully qualified name. * The new element is detached from its parent, and getParent() on the clone * will return null. *

* * @param qName * DOCUMENT ME! * * @return a new deep copy Element */ Element createCopy(QName qName); String elementText(String name); String elementText(QName qname); String elementTextTrim(String name); String elementTextTrim(QName qname); /** * Returns a node at the given index suitable for an XPath result set. This * means the resulting Node will either be null or it will support the * parent relationship. * * @param index * DOCUMENT ME! * * @return the Node for the given index which will support the parent * relationship or null if there is not a node at the given index. */ Node getXPathResult(int index); } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/dom/0000755000175000017500000000000012133227266016163 5ustar ebourgebourgdom4j-1.6.1/src/java/org/dom4j/dom/DOMComment.java0000644000175000017500000001650310242120022020752 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dom; import org.dom4j.Element; import org.dom4j.tree.DefaultComment; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; /** *

* DOMText implements a Text node which supports the W3C DOM API. *

* * @author James Strachan * @version $Revision: 1.12 $ */ public class DOMComment extends DefaultComment implements org.w3c.dom.Comment { public DOMComment(String text) { super(text); } public DOMComment(Element parent, String text) { super(parent, text); } // org.w3c.dom.Node interface // ------------------------------------------------------------------------- public boolean supports(String feature, String version) { return DOMNodeHelper.supports(this, feature, version); } public String getNamespaceURI() { return DOMNodeHelper.getNamespaceURI(this); } public String getPrefix() { return DOMNodeHelper.getPrefix(this); } public void setPrefix(String prefix) throws DOMException { DOMNodeHelper.setPrefix(this, prefix); } public String getLocalName() { return DOMNodeHelper.getLocalName(this); } public String getNodeName() { return "#comment"; } // already part of API // // public short getNodeType(); public String getNodeValue() throws DOMException { return DOMNodeHelper.getNodeValue(this); } public void setNodeValue(String nodeValue) throws DOMException { DOMNodeHelper.setNodeValue(this, nodeValue); } public org.w3c.dom.Node getParentNode() { return DOMNodeHelper.getParentNode(this); } public NodeList getChildNodes() { return DOMNodeHelper.getChildNodes(this); } public org.w3c.dom.Node getFirstChild() { return DOMNodeHelper.getFirstChild(this); } public org.w3c.dom.Node getLastChild() { return DOMNodeHelper.getLastChild(this); } public org.w3c.dom.Node getPreviousSibling() { return DOMNodeHelper.getPreviousSibling(this); } public org.w3c.dom.Node getNextSibling() { return DOMNodeHelper.getNextSibling(this); } public NamedNodeMap getAttributes() { return null; } public Document getOwnerDocument() { return DOMNodeHelper.getOwnerDocument(this); } public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild, org.w3c.dom.Node refChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.insertBefore(this, newChild, refChild); } public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild, org.w3c.dom.Node oldChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.replaceChild(this, newChild, oldChild); } public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild) throws DOMException { return DOMNodeHelper.removeChild(this, oldChild); } public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.appendChild(this, newChild); } private void checkNewChildNode(org.w3c.dom.Node newChild) throws DOMException { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Comment nodes cannot have children"); } public boolean hasChildNodes() { return DOMNodeHelper.hasChildNodes(this); } public org.w3c.dom.Node cloneNode(boolean deep) { return DOMNodeHelper.cloneNode(this, deep); } public void normalize() { DOMNodeHelper.normalize(this); } public boolean isSupported(String feature, String version) { return DOMNodeHelper.isSupported(this, feature, version); } public boolean hasAttributes() { return DOMNodeHelper.hasAttributes(this); } // org.w3c.dom.CharacterData interface // ------------------------------------------------------------------------- public String getData() throws DOMException { return DOMNodeHelper.getData(this); } public void setData(String data) throws DOMException { DOMNodeHelper.setData(this, data); } public int getLength() { return DOMNodeHelper.getLength(this); } public String substringData(int offset, int count) throws DOMException { return DOMNodeHelper.substringData(this, offset, count); } public void appendData(String arg) throws DOMException { DOMNodeHelper.appendData(this, arg); } public void insertData(int offset, String arg) throws DOMException { DOMNodeHelper.insertData(this, offset, arg); } public void deleteData(int offset, int count) throws DOMException { DOMNodeHelper.deleteData(this, offset, count); } public void replaceData(int offset, int count, String arg) throws DOMException { DOMNodeHelper.replaceData(this, offset, count, arg); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/dom/DOMDocumentFactory.java0000644000175000017500000001656010242120005022462 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dom; import java.util.Map; import org.dom4j.Attribute; import org.dom4j.CDATA; import org.dom4j.Comment; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.DocumentType; import org.dom4j.Element; import org.dom4j.Entity; import org.dom4j.Namespace; import org.dom4j.ProcessingInstruction; import org.dom4j.QName; import org.dom4j.Text; import org.dom4j.util.SingletonStrategy; import org.w3c.dom.DOMException; /** *

* DOMDocumentFactory is a factory of DOM4J objects which * implement the W3C DOM API. *

* * @author James Strachan * @version $Revision: 1.21 $ */ public class DOMDocumentFactory extends DocumentFactory implements org.w3c.dom.DOMImplementation { /** The Singleton instance */ private static SingletonStrategy singleton = null; static { try { String defaultSingletonClass = "org.dom4j.util.SimpleSingleton"; Class clazz = null; try { String singletonClass = defaultSingletonClass; singletonClass = System.getProperty( "org.dom4j.dom.DOMDocumentFactory.singleton.strategy", singletonClass); clazz = Class.forName(singletonClass); } catch (Exception exc1) { try { String singletonClass = defaultSingletonClass; clazz = Class.forName(singletonClass); } catch (Exception exc2) { } } singleton = (SingletonStrategy) clazz.newInstance(); singleton.setSingletonClassName(DOMDocumentFactory.class.getName()); } catch (Exception exc3) { } } /** *

* Access to the singleton instance of this factory. *

* * @return the default singleon instance */ public static DocumentFactory getInstance() { DOMDocumentFactory fact = (DOMDocumentFactory) singleton.instance(); return fact; } // Factory methods public Document createDocument() { DOMDocument answer = new DOMDocument(); answer.setDocumentFactory(this); return answer; } public DocumentType createDocType(String name, String publicId, String systemId) { return new DOMDocumentType(name, publicId, systemId); } public Element createElement(QName qname) { return new DOMElement(qname); } public Element createElement(QName qname, int attributeCount) { return new DOMElement(qname, attributeCount); } public Attribute createAttribute(Element owner, QName qname, String value) { return new DOMAttribute(qname, value); } public CDATA createCDATA(String text) { return new DOMCDATA(text); } public Comment createComment(String text) { return new DOMComment(text); } public Text createText(String text) { return new DOMText(text); } public Entity createEntity(String name) { return new DOMEntityReference(name); } public Entity createEntity(String name, String text) { return new DOMEntityReference(name, text); } public Namespace createNamespace(String prefix, String uri) { return new DOMNamespace(prefix, uri); } public ProcessingInstruction createProcessingInstruction(String target, String data) { return new DOMProcessingInstruction(target, data); } public ProcessingInstruction createProcessingInstruction(String target, Map data) { return new DOMProcessingInstruction(target, data); } // org.w3c.dom.DOMImplementation interface public boolean hasFeature(String feat, String version) { if ("XML".equalsIgnoreCase(feat) || "Core".equalsIgnoreCase(feat)) { return ((version == null) || (version.length() == 0) || "1.0".equals(version) || "2.0".equals(version)); } return false; } public org.w3c.dom.DocumentType createDocumentType(String qualifiedName, String publicId, String systemId) throws DOMException { return new DOMDocumentType(qualifiedName, publicId, systemId); } public org.w3c.dom.Document createDocument(String namespaceURI, String qualifiedName, org.w3c.dom.DocumentType docType) throws org.w3c.dom.DOMException { DOMDocument document; if (docType != null) { DOMDocumentType documentType = asDocumentType(docType); document = new DOMDocument(documentType); } else { document = new DOMDocument(); } document.addElement(createQName(qualifiedName, namespaceURI)); return document; } // Implementation methods protected DOMDocumentType asDocumentType(org.w3c.dom.DocumentType docType) { if (docType instanceof DOMDocumentType) { return (DOMDocumentType) docType; } else { return new DOMDocumentType(docType.getName(), docType.getPublicId(), docType.getSystemId()); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */dom4j-1.6.1/src/java/org/dom4j/dom/DOMNamespace.java0000644000175000017500000001371110242117777021271 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dom; import org.dom4j.Element; import org.dom4j.tree.DefaultNamespace; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; /** *

* DOMNamespace implements a Namespace that is compatable with * the DOM API. *

* * @author James Strachan * @version $Revision: 1.10 $ */ public class DOMNamespace extends DefaultNamespace implements org.w3c.dom.Node { public DOMNamespace(String prefix, String uri) { super(prefix, uri); } public DOMNamespace(Element parent, String prefix, String uri) { super(parent, prefix, uri); } // org.w3c.dom.Node interface // ------------------------------------------------------------------------- public boolean supports(String feature, String version) { return DOMNodeHelper.supports(this, feature, version); } public String getNamespaceURI() { return DOMNodeHelper.getNamespaceURI(this); } // public String getPrefix() { // return DOMNodeHelper.getPrefix(this); // } public void setPrefix(String prefix) throws DOMException { DOMNodeHelper.setPrefix(this, prefix); } public String getLocalName() { return DOMNodeHelper.getLocalName(this); } public String getNodeName() { return getName(); } // already part of API // // public short getNodeType(); public String getNodeValue() throws DOMException { return DOMNodeHelper.getNodeValue(this); } public void setNodeValue(String nodeValue) throws DOMException { DOMNodeHelper.setNodeValue(this, nodeValue); } public org.w3c.dom.Node getParentNode() { return DOMNodeHelper.getParentNode(this); } public NodeList getChildNodes() { return DOMNodeHelper.getChildNodes(this); } public org.w3c.dom.Node getFirstChild() { return DOMNodeHelper.getFirstChild(this); } public org.w3c.dom.Node getLastChild() { return DOMNodeHelper.getLastChild(this); } public org.w3c.dom.Node getPreviousSibling() { return DOMNodeHelper.getPreviousSibling(this); } public org.w3c.dom.Node getNextSibling() { return DOMNodeHelper.getNextSibling(this); } public NamedNodeMap getAttributes() { return DOMNodeHelper.getAttributes(this); } public Document getOwnerDocument() { return DOMNodeHelper.getOwnerDocument(this); } public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild, org.w3c.dom.Node refChild) throws DOMException { return DOMNodeHelper.insertBefore(this, newChild, refChild); } public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild, org.w3c.dom.Node oldChild) throws DOMException { return DOMNodeHelper.replaceChild(this, newChild, oldChild); } public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild) throws DOMException { return DOMNodeHelper.removeChild(this, oldChild); } public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild) throws DOMException { return DOMNodeHelper.appendChild(this, newChild); } public boolean hasChildNodes() { return DOMNodeHelper.hasChildNodes(this); } public org.w3c.dom.Node cloneNode(boolean deep) { return DOMNodeHelper.cloneNode(this, deep); } public void normalize() { DOMNodeHelper.normalize(this); } public boolean isSupported(String feature, String version) { return DOMNodeHelper.isSupported(this, feature, version); } public boolean hasAttributes() { return DOMNodeHelper.hasAttributes(this); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/dom/DOMCDATA.java0000644000175000017500000002124510242120005020164 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dom; import org.dom4j.CDATA; import org.dom4j.Element; import org.dom4j.tree.DefaultCDATA; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; /** *

* DOMCDATA implements a CDATA Section which supports the W3C DOM * API. *

* * @author James Strachan * @version $Revision: 1.12 $ */ public class DOMCDATA extends DefaultCDATA implements org.w3c.dom.CDATASection { public DOMCDATA(String text) { super(text); } public DOMCDATA(Element parent, String text) { super(parent, text); } // org.w3c.dom.Node interface // ------------------------------------------------------------------------- public boolean supports(String feature, String version) { return DOMNodeHelper.supports(this, feature, version); } public String getNamespaceURI() { return DOMNodeHelper.getNamespaceURI(this); } public String getPrefix() { return DOMNodeHelper.getPrefix(this); } public void setPrefix(String prefix) throws DOMException { DOMNodeHelper.setPrefix(this, prefix); } public String getLocalName() { return DOMNodeHelper.getLocalName(this); } public String getNodeName() { return "#cdata-section"; } // already part of API // // public short getNodeType(); public String getNodeValue() throws DOMException { return DOMNodeHelper.getNodeValue(this); } public void setNodeValue(String nodeValue) throws DOMException { DOMNodeHelper.setNodeValue(this, nodeValue); } public org.w3c.dom.Node getParentNode() { return DOMNodeHelper.getParentNode(this); } public NodeList getChildNodes() { return DOMNodeHelper.getChildNodes(this); } public org.w3c.dom.Node getFirstChild() { return DOMNodeHelper.getFirstChild(this); } public org.w3c.dom.Node getLastChild() { return DOMNodeHelper.getLastChild(this); } public org.w3c.dom.Node getPreviousSibling() { return DOMNodeHelper.getPreviousSibling(this); } public org.w3c.dom.Node getNextSibling() { return DOMNodeHelper.getNextSibling(this); } public NamedNodeMap getAttributes() { return null; } public Document getOwnerDocument() { return DOMNodeHelper.getOwnerDocument(this); } public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild, org.w3c.dom.Node refChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.insertBefore(this, newChild, refChild); } public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild, org.w3c.dom.Node oldChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.replaceChild(this, newChild, oldChild); } public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild) throws DOMException { return DOMNodeHelper.removeChild(this, oldChild); } public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.appendChild(this, newChild); } private void checkNewChildNode(org.w3c.dom.Node newChild) throws DOMException { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "CDATASection nodes cannot have children"); } public boolean hasChildNodes() { return DOMNodeHelper.hasChildNodes(this); } public org.w3c.dom.Node cloneNode(boolean deep) { return DOMNodeHelper.cloneNode(this, deep); } public void normalize() { DOMNodeHelper.normalize(this); } public boolean isSupported(String feature, String version) { return DOMNodeHelper.isSupported(this, feature, version); } public boolean hasAttributes() { return DOMNodeHelper.hasAttributes(this); } // org.w3c.dom.CharacterData interface // ------------------------------------------------------------------------- public String getData() throws DOMException { return DOMNodeHelper.getData(this); } public void setData(String data) throws DOMException { DOMNodeHelper.setData(this, data); } public int getLength() { return DOMNodeHelper.getLength(this); } public String substringData(int offset, int count) throws DOMException { return DOMNodeHelper.substringData(this, offset, count); } public void appendData(String arg) throws DOMException { DOMNodeHelper.appendData(this, arg); } public void insertData(int offset, String arg) throws DOMException { DOMNodeHelper.insertData(this, offset, arg); } public void deleteData(int offset, int count) throws DOMException { DOMNodeHelper.deleteData(this, offset, count); } public void replaceData(int offset, int count, String arg) throws DOMException { DOMNodeHelper.replaceData(this, offset, count, arg); } // org.w3c.dom.Text interface // ------------------------------------------------------------------------- public org.w3c.dom.Text splitText(int offset) throws DOMException { if (isReadOnly()) { throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "CharacterData node is read only: " + this); } else { String text = getText(); int length = (text != null) ? text.length() : 0; if ((offset < 0) || (offset >= length)) { throw new DOMException(DOMException.INDEX_SIZE_ERR, "No text at offset: " + offset); } else { String start = text.substring(0, offset); String rest = text.substring(offset); setText(start); Element parent = getParent(); CDATA newText = createCDATA(rest); if (parent != null) { parent.add(newText); } return DOMNodeHelper.asDOMText(newText); } } } // Implementation methods // ------------------------------------------------------------------------- protected CDATA createCDATA(String text) { return new DOMCDATA(text); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/dom/DOMEntityReference.java0000644000175000017500000001542510242120015022447 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dom; import org.dom4j.Element; import org.dom4j.tree.DefaultEntity; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; /** *

* DOMEntity implements a Entity node which supports the W3C DOM * API. *

* * @author James Strachan * @version $Revision: 1.12 $ */ public class DOMEntityReference extends DefaultEntity implements org.w3c.dom.EntityReference { public DOMEntityReference(String name) { super(name); } public DOMEntityReference(String name, String text) { super(name, text); } public DOMEntityReference(Element parent, String name, String text) { super(parent, name, text); } // org.w3c.dom.Node interface // ------------------------------------------------------------------------- public boolean supports(String feature, String version) { return DOMNodeHelper.supports(this, feature, version); } public String getNamespaceURI() { return DOMNodeHelper.getNamespaceURI(this); } public String getPrefix() { return DOMNodeHelper.getPrefix(this); } public void setPrefix(String prefix) throws DOMException { DOMNodeHelper.setPrefix(this, prefix); } public String getLocalName() { return DOMNodeHelper.getLocalName(this); } public String getNodeName() { return getName(); } // already part of API // // public short getNodeType(); public String getNodeValue() throws DOMException { return null; } public void setNodeValue(String nodeValue) throws DOMException { } public org.w3c.dom.Node getParentNode() { return DOMNodeHelper.getParentNode(this); } public NodeList getChildNodes() { return DOMNodeHelper.getChildNodes(this); } public org.w3c.dom.Node getFirstChild() { return DOMNodeHelper.getFirstChild(this); } public org.w3c.dom.Node getLastChild() { return DOMNodeHelper.getLastChild(this); } public org.w3c.dom.Node getPreviousSibling() { return DOMNodeHelper.getPreviousSibling(this); } public org.w3c.dom.Node getNextSibling() { return DOMNodeHelper.getNextSibling(this); } public NamedNodeMap getAttributes() { return null; } public Document getOwnerDocument() { return DOMNodeHelper.getOwnerDocument(this); } public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild, org.w3c.dom.Node refChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.insertBefore(this, newChild, refChild); } public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild, org.w3c.dom.Node oldChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.replaceChild(this, newChild, oldChild); } public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild) throws DOMException { return DOMNodeHelper.removeChild(this, oldChild); } public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.appendChild(this, newChild); } private void checkNewChildNode(org.w3c.dom.Node newChild) throws DOMException { final int nodeType = newChild.getNodeType(); if (!((nodeType == org.w3c.dom.Node.ELEMENT_NODE) || (nodeType == org.w3c.dom.Node.TEXT_NODE) || (nodeType == org.w3c.dom.Node.COMMENT_NODE) || (nodeType == org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE) || (nodeType == org.w3c.dom.Node.CDATA_SECTION_NODE) || (nodeType == org.w3c.dom.Node.ENTITY_REFERENCE_NODE))) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Given node cannot be a child of an entity " + "reference"); } } public boolean hasChildNodes() { return DOMNodeHelper.hasChildNodes(this); } public org.w3c.dom.Node cloneNode(boolean deep) { return DOMNodeHelper.cloneNode(this, deep); } public void normalize() { DOMNodeHelper.normalize(this); } public boolean isSupported(String feature, String version) { return DOMNodeHelper.isSupported(this, feature, version); } public boolean hasAttributes() { return DOMNodeHelper.hasAttributes(this); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/dom/DOMDocumentType.java0000644000175000017500000001541410242120024021772 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dom; import org.dom4j.tree.DefaultDocumentType; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; /** *

* DOMDocumentType implements a DocumentType node which supports * the W3C DOM API. *

* * @author James Strachan * @version $Revision: 1.11 $ */ public class DOMDocumentType extends DefaultDocumentType implements org.w3c.dom.DocumentType { public DOMDocumentType() { } public DOMDocumentType(String elementName, String systemID) { super(elementName, systemID); } public DOMDocumentType(String name, String publicID, String systemID) { super(name, publicID, systemID); } // org.w3c.dom.Node interface // ------------------------------------------------------------------------- public boolean supports(String feature, String version) { return DOMNodeHelper.supports(this, feature, version); } public String getNamespaceURI() { return DOMNodeHelper.getNamespaceURI(this); } public String getPrefix() { return DOMNodeHelper.getPrefix(this); } public void setPrefix(String prefix) throws DOMException { DOMNodeHelper.setPrefix(this, prefix); } public String getLocalName() { return DOMNodeHelper.getLocalName(this); } public String getNodeName() { return getName(); } // already part of API // // public short getNodeType(); public String getNodeValue() throws DOMException { return null; } public void setNodeValue(String nodeValue) throws DOMException { } public org.w3c.dom.Node getParentNode() { return DOMNodeHelper.getParentNode(this); } public NodeList getChildNodes() { return DOMNodeHelper.getChildNodes(this); } public org.w3c.dom.Node getFirstChild() { return DOMNodeHelper.getFirstChild(this); } public org.w3c.dom.Node getLastChild() { return DOMNodeHelper.getLastChild(this); } public org.w3c.dom.Node getPreviousSibling() { return DOMNodeHelper.getPreviousSibling(this); } public org.w3c.dom.Node getNextSibling() { return DOMNodeHelper.getNextSibling(this); } public NamedNodeMap getAttributes() { return null; } public Document getOwnerDocument() { return DOMNodeHelper.getOwnerDocument(this); } public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild, org.w3c.dom.Node refChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.insertBefore(this, newChild, refChild); } public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild, org.w3c.dom.Node oldChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.replaceChild(this, newChild, oldChild); } public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild) throws DOMException { return DOMNodeHelper.removeChild(this, oldChild); } public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.appendChild(this, newChild); } private void checkNewChildNode(org.w3c.dom.Node newChild) throws DOMException { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "DocumentType nodes cannot have children"); } public boolean hasChildNodes() { return DOMNodeHelper.hasChildNodes(this); } public org.w3c.dom.Node cloneNode(boolean deep) { return DOMNodeHelper.cloneNode(this, deep); } public void normalize() { DOMNodeHelper.normalize(this); } public boolean isSupported(String feature, String version) { return DOMNodeHelper.isSupported(this, feature, version); } public boolean hasAttributes() { return DOMNodeHelper.hasAttributes(this); } // org.w3c.dom.DocumentType interface // ------------------------------------------------------------------------- public NamedNodeMap getEntities() { return null; } public NamedNodeMap getNotations() { return null; } public String getPublicId() { return getPublicID(); } public String getSystemId() { return getSystemID(); } public String getInternalSubset() { return getElementName(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/dom/DOMAttribute.java0000644000175000017500000001620210242120014021310 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dom; import org.dom4j.Element; import org.dom4j.QName; import org.dom4j.tree.DefaultAttribute; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; /** *

* DOMAttribute implements a doubly linked attribute which * supports the W3C DOM API. *

* * @author James Strachan * @version $Revision: 1.14 $ */ public class DOMAttribute extends DefaultAttribute implements org.w3c.dom.Attr { public DOMAttribute(QName qname) { super(qname); } public DOMAttribute(QName qname, String value) { super(qname, value); } public DOMAttribute(Element parent, QName qname, String value) { super(parent, qname, value); } // org.w3c.dom.Node interface // ------------------------------------------------------------------------- public boolean supports(String feature, String version) { return DOMNodeHelper.supports(this, feature, version); } public String getNamespaceURI() { return getQName().getNamespaceURI(); } public String getPrefix() { return getQName().getNamespacePrefix(); } public void setPrefix(String prefix) throws DOMException { DOMNodeHelper.setPrefix(this, prefix); } public String getLocalName() { return getQName().getName(); } public String getNodeName() { return getName(); } // already part of API // // public short getNodeType(); public String getNodeValue() throws DOMException { return DOMNodeHelper.getNodeValue(this); } public void setNodeValue(String nodeValue) throws DOMException { DOMNodeHelper.setNodeValue(this, nodeValue); } public org.w3c.dom.Node getParentNode() { // Per http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-637646024 // and the NIST conformance tests, Attr.getParentNode() should always // return null return null; } public NodeList getChildNodes() { return DOMNodeHelper.getChildNodes(this); } public org.w3c.dom.Node getFirstChild() { return DOMNodeHelper.getFirstChild(this); } public org.w3c.dom.Node getLastChild() { return DOMNodeHelper.getLastChild(this); } public org.w3c.dom.Node getPreviousSibling() { return DOMNodeHelper.getPreviousSibling(this); } public org.w3c.dom.Node getNextSibling() { return DOMNodeHelper.getNextSibling(this); } public NamedNodeMap getAttributes() { return null; } public Document getOwnerDocument() { return DOMNodeHelper.getOwnerDocument(this); } public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild, org.w3c.dom.Node refChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.insertBefore(this, newChild, refChild); } public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild, org.w3c.dom.Node oldChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.replaceChild(this, newChild, oldChild); } public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild) throws DOMException { return DOMNodeHelper.removeChild(this, oldChild); } public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.appendChild(this, newChild); } private void checkNewChildNode(org.w3c.dom.Node newChild) throws DOMException { final int nodeType = newChild.getNodeType(); if (!((nodeType == org.w3c.dom.Node.TEXT_NODE) || (nodeType == org.w3c.dom.Node.ENTITY_REFERENCE_NODE))) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "The node cannot be a child of attribute"); } } public boolean hasChildNodes() { return DOMNodeHelper.hasChildNodes(this); } public org.w3c.dom.Node cloneNode(boolean deep) { return DOMNodeHelper.cloneNode(this, deep); } public void normalize() { DOMNodeHelper.normalize(this); } public boolean isSupported(String feature, String version) { return DOMNodeHelper.isSupported(this, feature, version); } public boolean hasAttributes() { return DOMNodeHelper.hasAttributes(this); } // org.w3c.dom.Attr interface // ------------------------------------------------------------------------- // public String getName(); public boolean getSpecified() { return true; } // public String getValue(); // public void setValue(String value) throws DOMException; public org.w3c.dom.Element getOwnerElement() { return DOMNodeHelper.asDOMElement(getParent()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/dom/DOMElement.java0000644000175000017500000003337510242120004020747 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dom; import java.util.ArrayList; import java.util.List; import org.dom4j.Attribute; import org.dom4j.DocumentFactory; import org.dom4j.Namespace; import org.dom4j.QName; import org.dom4j.tree.DefaultElement; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** *

* DOMElement implements an XML element which supports the W3C * DOM API. *

* * @author James Strachan * @version $Revision: 1.23 $ */ public class DOMElement extends DefaultElement implements org.w3c.dom.Element { /** The DocumentFactory instance used by default */ private static final DocumentFactory DOCUMENT_FACTORY = DOMDocumentFactory .getInstance(); public DOMElement(String name) { super(name); } public DOMElement(QName qname) { super(qname); } public DOMElement(QName qname, int attributeCount) { super(qname, attributeCount); } public DOMElement(String name, Namespace namespace) { super(name, namespace); } // org.w3c.dom.Node interface // ------------------------------------------------------------------------- public boolean supports(String feature, String version) { return DOMNodeHelper.supports(this, feature, version); } public String getNamespaceURI() { return getQName().getNamespaceURI(); } public String getPrefix() { return getQName().getNamespacePrefix(); } public void setPrefix(String prefix) throws DOMException { DOMNodeHelper.setPrefix(this, prefix); } public String getLocalName() { return getQName().getName(); } public String getNodeName() { return getName(); } // already part of API // // public short getNodeType(); public String getNodeValue() throws DOMException { return null; } public void setNodeValue(String nodeValue) throws DOMException { } public org.w3c.dom.Node getParentNode() { return DOMNodeHelper.getParentNode(this); } public NodeList getChildNodes() { return DOMNodeHelper.createNodeList(content()); } public org.w3c.dom.Node getFirstChild() { return DOMNodeHelper.asDOMNode(node(0)); } public org.w3c.dom.Node getLastChild() { return DOMNodeHelper.asDOMNode(node(nodeCount() - 1)); } public org.w3c.dom.Node getPreviousSibling() { return DOMNodeHelper.getPreviousSibling(this); } public org.w3c.dom.Node getNextSibling() { return DOMNodeHelper.getNextSibling(this); } public NamedNodeMap getAttributes() { return new DOMAttributeNodeMap(this); } public Document getOwnerDocument() { return DOMNodeHelper.getOwnerDocument(this); } public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild, org.w3c.dom.Node refChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.insertBefore(this, newChild, refChild); } public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild, org.w3c.dom.Node oldChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.replaceChild(this, newChild, oldChild); } public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild) throws DOMException { return DOMNodeHelper.removeChild(this, oldChild); } public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.appendChild(this, newChild); } private void checkNewChildNode(org.w3c.dom.Node newChild) throws DOMException { final int nodeType = newChild.getNodeType(); if (!((nodeType == Node.ELEMENT_NODE) || (nodeType == Node.TEXT_NODE) || (nodeType == Node.COMMENT_NODE) || (nodeType == Node.PROCESSING_INSTRUCTION_NODE) || (nodeType == Node.CDATA_SECTION_NODE) || (nodeType == Node.ENTITY_REFERENCE_NODE))) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Given node cannot be a child of element"); } } public boolean hasChildNodes() { return nodeCount() > 0; } public org.w3c.dom.Node cloneNode(boolean deep) { return DOMNodeHelper.cloneNode(this, deep); } public boolean isSupported(String feature, String version) { return DOMNodeHelper.isSupported(this, feature, version); } public boolean hasAttributes() { return DOMNodeHelper.hasAttributes(this); } // org.w3c.dom.Element interface // ------------------------------------------------------------------------- public String getTagName() { return getName(); } public String getAttribute(String name) { String answer = attributeValue(name); return (answer != null) ? answer : ""; } public void setAttribute(String name, String value) throws DOMException { addAttribute(name, value); } public void removeAttribute(String name) throws DOMException { Attribute attribute = attribute(name); if (attribute != null) { remove(attribute); } } public org.w3c.dom.Attr getAttributeNode(String name) { return DOMNodeHelper.asDOMAttr(attribute(name)); } public org.w3c.dom.Attr setAttributeNode(org.w3c.dom.Attr newAttr) throws DOMException { if (this.isReadOnly()) { throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "No modification allowed"); } Attribute attribute = attribute(newAttr); if (attribute != newAttr) { if (newAttr.getOwnerElement() != null) { throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR, "Attribute is already in use"); } Attribute newAttribute = createAttribute(newAttr); if (attribute != null) { attribute.detach(); } add(newAttribute); } return DOMNodeHelper.asDOMAttr(attribute); } public org.w3c.dom.Attr removeAttributeNode(org.w3c.dom.Attr oldAttr) throws DOMException { Attribute attribute = attribute(oldAttr); if (attribute != null) { attribute.detach(); return DOMNodeHelper.asDOMAttr(attribute); } else { throw new DOMException(DOMException.NOT_FOUND_ERR, "No such attribute"); } } public String getAttributeNS(String namespaceURI, String localName) { Attribute attribute = attribute(namespaceURI, localName); if (attribute != null) { String answer = attribute.getValue(); if (answer != null) { return answer; } } return ""; } public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException { Attribute attribute = attribute(namespaceURI, qualifiedName); if (attribute != null) { attribute.setValue(value); } else { QName qname = getQName(namespaceURI, qualifiedName); addAttribute(qname, value); } } public void removeAttributeNS(String namespaceURI, String localName) throws DOMException { Attribute attribute = attribute(namespaceURI, localName); if (attribute != null) { remove(attribute); } } public org.w3c.dom.Attr getAttributeNodeNS(String namespaceURI, String localName) { Attribute attribute = attribute(namespaceURI, localName); if (attribute != null) { DOMNodeHelper.asDOMAttr(attribute); } return null; } public org.w3c.dom.Attr setAttributeNodeNS(org.w3c.dom.Attr newAttr) throws DOMException { Attribute attribute = attribute(newAttr.getNamespaceURI(), newAttr .getLocalName()); if (attribute != null) { attribute.setValue(newAttr.getValue()); } else { attribute = createAttribute(newAttr); add(attribute); } return DOMNodeHelper.asDOMAttr(attribute); } public NodeList getElementsByTagName(String name) { ArrayList list = new ArrayList(); DOMNodeHelper.appendElementsByTagName(list, this, name); return DOMNodeHelper.createNodeList(list); } public NodeList getElementsByTagNameNS(String namespace, String lName) { ArrayList list = new ArrayList(); DOMNodeHelper.appendElementsByTagNameNS(list, this, namespace, lName); return DOMNodeHelper.createNodeList(list); } public boolean hasAttribute(String name) { return attribute(name) != null; } public boolean hasAttributeNS(String namespaceURI, String localName) { return attribute(namespaceURI, localName) != null; } // Implementation methods // ------------------------------------------------------------------------- protected DocumentFactory getDocumentFactory() { DocumentFactory factory = getQName().getDocumentFactory(); return (factory != null) ? factory : DOCUMENT_FACTORY; } protected Attribute attribute(org.w3c.dom.Attr attr) { return attribute(DOCUMENT_FACTORY.createQName(attr.getLocalName(), attr .getPrefix(), attr.getNamespaceURI())); } protected Attribute attribute(String namespaceURI, String localName) { List attributes = attributeList(); int size = attributes.size(); for (int i = 0; i < size; i++) { Attribute attribute = (Attribute) attributes.get(i); if (localName.equals(attribute.getName()) && (((namespaceURI == null || namespaceURI.length() == 0) && ((attribute.getNamespaceURI() == null) || (attribute.getNamespaceURI().length() == 0))) || ((namespaceURI != null) && namespaceURI .equals(attribute.getNamespaceURI())))) { return attribute; } } return null; } protected Attribute createAttribute(org.w3c.dom.Attr newAttr) { QName qname = null; String name = newAttr.getLocalName(); if (name != null) { String prefix = newAttr.getPrefix(); String uri = newAttr.getNamespaceURI(); qname = getDocumentFactory().createQName(name, prefix, uri); } else { name = newAttr.getName(); qname = getDocumentFactory().createQName(name); } return new DOMAttribute(qname, newAttr.getValue()); } protected QName getQName(String namespace, String qualifiedName) { int index = qualifiedName.indexOf(':'); String prefix = ""; String localName = qualifiedName; if (index >= 0) { prefix = qualifiedName.substring(0, index); localName = qualifiedName.substring(index + 1); } return getDocumentFactory().createQName(localName, prefix, namespace); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/dom/DOMText.java0000644000175000017500000002117010242120022020270 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dom; import org.dom4j.Element; import org.dom4j.Text; import org.dom4j.tree.DefaultText; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; /** *

* DOMText implements a Text node which supports the W3C DOM API. *

* * @author James Strachan * @version $Revision: 1.12 $ */ public class DOMText extends DefaultText implements org.w3c.dom.Text { public DOMText(String text) { super(text); } public DOMText(Element parent, String text) { super(parent, text); } // org.w3c.dom.Node interface // ------------------------------------------------------------------------- public boolean supports(String feature, String version) { return DOMNodeHelper.supports(this, feature, version); } public String getNamespaceURI() { return DOMNodeHelper.getNamespaceURI(this); } public String getPrefix() { return DOMNodeHelper.getPrefix(this); } public void setPrefix(String prefix) throws DOMException { DOMNodeHelper.setPrefix(this, prefix); } public String getLocalName() { return DOMNodeHelper.getLocalName(this); } public String getNodeName() { return "#text"; } // already part of API // // public short getNodeType(); public String getNodeValue() throws DOMException { return DOMNodeHelper.getNodeValue(this); } public void setNodeValue(String nodeValue) throws DOMException { DOMNodeHelper.setNodeValue(this, nodeValue); } public org.w3c.dom.Node getParentNode() { return DOMNodeHelper.getParentNode(this); } public NodeList getChildNodes() { return DOMNodeHelper.getChildNodes(this); } public org.w3c.dom.Node getFirstChild() { return DOMNodeHelper.getFirstChild(this); } public org.w3c.dom.Node getLastChild() { return DOMNodeHelper.getLastChild(this); } public org.w3c.dom.Node getPreviousSibling() { return DOMNodeHelper.getPreviousSibling(this); } public org.w3c.dom.Node getNextSibling() { return DOMNodeHelper.getNextSibling(this); } public NamedNodeMap getAttributes() { return null; } public Document getOwnerDocument() { return DOMNodeHelper.getOwnerDocument(this); } public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild, org.w3c.dom.Node refChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.insertBefore(this, newChild, refChild); } public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild, org.w3c.dom.Node oldChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.replaceChild(this, newChild, oldChild); } public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild) throws DOMException { return DOMNodeHelper.removeChild(this, oldChild); } public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.appendChild(this, newChild); } private void checkNewChildNode(org.w3c.dom.Node newChild) throws DOMException { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Text nodes cannot have children"); } public boolean hasChildNodes() { return DOMNodeHelper.hasChildNodes(this); } public org.w3c.dom.Node cloneNode(boolean deep) { return DOMNodeHelper.cloneNode(this, deep); } public void normalize() { DOMNodeHelper.normalize(this); } public boolean isSupported(String feature, String version) { return DOMNodeHelper.isSupported(this, feature, version); } public boolean hasAttributes() { return DOMNodeHelper.hasAttributes(this); } // org.w3c.dom.CharacterData interface // ------------------------------------------------------------------------- public String getData() throws DOMException { return DOMNodeHelper.getData(this); } public void setData(String data) throws DOMException { DOMNodeHelper.setData(this, data); } public int getLength() { return DOMNodeHelper.getLength(this); } public String substringData(int offset, int count) throws DOMException { return DOMNodeHelper.substringData(this, offset, count); } public void appendData(String arg) throws DOMException { DOMNodeHelper.appendData(this, arg); } public void insertData(int offset, String arg) throws DOMException { DOMNodeHelper.insertData(this, offset, arg); } public void deleteData(int offset, int count) throws DOMException { DOMNodeHelper.deleteData(this, offset, count); } public void replaceData(int offset, int count, String arg) throws DOMException { DOMNodeHelper.replaceData(this, offset, count, arg); } // org.w3c.dom.Text interface // ------------------------------------------------------------------------- public org.w3c.dom.Text splitText(int offset) throws DOMException { if (isReadOnly()) { throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "CharacterData node is read only: " + this); } else { String text = getText(); int length = (text != null) ? text.length() : 0; if ((offset < 0) || (offset >= length)) { throw new DOMException(DOMException.INDEX_SIZE_ERR, "No text at offset: " + offset); } else { String start = text.substring(0, offset); String rest = text.substring(offset); setText(start); Element parent = getParent(); Text newText = createText(rest); if (parent != null) { parent.add(newText); } return DOMNodeHelper.asDOMText(newText); } } } // Implementation methods // ------------------------------------------------------------------------- protected Text createText(String text) { return new DOMText(text); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/dom/DOMNodeHelper.java0000644000175000017500000004463110242120015021402 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dom; import java.util.List; import org.dom4j.Branch; import org.dom4j.CharacterData; import org.dom4j.Document; import org.dom4j.DocumentType; import org.dom4j.Element; import org.dom4j.Node; import org.w3c.dom.DOMException; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; /** *

* DOMNodeHelper contains a collection of utility methods for use * across Node implementations. *

* * @author James Strachan * @version $Revision: 1.20 $ */ public class DOMNodeHelper { public static final NodeList EMPTY_NODE_LIST = new EmptyNodeList(); protected DOMNodeHelper() { } // Node API // ------------------------------------------------------------------------- public static boolean supports(Node node, String feature, String version) { return false; } public static String getNamespaceURI(Node node) { return null; } public static String getPrefix(Node node) { return null; } public static String getLocalName(Node node) { return null; } public static void setPrefix(Node node, String prefix) throws DOMException { notSupported(); } public static String getNodeValue(Node node) throws DOMException { return node.getText(); } public static void setNodeValue(Node node, String nodeValue) throws DOMException { node.setText(nodeValue); } public static org.w3c.dom.Node getParentNode(Node node) { return asDOMNode(node.getParent()); } public static NodeList getChildNodes(Node node) { return EMPTY_NODE_LIST; } public static org.w3c.dom.Node getFirstChild(Node node) { return null; } public static org.w3c.dom.Node getLastChild(Node node) { return null; } public static org.w3c.dom.Node getPreviousSibling(Node node) { Element parent = node.getParent(); if (parent != null) { int index = parent.indexOf(node); if (index > 0) { Node previous = parent.node(index - 1); return asDOMNode(previous); } } return null; } public static org.w3c.dom.Node getNextSibling(Node node) { Element parent = node.getParent(); if (parent != null) { int index = parent.indexOf(node); if (index >= 0) { if (++index < parent.nodeCount()) { Node next = parent.node(index); return asDOMNode(next); } } } return null; } public static NamedNodeMap getAttributes(Node node) { return null; } public static org.w3c.dom.Document getOwnerDocument(Node node) { return asDOMDocument(node.getDocument()); } public static org.w3c.dom.Node insertBefore(Node node, org.w3c.dom.Node newChild, org.w3c.dom.Node refChild) throws DOMException { if (node instanceof Branch) { Branch branch = (Branch) node; List list = branch.content(); int index = list.indexOf(refChild); if (index < 0) { branch.add((Node) newChild); } else { list.add(index, newChild); } return newChild; } else { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Children not allowed for this node: " + node); } } public static org.w3c.dom.Node replaceChild(Node node, org.w3c.dom.Node newChild, org.w3c.dom.Node oldChild) throws DOMException { if (node instanceof Branch) { Branch branch = (Branch) node; List list = branch.content(); int index = list.indexOf(oldChild); if (index < 0) { throw new DOMException(DOMException.NOT_FOUND_ERR, "Tried to replace a non existing child " + "for node: " + node); } list.set(index, newChild); return oldChild; } else { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Children not allowed for this node: " + node); } } public static org.w3c.dom.Node removeChild(Node node, org.w3c.dom.Node oldChild) throws DOMException { if (node instanceof Branch) { Branch branch = (Branch) node; branch.remove((Node) oldChild); return oldChild; } throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Children not allowed for this node: " + node); } public static org.w3c.dom.Node appendChild(Node node, org.w3c.dom.Node newChild) throws DOMException { if (node instanceof Branch) { Branch branch = (Branch) node; org.w3c.dom.Node previousParent = newChild.getParentNode(); if (previousParent != null) { previousParent.removeChild(newChild); } branch.add((Node) newChild); return newChild; } throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Children not allowed for this node: " + node); } public static boolean hasChildNodes(Node node) { return false; } public static org.w3c.dom.Node cloneNode(Node node, boolean deep) { return asDOMNode((Node) node.clone()); } public static void normalize(Node node) { notSupported(); } public static boolean isSupported(Node n, String feature, String version) { return false; } public static boolean hasAttributes(Node node) { if ((node != null) && node instanceof Element) { return ((Element) node).attributeCount() > 0; } else { return false; } } // CharacterData API // ------------------------------------------------------------------------- public static String getData(CharacterData charData) throws DOMException { return charData.getText(); } public static void setData(CharacterData charData, String data) throws DOMException { charData.setText(data); } public static int getLength(CharacterData charData) { String text = charData.getText(); return (text != null) ? text.length() : 0; } public static String substringData(CharacterData charData, int offset, int count) throws DOMException { if (count < 0) { throw new DOMException(DOMException.INDEX_SIZE_ERR, "Illegal value for count: " + count); } String text = charData.getText(); int length = (text != null) ? text.length() : 0; if ((offset < 0) || (offset >= length)) { throw new DOMException(DOMException.INDEX_SIZE_ERR, "No text at offset: " + offset); } if ((offset + count) > length) { return text.substring(offset); } return text.substring(offset, offset + count); } public static void appendData(CharacterData charData, String arg) throws DOMException { if (charData.isReadOnly()) { throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "CharacterData node is read only: " + charData); } else { String text = charData.getText(); if (text == null) { charData.setText(text); } else { charData.setText(text + arg); } } } public static void insertData(CharacterData data, int offset, String arg) throws DOMException { if (data.isReadOnly()) { throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "CharacterData node is read only: " + data); } else { String text = data.getText(); if (text == null) { data.setText(arg); } else { int length = text.length(); if ((offset < 0) || (offset > length)) { throw new DOMException(DOMException.INDEX_SIZE_ERR, "No text at offset: " + offset); } else { StringBuffer buffer = new StringBuffer(text); buffer.insert(offset, arg); data.setText(buffer.toString()); } } } } public static void deleteData(CharacterData charData, int offset, int count) throws DOMException { if (charData.isReadOnly()) { throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "CharacterData node is read only: " + charData); } else { if (count < 0) { throw new DOMException(DOMException.INDEX_SIZE_ERR, "Illegal value for count: " + count); } String text = charData.getText(); if (text != null) { int length = text.length(); if ((offset < 0) || (offset >= length)) { throw new DOMException(DOMException.INDEX_SIZE_ERR, "No text at offset: " + offset); } else { StringBuffer buffer = new StringBuffer(text); buffer.delete(offset, offset + count); charData.setText(buffer.toString()); } } } } public static void replaceData(CharacterData charData, int offset, int count, String arg) throws DOMException { if (charData.isReadOnly()) { throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "CharacterData node is read only: " + charData); } else { if (count < 0) { throw new DOMException(DOMException.INDEX_SIZE_ERR, "Illegal value for count: " + count); } String text = charData.getText(); if (text != null) { int length = text.length(); if ((offset < 0) || (offset >= length)) { throw new DOMException(DOMException.INDEX_SIZE_ERR, "No text at offset: " + offset); } else { StringBuffer buffer = new StringBuffer(text); buffer.replace(offset, offset + count, arg); charData.setText(buffer.toString()); } } } } // Branch API // ------------------------------------------------------------------------- public static void appendElementsByTagName(List list, Branch parent, String name) { final boolean isStar = "*".equals(name); for (int i = 0, size = parent.nodeCount(); i < size; i++) { Node node = parent.node(i); if (node instanceof Element) { Element element = (Element) node; if (isStar || name.equals(element.getName())) { list.add(element); } appendElementsByTagName(list, element, name); } } } public static void appendElementsByTagNameNS(List list, Branch parent, String namespace, String localName) { final boolean isStarNS = "*".equals(namespace); final boolean isStar = "*".equals(localName); for (int i = 0, size = parent.nodeCount(); i < size; i++) { Node node = parent.node(i); if (node instanceof Element) { Element element = (Element) node; if ((isStarNS || (((namespace == null) || (namespace.length() == 0)) && ((element .getNamespaceURI() == null) || (element .getNamespaceURI().length() == 0))) || ((namespace != null) && namespace .equals(element.getNamespaceURI()))) && (isStar || localName.equals(element.getName()))) { list.add(element); } appendElementsByTagNameNS(list, element, namespace, localName); } } } // Helper methods // ------------------------------------------------------------------------- public static NodeList createNodeList(final List list) { return new NodeList() { public org.w3c.dom.Node item(int index) { if (index >= getLength()) { /* * From the NodeList specification: If index is greater than * or equal to the number of nodes in the list, this returns * null. */ return null; } else { return DOMNodeHelper.asDOMNode((Node) list.get(index)); } } public int getLength() { return list.size(); } }; } public static org.w3c.dom.Node asDOMNode(Node node) { if (node == null) { return null; } if (node instanceof org.w3c.dom.Node) { return (org.w3c.dom.Node) node; } else { // Use DOMWriter? System.out.println("Cannot convert: " + node + " into a W3C DOM Node"); notSupported(); return null; } } public static org.w3c.dom.Document asDOMDocument(Document document) { if (document == null) { return null; } if (document instanceof org.w3c.dom.Document) { return (org.w3c.dom.Document) document; } else { // Use DOMWriter? notSupported(); return null; } } public static org.w3c.dom.DocumentType asDOMDocumentType(DocumentType dt) { if (dt == null) { return null; } if (dt instanceof org.w3c.dom.DocumentType) { return (org.w3c.dom.DocumentType) dt; } else { // Use DOMWriter? notSupported(); return null; } } public static org.w3c.dom.Text asDOMText(CharacterData text) { if (text == null) { return null; } if (text instanceof org.w3c.dom.Text) { return (org.w3c.dom.Text) text; } else { // Use DOMWriter? notSupported(); return null; } } public static org.w3c.dom.Element asDOMElement(Node element) { if (element == null) { return null; } if (element instanceof org.w3c.dom.Element) { return (org.w3c.dom.Element) element; } else { // Use DOMWriter? notSupported(); return null; } } public static org.w3c.dom.Attr asDOMAttr(Node attribute) { if (attribute == null) { return null; } if (attribute instanceof org.w3c.dom.Attr) { return (org.w3c.dom.Attr) attribute; } else { // Use DOMWriter? notSupported(); return null; } } /** * Called when a method has not been implemented yet * * @throws DOMException * DOCUMENT ME! */ public static void notSupported() { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Not supported yet"); } public static class EmptyNodeList implements NodeList { public org.w3c.dom.Node item(int index) { return null; } public int getLength() { return 0; } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/dom/DOMDocument.java0000644000175000017500000002626110242120020021126 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dom; import java.util.ArrayList; import org.dom4j.DocumentFactory; import org.dom4j.QName; import org.dom4j.tree.DefaultDocument; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.EntityReference; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; /** *

* DOMDocument implements an XML document which supports the W3C * DOM API. *

* * @author James Strachan * @version $Revision: 1.17 $ */ public class DOMDocument extends DefaultDocument implements Document { /** The DocumentFactory instance used by default */ private static final DOMDocumentFactory DOCUMENT_FACTORY = (DOMDocumentFactory) DOMDocumentFactory.getInstance(); public DOMDocument() { init(); } public DOMDocument(String name) { super(name); init(); } public DOMDocument(DOMElement rootElement) { super(rootElement); init(); } public DOMDocument(DOMDocumentType docType) { super(docType); init(); } public DOMDocument(DOMElement rootElement, DOMDocumentType docType) { super(rootElement, docType); init(); } public DOMDocument(String name, DOMElement rootElement, DOMDocumentType docType) { super(name, rootElement, docType); init(); } private void init() { setDocumentFactory(DOCUMENT_FACTORY); } // org.w3c.dom.Node interface // ------------------------------------------------------------------------- public boolean supports(String feature, String version) { return DOMNodeHelper.supports(this, feature, version); } public String getNamespaceURI() { return DOMNodeHelper.getNamespaceURI(this); } public String getPrefix() { return DOMNodeHelper.getPrefix(this); } public void setPrefix(String prefix) throws DOMException { DOMNodeHelper.setPrefix(this, prefix); } public String getLocalName() { return DOMNodeHelper.getLocalName(this); } public String getNodeName() { return "#document"; } // already part of API // // public short getNodeType(); public String getNodeValue() throws DOMException { return null; } public void setNodeValue(String nodeValue) throws DOMException { } public org.w3c.dom.Node getParentNode() { return DOMNodeHelper.getParentNode(this); } public NodeList getChildNodes() { return DOMNodeHelper.createNodeList(content()); } public org.w3c.dom.Node getFirstChild() { return DOMNodeHelper.asDOMNode(node(0)); } public org.w3c.dom.Node getLastChild() { return DOMNodeHelper.asDOMNode(node(nodeCount() - 1)); } public org.w3c.dom.Node getPreviousSibling() { return DOMNodeHelper.getPreviousSibling(this); } public org.w3c.dom.Node getNextSibling() { return DOMNodeHelper.getNextSibling(this); } public NamedNodeMap getAttributes() { return null; } public org.w3c.dom.Document getOwnerDocument() { return null; } public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild, org.w3c.dom.Node refChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.insertBefore(this, newChild, refChild); } public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild, org.w3c.dom.Node oldChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.replaceChild(this, newChild, oldChild); } public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild) throws DOMException { return DOMNodeHelper.removeChild(this, oldChild); } public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.appendChild(this, newChild); } private void checkNewChildNode(org.w3c.dom.Node newChild) throws DOMException { final int nodeType = newChild.getNodeType(); if (!((nodeType == org.w3c.dom.Node.ELEMENT_NODE) || (nodeType == org.w3c.dom.Node.COMMENT_NODE) || (nodeType == org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE) || (nodeType == org.w3c.dom.Node.DOCUMENT_TYPE_NODE))) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Given node cannot be a child of document"); } } public boolean hasChildNodes() { return nodeCount() > 0; } public org.w3c.dom.Node cloneNode(boolean deep) { return DOMNodeHelper.cloneNode(this, deep); } public boolean isSupported(String feature, String version) { return DOMNodeHelper.isSupported(this, feature, version); } public boolean hasAttributes() { return DOMNodeHelper.hasAttributes(this); } // org.w3c.dom.Document interface // ------------------------------------------------------------------------- public NodeList getElementsByTagName(String name) { ArrayList list = new ArrayList(); DOMNodeHelper.appendElementsByTagName(list, this, name); return DOMNodeHelper.createNodeList(list); } public NodeList getElementsByTagNameNS(String namespace, String name) { ArrayList list = new ArrayList(); DOMNodeHelper.appendElementsByTagNameNS(list, this, namespace, name); return DOMNodeHelper.createNodeList(list); } public org.w3c.dom.DocumentType getDoctype() { return DOMNodeHelper.asDOMDocumentType(getDocType()); } public org.w3c.dom.DOMImplementation getImplementation() { if (getDocumentFactory() instanceof org.w3c.dom.DOMImplementation) { return (org.w3c.dom.DOMImplementation) getDocumentFactory(); } else { return DOCUMENT_FACTORY; } } public org.w3c.dom.Element getDocumentElement() { return DOMNodeHelper.asDOMElement(getRootElement()); } public org.w3c.dom.Element createElement(String name) throws DOMException { return (org.w3c.dom.Element) getDocumentFactory().createElement(name); } public org.w3c.dom.DocumentFragment createDocumentFragment() { DOMNodeHelper.notSupported(); return null; } public org.w3c.dom.Text createTextNode(String data) { return (org.w3c.dom.Text) getDocumentFactory().createText(data); } public org.w3c.dom.Comment createComment(String data) { return (org.w3c.dom.Comment) getDocumentFactory().createComment(data); } public CDATASection createCDATASection(String data) throws DOMException { return (CDATASection) getDocumentFactory().createCDATA(data); } public ProcessingInstruction createProcessingInstruction(String target, String data) throws DOMException { return (ProcessingInstruction) getDocumentFactory() .createProcessingInstruction(target, data); } public Attr createAttribute(String name) throws DOMException { QName qname = getDocumentFactory().createQName(name); return (Attr) getDocumentFactory().createAttribute(null, qname, ""); } public EntityReference createEntityReference(String name) throws DOMException { return (EntityReference) getDocumentFactory().createEntity(name, null); } public org.w3c.dom.Node importNode(org.w3c.dom.Node importedNode, boolean deep) throws DOMException { DOMNodeHelper.notSupported(); return null; } public org.w3c.dom.Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException { QName qname = getDocumentFactory().createQName(qualifiedName, namespaceURI); return (org.w3c.dom.Element) getDocumentFactory().createElement(qname); } public org.w3c.dom.Attr createAttributeNS(String namespaceURI, String qualifiedName) throws DOMException { QName qname = getDocumentFactory().createQName(qualifiedName, namespaceURI); return (org.w3c.dom.Attr) getDocumentFactory().createAttribute(null, qname, null); } public org.w3c.dom.Element getElementById(String elementId) { return DOMNodeHelper.asDOMElement(elementByID(elementId)); } // Implementation methods // ------------------------------------------------------------------------- protected DocumentFactory getDocumentFactory() { if (super.getDocumentFactory() == null) { return DOCUMENT_FACTORY; } else { return super.getDocumentFactory(); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/dom/package.html0000644000175000017500000000023310242120006020421 0ustar ebourgebourg

An implementation of the dom4j API which also supports the W3C object model.

dom4j-1.6.1/src/java/org/dom4j/dom/DOMProcessingInstruction.java0000644000175000017500000001620410242120007023727 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dom; import java.util.Map; import org.dom4j.Element; import org.dom4j.tree.DefaultProcessingInstruction; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; /** *

* DOMProcessingInstruction implements a ProcessingInstruction * node which supports the W3C DOM API. *

* * @author James Strachan * @version $Revision: 1.12 $ */ public class DOMProcessingInstruction extends DefaultProcessingInstruction implements org.w3c.dom.ProcessingInstruction { public DOMProcessingInstruction(String target, Map values) { super(target, values); } public DOMProcessingInstruction(String target, String values) { super(target, values); } public DOMProcessingInstruction(Element parent, String target, String val) { super(parent, target, val); } // org.w3c.dom.Node interface // ------------------------------------------------------------------------- public boolean supports(String feature, String version) { return DOMNodeHelper.supports(this, feature, version); } public String getNamespaceURI() { return DOMNodeHelper.getNamespaceURI(this); } public String getPrefix() { return DOMNodeHelper.getPrefix(this); } public void setPrefix(String prefix) throws DOMException { DOMNodeHelper.setPrefix(this, prefix); } public String getLocalName() { return DOMNodeHelper.getLocalName(this); } public String getNodeName() { return getName(); } // already part of API // // public short getNodeType(); public String getNodeValue() throws DOMException { return DOMNodeHelper.getNodeValue(this); } public void setNodeValue(String nodeValue) throws DOMException { DOMNodeHelper.setNodeValue(this, nodeValue); } public org.w3c.dom.Node getParentNode() { return DOMNodeHelper.getParentNode(this); } public NodeList getChildNodes() { return DOMNodeHelper.getChildNodes(this); } public org.w3c.dom.Node getFirstChild() { return DOMNodeHelper.getFirstChild(this); } public org.w3c.dom.Node getLastChild() { return DOMNodeHelper.getLastChild(this); } public org.w3c.dom.Node getPreviousSibling() { return DOMNodeHelper.getPreviousSibling(this); } public org.w3c.dom.Node getNextSibling() { return DOMNodeHelper.getNextSibling(this); } public NamedNodeMap getAttributes() { return null; } public Document getOwnerDocument() { return DOMNodeHelper.getOwnerDocument(this); } public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild, org.w3c.dom.Node refChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.insertBefore(this, newChild, refChild); } public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild, org.w3c.dom.Node oldChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.replaceChild(this, newChild, oldChild); } public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild) throws DOMException { return DOMNodeHelper.removeChild(this, oldChild); } public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild) throws DOMException { checkNewChildNode(newChild); return DOMNodeHelper.appendChild(this, newChild); } private void checkNewChildNode(org.w3c.dom.Node newChild) throws DOMException { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "PI nodes cannot have children"); } public boolean hasChildNodes() { return DOMNodeHelper.hasChildNodes(this); } public org.w3c.dom.Node cloneNode(boolean deep) { return DOMNodeHelper.cloneNode(this, deep); } public void normalize() { DOMNodeHelper.normalize(this); } public boolean isSupported(String feature, String version) { return DOMNodeHelper.isSupported(this, feature, version); } public boolean hasAttributes() { return DOMNodeHelper.hasAttributes(this); } // org.w3c.dom.ProcessingInstruction interface // ------------------------------------------------------------------------- // public String getTarget(); public String getData() { return getText(); } public void setData(String data) throws DOMException { if (isReadOnly()) { throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "This ProcessingInstruction is read only"); } else { setText(data); } } // Implementation methods // ------------------------------------------------------------------------- } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/dom/DOMAttributeNodeMap.java0000644000175000017500000001116110242120023022553 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dom; import org.w3c.dom.Attr; import org.w3c.dom.DOMException; import org.w3c.dom.Node; /** *

* DOMAttributeNodeMap implements a W3C NameNodeMap for the * attributes of an element. *

* * @author James Strachan * @version $Revision: 1.8 $ */ public class DOMAttributeNodeMap implements org.w3c.dom.NamedNodeMap { private DOMElement element; public DOMAttributeNodeMap(DOMElement element) { this.element = element; } // org.w3c.dom.NamedNodeMap interface // ------------------------------------------------------------------------- public void foo() throws DOMException { DOMNodeHelper.notSupported(); } public Node getNamedItem(String name) { return element.getAttributeNode(name); } public Node setNamedItem(Node arg) throws DOMException { if (arg instanceof Attr) { return element.setAttributeNode((org.w3c.dom.Attr) arg); } else { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Node is not an Attr: " + arg); } } public Node removeNamedItem(String name) throws DOMException { org.w3c.dom.Attr attr = element.getAttributeNode(name); if (attr == null) { throw new DOMException(DOMException.NOT_FOUND_ERR, "No attribute named " + name); } return element.removeAttributeNode(attr); } public Node item(int index) { return DOMNodeHelper.asDOMAttr(element.attribute(index)); } public int getLength() { return element.attributeCount(); } public Node getNamedItemNS(String namespaceURI, String localName) { return element.getAttributeNodeNS(namespaceURI, localName); } public Node setNamedItemNS(Node arg) throws DOMException { if (arg instanceof Attr) { return element.setAttributeNodeNS((org.w3c.dom.Attr) arg); } else { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Node is not an Attr: " + arg); } } public Node removeNamedItemNS(String namespaceURI, String localName) throws DOMException { org.w3c.dom.Attr attr = element.getAttributeNodeNS(namespaceURI, localName); if (attr != null) { return element.removeAttributeNode(attr); } return attr; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/rule/0000755000175000017500000000000012133227266016353 5ustar ebourgebourgdom4j-1.6.1/src/java/org/dom4j/rule/Action.java0000644000175000017500000000476010242120003020416 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.rule; import org.dom4j.Node; /** *

* Action represents some default action which should occur when * a rule matches a node in the XSLT processing model. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public interface Action { void run(Node node) throws Exception; } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/rule/Stylesheet.java0000644000175000017500000002537510242120021021337 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.rule; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.XPath; /** *

* Stylesheet implements an XSLT stylesheet such that rules can * be added to the stylesheet and the stylesheet can be applied to a source * document or node. *

* * @author James Strachan * @version $Revision: 1.14 $ */ public class Stylesheet { private RuleManager ruleManager = new RuleManager(); /** Holds value of property mode. */ private String modeName; /** * Creates a new empty stylesheet. */ public Stylesheet() { } /** * Add a rule to this stylesheet. * * @param rule * the rule to add */ public void addRule(Rule rule) { ruleManager.addRule(rule); } /** * Removes the specified rule from this stylesheet. * * @param rule * the rule to remove */ public void removeRule(Rule rule) { ruleManager.removeRule(rule); } /** * Runs this stylesheet on the given input which should be either a Node or * a List of Node objects. * * @param input * the input to run this stylesheet on * * @throws Exception * if something goes wrong */ public void run(Object input) throws Exception { run(input, this.modeName); } public void run(Object input, String mode) throws Exception { if (input instanceof Node) { run((Node) input, mode); } else if (input instanceof List) { run((List) input, mode); } } public void run(List list) throws Exception { run(list, this.modeName); } public void run(List list, String mode) throws Exception { for (int i = 0, size = list.size(); i < size; i++) { Object object = list.get(i); if (object instanceof Node) { run((Node) object, mode); } } } public void run(Node node) throws Exception { run(node, this.modeName); } public void run(Node node, String mode) throws Exception { Mode mod = ruleManager.getMode(mode); mod.fireRule(node); } /** * Processes the result of the xpath expression. The xpath expression is * evaluated against the provided input object. * * @param input * the input object * @param xpath * the xpath expression * @throws Exception * if something goes wrong */ public void applyTemplates(Object input, XPath xpath) throws Exception { applyTemplates(input, xpath, this.modeName); } /** * Processes the result of the xpath expression in the given mode. The xpath * expression is evaluated against the provided input object. * * @param input * the input object * @param xpath * the xpath expression * @param mode * the mode * @throws Exception * if something goes wrong */ public void applyTemplates(Object input, XPath xpath, String mode) throws Exception { Mode mod = ruleManager.getMode(mode); List list = xpath.selectNodes(input); Iterator it = list.iterator(); while (it.hasNext()) { Node current = (Node) it.next(); mod.fireRule(current); } } /** * Processes the result of the xpath expression. The xpath expression is * evaluated against the provided input object. * * @param input * the input object * @param xpath * the xpath expression * @throws Exception * if something goes wrong * @deprecated Use {@link Stylesheet#applyTemplates(Object, XPath)}instead. */ public void applyTemplates(Object input, org.jaxen.XPath xpath) throws Exception { applyTemplates(input, xpath, this.modeName); } /** * Processes the result of the xpath expression in the given mode. The xpath * expression is evaluated against the provided input object. * * @param input * the input object * @param xpath * the xpath expression * @param mode * the mode * @throws Exception * if something goes wrong * @deprecated Use {@link Stylesheet#applyTemplates(Object, XPath, String)} * instead. */ public void applyTemplates(Object input, org.jaxen.XPath xpath, String mode) throws Exception { Mode mod = ruleManager.getMode(mode); List list = xpath.selectNodes(input); Iterator it = list.iterator(); while (it.hasNext()) { Node current = (Node) it.next(); mod.fireRule(current); } } /** * If input is a Node, this will processes all of the * children of that node. If input is a List of * Nodess, these nodes will be iterated and all children of * each node will be processed. * * @param input * the input object, this can either be a Node or * a List * @throws Exception * if something goes wrong */ public void applyTemplates(Object input) throws Exception { applyTemplates(input, this.modeName); } /** * Processes the input object in the given mode. If input is a * Node, this will processes all of the children of that * node. If input is a List of Nodess, these * nodes will be iterated and all children of each node will be processed. * * @param input * the input object, this can either be a Node or * a List * @param mode * the mode * @throws Exception * if something goes wrong */ public void applyTemplates(Object input, String mode) throws Exception { Mode mod = ruleManager.getMode(mode); if (input instanceof Element) { // iterate through all children Element element = (Element) input; for (int i = 0, size = element.nodeCount(); i < size; i++) { Node node = element.node(i); mod.fireRule(node); } } else if (input instanceof Document) { // iterate through all children Document document = (Document) input; for (int i = 0, size = document.nodeCount(); i < size; i++) { Node node = document.node(i); mod.fireRule(node); } } else if (input instanceof List) { List list = (List) input; for (int i = 0, size = list.size(); i < size; i++) { Object object = list.get(i); if (object instanceof Element) { applyTemplates((Element) object, mode); } else if (object instanceof Document) { applyTemplates((Document) object, mode); } } } } public void clear() { ruleManager.clear(); } // Properties // ------------------------------------------------------------------------- /** * DOCUMENT ME! * * @return the name of the mode the stylesheet uses by default */ public String getModeName() { return modeName; } /** * Sets the name of the mode that the stylesheet uses by default. * * @param modeName * DOCUMENT ME! */ public void setModeName(String modeName) { this.modeName = modeName; } /** * DOCUMENT ME! * * @return the default value-of action which is used in the default rules * for the pattern "text()|@" */ public Action getValueOfAction() { return ruleManager.getValueOfAction(); } /** * Sets the default value-of action which is used in the default rules for * the pattern "text()|@" * * @param valueOfAction * DOCUMENT ME! */ public void setValueOfAction(Action valueOfAction) { ruleManager.setValueOfAction(valueOfAction); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/rule/Pattern.java0000644000175000017500000001106410242120006020614 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.rule; import org.dom4j.Node; import org.dom4j.NodeFilter; /** *

* Pattern defines the behaviour for pattern in the XSLT * processing model. *

* * @author James Strachan * @version $Revision: 1.6 $ */ public interface Pattern extends NodeFilter { // These node numbers are compatable with DOM4J's Node types /** Matches any node */ short ANY_NODE = 0; /** Matches no nodes */ short NONE = 9999; /** Count of the number of node types */ short NUMBER_OF_TYPES = Node.UNKNOWN_NODE; /** * According to the spec * we should return 0.5 if we cannot determine the priority */ double DEFAULT_PRIORITY = 0.5; /** * DOCUMENT ME! * * @param node * DOCUMENT ME! * * @return true if the pattern matches the given DOM4J node. */ boolean matches(Node node); /** * Returns the default resolution policy of the pattern according to the XSLT conflict resolution * spec . * * @return DOCUMENT ME! */ double getPriority(); /** * If this pattern is a union pattern then this method should return an * array of patterns which describe the union pattern, which should contain * more than one pattern. Otherwise this method should return null. * * @return an array of the patterns which make up this union pattern or null * if this pattern is not a union pattern */ Pattern[] getUnionPatterns(); /** * DOCUMENT ME! * * @return the type of node the pattern matches which by default should * return ANY_NODE if it can match any kind of node. */ short getMatchType(); /** * For patterns which only match an ATTRIBUTE_NODE or an ELEMENT_NODE then * this pattern may return the name of the element or attribute it matches. * This allows a more efficient rule matching algorithm to be performed, * rather than a brute force approach of evaluating every pattern for a * given Node. * * @return the name of the element or attribute this pattern matches or null * if this pattern matches any or more than one name. */ String getMatchesNodeName(); } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/rule/Rule.java0000644000175000017500000002254210242120003020106 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.rule; import org.dom4j.Node; /** *

* Rule matches against DOM4J Node so that some action can be * performed such as in the XSLT processing model. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public class Rule implements Comparable { /** Holds value of property mode. */ private String mode; /** Holds value of property importPrecedence. */ private int importPrecedence; /** Holds value of property priority. */ private double priority; /** Holds value of property appearenceCount. */ private int appearenceCount; /** Holds value of property pattern. */ private Pattern pattern; /** Holds value of property action. */ private Action action; public Rule() { this.priority = Pattern.DEFAULT_PRIORITY; } public Rule(Pattern pattern) { this.pattern = pattern; this.priority = pattern.getPriority(); } public Rule(Pattern pattern, Action action) { this(pattern); this.action = action; } /** * Constructs a new Rule with the same instance data as the given rule but a * different pattern. * * @param that * DOCUMENT ME! * @param pattern * DOCUMENT ME! */ public Rule(Rule that, Pattern pattern) { this.mode = that.mode; this.importPrecedence = that.importPrecedence; this.priority = that.priority; this.appearenceCount = that.appearenceCount; this.action = that.action; this.pattern = pattern; } public boolean equals(Object that) { if (that instanceof Rule) { return compareTo((Rule) that) == 0; } return false; } public int hashCode() { return importPrecedence + appearenceCount; } public int compareTo(Object that) { if (that instanceof Rule) { return compareTo((Rule) that); } return getClass().getName().compareTo(that.getClass().getName()); } /** * Compares two rules in XSLT processing model order assuming that the modes * are equal. * * @param that * DOCUMENT ME! * * @return DOCUMENT ME! */ public int compareTo(Rule that) { int answer = this.importPrecedence - that.importPrecedence; if (answer == 0) { answer = (int) Math.round(this.priority - that.priority); if (answer == 0) { answer = this.appearenceCount - that.appearenceCount; } } return answer; } public String toString() { return super.toString() + "[ pattern: " + getPattern() + " action: " + getAction() + " ]"; } /** * DOCUMENT ME! * * @param node * DOCUMENT ME! * * @return true if the pattern matches the given DOM4J node. */ public final boolean matches(Node node) { return pattern.matches(node); } /** * If this rule contains a union pattern then this method should return an * array of Rules which describe the union rule, which should contain more * than one rule. Otherwise this method should return null. * * @return an array of the rules which make up this union rule or null if * this rule is not a union rule */ public Rule[] getUnionRules() { Pattern[] patterns = pattern.getUnionPatterns(); if (patterns == null) { return null; } int size = patterns.length; Rule[] answer = new Rule[size]; for (int i = 0; i < size; i++) { answer[i] = new Rule(this, patterns[i]); } return answer; } /** * DOCUMENT ME! * * @return the type of node the pattern matches which by default should * return ANY_NODE if it can match any kind of node. */ public final short getMatchType() { return pattern.getMatchType(); } /** * For patterns which only match an ATTRIBUTE_NODE or an ELEMENT_NODE then * this pattern may return the name of the element or attribute it matches. * This allows a more efficient rule matching algorithm to be performed, * rather than a brute force approach of evaluating every pattern for a * given Node. * * @return the name of the element or attribute this pattern matches or null * if this pattern matches any or more than one name. */ public final String getMatchesNodeName() { return pattern.getMatchesNodeName(); } /** * Getter for property mode. * * @return Value of property mode. */ public String getMode() { return mode; } /** * Setter for property mode. * * @param mode * New value of property mode. */ public void setMode(String mode) { this.mode = mode; } /** * Getter for property importPrecedence. * * @return Value of property importPrecedence. */ public int getImportPrecedence() { return importPrecedence; } /** * Setter for property importPrecedence. * * @param importPrecedence * New value of property importPrecedence. */ public void setImportPrecedence(int importPrecedence) { this.importPrecedence = importPrecedence; } /** * Getter for property priority. * * @return Value of property priority. */ public double getPriority() { return priority; } /** * Setter for property priority. * * @param priority * New value of property priority. */ public void setPriority(double priority) { this.priority = priority; } /** * Getter for property appearenceCount. * * @return Value of property appearenceCount. */ public int getAppearenceCount() { return appearenceCount; } /** * Setter for property appearenceCount. * * @param appearenceCount * New value of property appearenceCount. */ public void setAppearenceCount(int appearenceCount) { this.appearenceCount = appearenceCount; } /** * Getter for property pattern. * * @return Value of property pattern. */ public Pattern getPattern() { return pattern; } /** * Setter for property pattern. * * @param pattern * New value of property pattern. */ public void setPattern(Pattern pattern) { this.pattern = pattern; } /** * Getter for property action. * * @return Value of property action. */ public Action getAction() { return action; } /** * Setter for property action. * * @param action * New value of property action. */ public void setAction(Action action) { this.action = action; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/rule/pattern/0000755000175000017500000000000012133227266020030 5ustar ebourgebourgdom4j-1.6.1/src/java/org/dom4j/rule/pattern/NodeTypePattern.java0000644000175000017500000000776310242120023023753 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.rule.pattern; import org.dom4j.Node; import org.dom4j.rule.Pattern; /** *

* NodeTypePattern implements a Pattern which matches any node of * the given node type. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public class NodeTypePattern implements Pattern { /** A pattern which matches any Attribute node */ public static final NodeTypePattern ANY_ATTRIBUTE = new NodeTypePattern( Node.ATTRIBUTE_NODE); /** A pattern which matches any Comment node */ public static final NodeTypePattern ANY_COMMENT = new NodeTypePattern( Node.COMMENT_NODE); /** A pattern which matches any Document node */ public static final NodeTypePattern ANY_DOCUMENT = new NodeTypePattern( Node.DOCUMENT_NODE); /** A pattern which matches any Element node */ public static final NodeTypePattern ANY_ELEMENT = new NodeTypePattern( Node.ELEMENT_NODE); /** A pattern which matches any ProcessingInstruction node */ public static final NodeTypePattern ANY_PROCESSING_INSTRUCTION = new NodeTypePattern(Node.PROCESSING_INSTRUCTION_NODE); /** A pattern which matches any Text node */ public static final NodeTypePattern ANY_TEXT = new NodeTypePattern( Node.TEXT_NODE); private short nodeType; public NodeTypePattern(short nodeType) { this.nodeType = nodeType; } public boolean matches(Node node) { return node.getNodeType() == nodeType; } public double getPriority() { return Pattern.DEFAULT_PRIORITY; } public Pattern[] getUnionPatterns() { return null; } public short getMatchType() { return nodeType; } public String getMatchesNodeName() { return null; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/rule/pattern/DefaultPattern.java0000644000175000017500000000652110242120020023574 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.rule.pattern; import org.dom4j.Node; import org.dom4j.NodeFilter; import org.dom4j.rule.Pattern; /** *

* DefaultPattern a default implementation of Pattern which can * take any XPath implementation or NodeFilter for defining the pattern. * WARNING this implementation causes a worst case, brute force XSLT * rule evaluation to be performed. Wherever possible the methods {@link * #getPriority}, {@link #getMatchType}and {@link #getMatchesNodeName}should * be overloaded to allow more rule filtering to occur. *

* * @author James Strachan * @version $Revision: 1.6 $ */ public class DefaultPattern implements Pattern { private NodeFilter filter; public DefaultPattern(NodeFilter filter) { this.filter = filter; } public boolean matches(Node node) { return filter.matches(node); } public double getPriority() { return Pattern.DEFAULT_PRIORITY; } public Pattern[] getUnionPatterns() { return null; } public short getMatchType() { return ANY_NODE; } public String getMatchesNodeName() { return null; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/rule/NullAction.java0000644000175000017500000000506710242120015021255 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.rule; import org.dom4j.Node; /** *

* NullAction represents an empty action that does nothing. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public class NullAction implements Action { /** Singleton instance */ public static final NullAction SINGLETON = new NullAction(); public void run(Node node) throws Exception { } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/rule/RuleManager.java0000644000175000017500000001664410242120020021406 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.rule; import java.util.HashMap; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.rule.pattern.NodeTypePattern; /** *

* RuleManager manages a set of rules such that a rule can be * found for a given DOM4J Node using the XSLT processing model. *

* * @author James Strachan * @version $Revision: 1.9 $ */ public class RuleManager { /** Map of modes indexed by mode */ private HashMap modes = new HashMap(); /** * A counter so that rules can be ordered by the order in which they were * added to the rule base */ private int appearenceCount; /** Holds value of property valueOfAction. */ private Action valueOfAction; public RuleManager() { } /** * DOCUMENT ME! * * @param modeName * DOCUMENT ME! * * @return the Mode instance for the given mode name. If one does not exist * then it will be created. */ public Mode getMode(String modeName) { Mode mode = (Mode) modes.get(modeName); if (mode == null) { mode = createMode(); modes.put(modeName, mode); } return mode; } public void addRule(Rule rule) { rule.setAppearenceCount(++appearenceCount); Mode mode = getMode(rule.getMode()); Rule[] childRules = rule.getUnionRules(); if (childRules != null) { for (int i = 0, size = childRules.length; i < size; i++) { mode.addRule(childRules[i]); } } else { mode.addRule(rule); } } public void removeRule(Rule rule) { Mode mode = getMode(rule.getMode()); Rule[] childRules = rule.getUnionRules(); if (childRules != null) { for (int i = 0, size = childRules.length; i < size; i++) { mode.removeRule(childRules[i]); } } else { mode.removeRule(rule); } } /** * Performs an XSLT processing model match for the rule which matches the * given Node the best. * * @param modeName * is the name of the mode associated with the rule if any * @param node * is the DOM4J Node to match against * * @return the matching Rule or no rule if none matched */ public Rule getMatchingRule(String modeName, Node node) { Mode mode = (Mode) modes.get(modeName); if (mode != null) { return mode.getMatchingRule(node); } else { System.out.println("Warning: No Mode for mode: " + mode); return null; } } public void clear() { modes.clear(); appearenceCount = 0; } // Properties // ------------------------------------------------------------------------- /** * DOCUMENT ME! * * @return the default value-of action which is used in the default rules * for the pattern "text()|@" */ public Action getValueOfAction() { return valueOfAction; } /** * Sets the default value-of action which is used in the default rules for * the pattern "text()|@" * * @param valueOfAction * DOCUMENT ME! */ public void setValueOfAction(Action valueOfAction) { this.valueOfAction = valueOfAction; } // Implementation methods // ------------------------------------------------------------------------- /** * A factory method to return a new {@link Mode}instance which should add * the necessary default rules * * @return DOCUMENT ME! */ protected Mode createMode() { Mode mode = new Mode(); addDefaultRules(mode); return mode; } /** * Adds the default stylesheet rules to the given {@link Mode}instance * * @param mode * DOCUMENT ME! */ protected void addDefaultRules(final Mode mode) { // add an apply templates rule Action applyTemplates = new Action() { public void run(Node node) throws Exception { if (node instanceof Element) { mode.applyTemplates((Element) node); } else if (node instanceof Document) { mode.applyTemplates((Document) node); } } }; Action valueOf = getValueOfAction(); addDefaultRule(mode, NodeTypePattern.ANY_DOCUMENT, applyTemplates); addDefaultRule(mode, NodeTypePattern.ANY_ELEMENT, applyTemplates); if (valueOf != null) { addDefaultRule(mode, NodeTypePattern.ANY_ATTRIBUTE, valueOf); addDefaultRule(mode, NodeTypePattern.ANY_TEXT, valueOf); } } protected void addDefaultRule(Mode mode, Pattern pattern, Action action) { Rule rule = createDefaultRule(pattern, action); mode.addRule(rule); } protected Rule createDefaultRule(Pattern pattern, Action action) { Rule rule = new Rule(pattern, action); rule.setImportPrecedence(-1); return rule; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/rule/Mode.java0000644000175000017500000002324610242120005020067 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.rule; import java.util.HashMap; import java.util.Map; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Node; /** *

* Mode manages a number of RuleSet instances for the mode in a * stylesheet. It is responsible for finding the correct rule for a given DOM4J * Node using the XSLT processing model uses the smallest possible RuleSet to * reduce the number of Rule evaluations. *

* * @author James Strachan * @version $Revision: 1.9 $ */ public class Mode { private RuleSet[] ruleSets = new RuleSet[Pattern.NUMBER_OF_TYPES]; /** Map of exact (local) element names to RuleSet instances */ private Map elementNameRuleSets; /** Map of exact (local) attribute names to RuleSet instances */ private Map attributeNameRuleSets; public Mode() { } /** * Runs the actions associated with the given node * * @param node * DOCUMENT ME! * * @throws Exception * DOCUMENT ME! */ public void fireRule(Node node) throws Exception { if (node != null) { Rule rule = getMatchingRule(node); if (rule != null) { Action action = rule.getAction(); if (action != null) { action.run(node); } } } } public void applyTemplates(Element element) throws Exception { for (int i = 0, size = element.attributeCount(); i < size; i++) { Attribute attribute = element.attribute(i); fireRule(attribute); } for (int i = 0, size = element.nodeCount(); i < size; i++) { Node node = element.node(i); fireRule(node); } } public void applyTemplates(Document document) throws Exception { for (int i = 0, size = document.nodeCount(); i < size; i++) { Node node = document.node(i); fireRule(node); } } public void addRule(Rule rule) { int matchType = rule.getMatchType(); String name = rule.getMatchesNodeName(); if (name != null) { if (matchType == Node.ELEMENT_NODE) { elementNameRuleSets = addToNameMap(elementNameRuleSets, name, rule); } else if (matchType == Node.ATTRIBUTE_NODE) { attributeNameRuleSets = addToNameMap(attributeNameRuleSets, name, rule); } } if (matchType >= Pattern.NUMBER_OF_TYPES) { matchType = Pattern.ANY_NODE; } if (matchType == Pattern.ANY_NODE) { // add rule to all other RuleSets if they exist for (int i = 1, size = ruleSets.length; i < size; i++) { RuleSet ruleSet = ruleSets[i]; if (ruleSet != null) { ruleSet.addRule(rule); } } } getRuleSet(matchType).addRule(rule); } public void removeRule(Rule rule) { int matchType = rule.getMatchType(); String name = rule.getMatchesNodeName(); if (name != null) { if (matchType == Node.ELEMENT_NODE) { removeFromNameMap(elementNameRuleSets, name, rule); } else if (matchType == Node.ATTRIBUTE_NODE) { removeFromNameMap(attributeNameRuleSets, name, rule); } } if (matchType >= Pattern.NUMBER_OF_TYPES) { matchType = Pattern.ANY_NODE; } getRuleSet(matchType).removeRule(rule); if (matchType != Pattern.ANY_NODE) { getRuleSet(Pattern.ANY_NODE).removeRule(rule); } } /** * Performs an XSLT processing model match for the rule which matches the * given Node the best. * * @param node * is the DOM4J Node to match against * * @return the matching Rule or no rule if none matched */ public Rule getMatchingRule(Node node) { int matchType = node.getNodeType(); if (matchType == Node.ELEMENT_NODE) { if (elementNameRuleSets != null) { String name = node.getName(); RuleSet ruleSet = (RuleSet) elementNameRuleSets.get(name); if (ruleSet != null) { Rule answer = ruleSet.getMatchingRule(node); if (answer != null) { return answer; } } } } else if (matchType == Node.ATTRIBUTE_NODE) { if (attributeNameRuleSets != null) { String name = node.getName(); RuleSet ruleSet = (RuleSet) attributeNameRuleSets.get(name); if (ruleSet != null) { Rule answer = ruleSet.getMatchingRule(node); if (answer != null) { return answer; } } } } if ((matchType < 0) || (matchType >= ruleSets.length)) { matchType = Pattern.ANY_NODE; } Rule answer = null; RuleSet ruleSet = ruleSets[matchType]; if (ruleSet != null) { // try rules that match this kind of node first answer = ruleSet.getMatchingRule(node); } if ((answer == null) && (matchType != Pattern.ANY_NODE)) { // try general rules that match any kind of node ruleSet = ruleSets[Pattern.ANY_NODE]; if (ruleSet != null) { answer = ruleSet.getMatchingRule(node); } } return answer; } /** * DOCUMENT ME! * * @param matchType * DOCUMENT ME! * * @return the RuleSet for the given matching type. This method will never * return null, a new instance will be created. */ protected RuleSet getRuleSet(int matchType) { RuleSet ruleSet = ruleSets[matchType]; if (ruleSet == null) { ruleSet = new RuleSet(); ruleSets[matchType] = ruleSet; // add the patterns that match any node if (matchType != Pattern.ANY_NODE) { RuleSet allRules = ruleSets[Pattern.ANY_NODE]; if (allRules != null) { ruleSet.addAll(allRules); } } } return ruleSet; } /** * Adds the Rule to a RuleSet for the given name. * * @param map * DOCUMENT ME! * @param name * DOCUMENT ME! * @param rule * DOCUMENT ME! * * @return the Map (which will be created if the given map was null */ protected Map addToNameMap(Map map, String name, Rule rule) { if (map == null) { map = new HashMap(); } RuleSet ruleSet = (RuleSet) map.get(name); if (ruleSet == null) { ruleSet = new RuleSet(); map.put(name, ruleSet); } ruleSet.addRule(rule); return map; } protected void removeFromNameMap(Map map, String name, Rule rule) { if (map != null) { RuleSet ruleSet = (RuleSet) map.get(name); if (ruleSet != null) { ruleSet.removeRule(rule); } } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/rule/RuleSet.java0000644000175000017500000001101410242120013020553 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.rule; import java.util.ArrayList; import java.util.Collections; import org.dom4j.Node; /** *

* RuleSet manages a set of rules which are sorted in order of * relevance according to the XSLT defined conflict resolution policy. This * makes finding the correct rule for a DOM4J Node using the XSLT processing * model efficient as the rules can be evaluated in order of priority. *

* * @author James Strachan * @version $Revision: 1.10 $ */ public class RuleSet { /** An unordered list of Rule objects */ private ArrayList rules = new ArrayList(); /** A lazily evaluated and cached array of rules sorted */ private Rule[] ruleArray; public RuleSet() { } public String toString() { return super.toString() + " [RuleSet: " + rules + " ]"; } /** * Performs an XSLT processing model match for the rule which matches the * given Node the best. * * @param node * is the DOM4J Node to match against * * @return the matching Rule or no rule if none matched */ public Rule getMatchingRule(Node node) { Rule[] matches = getRuleArray(); for (int i = matches.length - 1; i >= 0; i--) { Rule rule = matches[i]; if (rule.matches(node)) { return rule; } } return null; } public void addRule(Rule rule) { rules.add(rule); ruleArray = null; } public void removeRule(Rule rule) { rules.remove(rule); ruleArray = null; } /** * Adds all the rules to this RuleSet from the given other rule set. * * @param that * DOCUMENT ME! */ public void addAll(RuleSet that) { rules.addAll(that.rules); ruleArray = null; } /** * Returns an array of sorted rules. * * @return the rules as a sorted array in ascending precendence so that the * rules at the end of the array should be used first */ protected Rule[] getRuleArray() { if (ruleArray == null) { Collections.sort(rules); int size = rules.size(); ruleArray = new Rule[size]; rules.toArray(ruleArray); } return ruleArray; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/rule/package.html0000644000175000017500000000061310242120017020615 0ustar ebourgebourg

A {@link org.dom4j.rule.Pattern} based XML rule engine which implements the full XSLT processing model while allowing any {@link org.dom4j.rule.Action} to be fired if a pattern matches. This package can be used as a the base for a full XSLT implementation or alternatives, such as a JSP custom tag implementation of XSLT.

dom4j-1.6.1/src/java/org/dom4j/Namespace.java0000644000175000017500000001743310242120003020127 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import org.dom4j.tree.AbstractNode; import org.dom4j.tree.DefaultNamespace; import org.dom4j.tree.NamespaceCache; /** *

* Namespace is a Flyweight Namespace that can be shared amongst * nodes. *

* * @author James Strachan * @version $Revision: 1.22 $ */ public class Namespace extends AbstractNode { /** Cache of Namespace instances */ protected static final NamespaceCache CACHE = new NamespaceCache(); /** XML Namespace */ public static final Namespace XML_NAMESPACE = CACHE.get("xml", "http://www.w3.org/XML/1998/namespace"); /** No Namespace present */ public static final Namespace NO_NAMESPACE = CACHE.get("", ""); /** The prefix mapped to this namespace */ private String prefix; /** The URI for this namespace */ private String uri; /** A cached version of the hashcode for efficiency */ private int hashCode; /** * DOCUMENT ME! * * @param prefix * is the prefix for this namespace * @param uri * is the URI for this namespace */ public Namespace(String prefix, String uri) { this.prefix = (prefix != null) ? prefix : ""; this.uri = (uri != null) ? uri : ""; } /** * A helper method to return the Namespace instance for the given prefix and * URI * * @param prefix * DOCUMENT ME! * @param uri * DOCUMENT ME! * * @return an interned Namespace object */ public static Namespace get(String prefix, String uri) { return CACHE.get(prefix, uri); } /** * A helper method to return the Namespace instance for no prefix and the * URI * * @param uri * DOCUMENT ME! * * @return an interned Namespace object */ public static Namespace get(String uri) { return CACHE.get(uri); } public short getNodeType() { return NAMESPACE_NODE; } /** * DOCUMENT ME! * * @return the hash code based on the qualified name and the URI of the * namespace. */ public int hashCode() { if (hashCode == 0) { hashCode = createHashCode(); } return hashCode; } /** * Factory method to create the hashcode allowing derived classes to change * the behaviour * * @return DOCUMENT ME! */ protected int createHashCode() { int result = uri.hashCode() ^ prefix.hashCode(); if (result == 0) { result = 0xbabe; } return result; } /** * Checks whether this Namespace equals the given Namespace. Two Namespaces * are equals if their URI and prefix are equal. * * @param object * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean equals(Object object) { if (this == object) { return true; } else if (object instanceof Namespace) { Namespace that = (Namespace) object; // we cache hash codes so this should be quick if (hashCode() == that.hashCode()) { return uri.equals(that.getURI()) && prefix.equals(that.getPrefix()); } } return false; } public String getText() { return uri; } public String getStringValue() { return uri; } /** * DOCUMENT ME! * * @return the prefix for this Namespace. */ public String getPrefix() { return prefix; } /** * DOCUMENT ME! * * @return the URI for this Namespace. */ public String getURI() { return uri; } public String getXPathNameStep() { if ((prefix != null) && !"".equals(prefix)) { return "namespace::" + prefix; } return "namespace::*[name()='']"; } public String getPath(Element context) { StringBuffer path = new StringBuffer(10); Element parent = getParent(); if ((parent != null) && (parent != context)) { path.append(parent.getPath(context)); path.append('/'); } path.append(getXPathNameStep()); return path.toString(); } public String getUniquePath(Element context) { StringBuffer path = new StringBuffer(10); Element parent = getParent(); if ((parent != null) && (parent != context)) { path.append(parent.getUniquePath(context)); path.append('/'); } path.append(getXPathNameStep()); return path.toString(); } public String toString() { return super.toString() + " [Namespace: prefix " + getPrefix() + " mapped to URI \"" + getURI() + "\"]"; } public String asXML() { StringBuffer asxml = new StringBuffer(10); String pref = getPrefix(); if ((pref != null) && (pref.length() > 0)) { asxml.append("xmlns:"); asxml.append(pref); asxml.append("=\""); } else { asxml.append("xmlns=\""); } asxml.append(getURI()); asxml.append("\""); return asxml.toString(); } public void accept(Visitor visitor) { visitor.visit(this); } protected Node createXPathResult(Element parent) { return new DefaultNamespace(parent, getPrefix(), getURI()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/ProcessingInstruction.java0000644000175000017500000000726110242120014022611 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import java.util.Map; /** *

* ProcessingInstruction defines an XML processing instruction. * The {@link Node#getName}method will return the target of the PI and the * {@link Node#getText}method will return the data from all of the * instructions. *

* * @author James Strachan * @version $Revision: 1.10 $ */ public interface ProcessingInstruction extends Node { /** * This method is the equivalent to the {@link #getName}method. It is added * for clarity. * * @return the target of this PI */ String getTarget(); /** * This method is the equivalent to the {@link #setName}method. It is added * for clarity. * * @param target * DOCUMENT ME! */ void setTarget(String target); /** * DOCUMENT ME! * * @return the text for all the data associated with the processing * instruction */ String getText(); /** *

* Returns the value of a specific name in the PI. *

* * @param name * is the name of the attribute to lookup. * * @return the value of the named attribute */ String getValue(String name); /** * DOCUMENT ME! * * @return the values for this processing instruction as a Map */ Map getValues(); void setValue(String name, String value); void setValues(Map data); boolean removeValue(String name); } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/XPath.java0000644000175000017500000002733510242120014017263 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import java.util.List; import java.util.Map; import org.jaxen.FunctionContext; import org.jaxen.NamespaceContext; import org.jaxen.VariableContext; /** *

* XPath represents an XPath expression after it has been parsed * from a String. *

* * @author James Strachan * @version $Revision: 1.20 $ */ public interface XPath extends NodeFilter { /** *

* getText will return the textual version of the XPath * expression. *

* * @return the textual format of the XPath expression. */ String getText(); /** *

* matches returns true if the given node matches the XPath * expression. To be more precise when evaluating this XPath expression on * the given node the result set must include the node. *

* * @param node * DOCUMENT ME! * * @return true if the given node matches this XPath expression */ boolean matches(Node node); /** *

* evaluate evaluates an XPath expression and returns the * result as an {@link Object}. The object returned can either be a {@link * List} of {@link Node}instances, a {@link Node}instance, a {@link * String} or a {@link Number}instance depending on the XPath expression. *

* * @param context * is either a node or a list of nodes on which to evalute the * XPath * * @return the value of the XPath expression as a {@link List}of {@link * Node} instances, a {@link Node}instance, a {@link String}or a * {@link Number}instance depending on the XPath expression. */ Object evaluate(Object context); /** *

* selectObject evaluates an XPath expression and returns the * result as an {@link Object}. The object returned can either be a {@link * List} of {@link Node}instances, a {@link Node}instance, a {@link * String} or a {@link Number}instance depending on the XPath expression. *

* * @param context * is either a node or a list of nodes on which to evalute the * XPath * * @return the value of the XPath expression as a {@link List}of {@link * Node} instances, a {@link Node}instance, a {@link String}or a * {@link Number}instance depending on the XPath expression. * * @deprecated please use evaluate(Object) instead. WILL BE REMOVED IN * dom4j-1.6 !! */ Object selectObject(Object context); /** *

* selectNodes performs this XPath expression on the given * {@link Node}or {@link List}of {@link Node}s instances appending all * the results together into a single list. *

* * @param context * is either a node or a list of nodes on which to evalute the * XPath * * @return the results of all the XPath evaluations as a single list */ List selectNodes(Object context); /** *

* selectNodes evaluates the XPath expression on the given * {@link Node}or {@link List}of {@link Node}s and returns the result as * a List of Node s sorted by the sort XPath * expression. *

* * @param context * is either a node or a list of nodes on which to evalute the * XPath * @param sortXPath * is the XPath expression to sort by * * @return a list of Node instances */ List selectNodes(Object context, XPath sortXPath); /** *

* selectNodes evaluates the XPath expression on the given * {@link Node}or {@link List}of {@link Node}s and returns the result as * a List of Node s sorted by the sort XPath * expression. *

* * @param context * is either a node or a list of nodes on which to evalute the * XPath * @param sortXPath * is the XPath expression to sort by * @param distinct * specifies whether or not duplicate values of the sort * expression are allowed. If this parameter is true then only * distinct sort expressions values are included in the result * * @return a list of Node instances */ List selectNodes(Object context, XPath sortXPath, boolean distinct); /** *

* selectSingleNode evaluates this XPath expression on the * given {@link Node}or {@link List}of {@link Node}s and returns the * result as a single Node instance. *

* * @param context * is either a node or a list of nodes on which to evalute the * XPath * * @return a single matching Node instance */ Node selectSingleNode(Object context); /** *

* valueOf evaluates this XPath expression and returns the * textual representation of the results using the XPath string() function. *

* * @param context * is either a node or a list of nodes on which to evalute the * XPath * * @return the string representation of the results of the XPath expression */ String valueOf(Object context); /** *

* numberValueOf evaluates an XPath expression and returns * the numeric value of the XPath expression if the XPath expression results * is a number, or null if the result is not a number. *

* * @param context * is either a node or a list of nodes on which to evalute the * XPath * * @return the numeric result of the XPath expression or null if the result * is not a number. */ Number numberValueOf(Object context); /** * Retrieve a boolean-value interpretation of this XPath expression when * evaluated against a given context. * *

* The boolean-value of the expression is determined per the * boolean(..) core function as defined in the XPath * specification. This means that an expression that selects zero nodes will * return false, while an expression that selects * one-or-more nodes will return true. *

* * @param context * The node, nodeset or Context object for evaluation. This value * can be null * * @return The boolean-value interpretation of this expression. * * @since 1.5 */ boolean booleanValueOf(Object context); /** *

* sort sorts the given List of Nodes using this XPath * expression as a {@link java.util.Comparator}. *

* * @param list * is the list of Nodes to sort */ void sort(List list); /** *

* sort sorts the given List of Nodes using this XPath * expression as a {@link java.util.Comparator}and optionally removing * duplicates. *

* * @param list * is the list of Nodes to sort * @param distinct * if true then duplicate values (using the sortXPath for * comparisions) will be removed from the List */ void sort(List list, boolean distinct); /** * DOCUMENT ME! * * @return the current function context */ FunctionContext getFunctionContext(); /** * Sets the function context to be used when evaluating XPath expressions * * @param functionContext * DOCUMENT ME! */ void setFunctionContext(FunctionContext functionContext); /** * DOCUMENT ME! * * @return the current namespace context */ NamespaceContext getNamespaceContext(); /** * Sets the namespace context to be used when evaluating XPath expressions * * @param namespaceContext * DOCUMENT ME! */ void setNamespaceContext(NamespaceContext namespaceContext); /** *

* Sets the current NamespaceContext from a Map where the keys are the * String namespace prefixes and the values are the namespace URIs. *

* *

* For example: * *

     * Map uris = new HashMap();
     * uris.put("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/");
     * uris.put("m", "urn:xmethodsBabelFish");
     * XPath xpath = document
     *         .createXPath("SOAP-ENV:Envelope/SOAP-ENV:Body/m:BabelFish");
     * xpath.setNamespaceURIs(uris);
     * Node babelfish = xpath.selectSingleNode(document);
     * 
* *

* * @param map * the map containing the namespace mappings */ void setNamespaceURIs(Map map); /** * DOCUMENT ME! * * @return the current variable context */ VariableContext getVariableContext(); /** * Sets the variable context to be used when evaluating XPath expressions * * @param variableContext * DOCUMENT ME! */ void setVariableContext(VariableContext variableContext); } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/Visitor.java0000644000175000017500000001207310242120016017671 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; /** *

* Visitor is used to implement the Visitor * pattern in DOM4J. An object of this interface can be passed to a * Node which will then call its typesafe methods. Please refer * to the Gang of Four book of Design Patterns for more details on the * Visitor pattern. *

* *

* This site * has further discussion on design patterns and links to the GOF book. This link describes the * Visitor pattern in detail. *

* * @author James Strachan * @version $Revision: 1.8 $ */ public interface Visitor { /** *

* Visits the given Document *

* * @param document * is the Document node to visit. */ void visit(Document document); /** *

* Visits the given DocumentType *

* * @param documentType * is the DocumentType node to visit. */ void visit(DocumentType documentType); /** *

* Visits the given Element *

* * @param node * is the Element node to visit. */ void visit(Element node); /** *

* Visits the given Attribute *

* * @param node * is the Attribute node to visit. */ void visit(Attribute node); /** *

* Visits the given CDATA *

* * @param node * is the CDATA node to visit. */ void visit(CDATA node); /** *

* Visits the given Comment *

* * @param node * is the Comment node to visit. */ void visit(Comment node); /** *

* Visits the given Entity *

* * @param node * is the Entity node to visit. */ void visit(Entity node); /** *

* Visits the given Namespace *

* * @param namespace * is the Namespace node to visit. */ void visit(Namespace namespace); /** *

* Visits the given ProcessingInstruction *

* * @param node * is the ProcessingInstruction node to visit. */ void visit(ProcessingInstruction node); /** *

* Visits the given Text *

* * @param node * is the Text node to visit. */ void visit(Text node); } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/0000755000175000017500000000000012133227266016013 5ustar ebourgebourgdom4j-1.6.1/src/java/org/dom4j/io/XMLResult.java0000644000175000017500000000745610242120016020511 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.io.Writer; import javax.xml.transform.sax.SAXResult; import org.xml.sax.ContentHandler; import org.xml.sax.ext.LexicalHandler; /** *

* XMLResult implements a JAXP {@link SAXResult}for an output * stream with support for pretty printing and control over how the XML is * formatted. *

* * @author James Strachan * @version $Revision: 1.9 $ */ public class XMLResult extends SAXResult { private XMLWriter xmlWriter; public XMLResult() { this(new XMLWriter()); } public XMLResult(Writer writer) { this(new XMLWriter(writer)); } public XMLResult(Writer writer, OutputFormat format) { this(new XMLWriter(writer, format)); } public XMLResult(OutputStream out) throws UnsupportedEncodingException { this(new XMLWriter(out)); } public XMLResult(OutputStream out, OutputFormat format) throws UnsupportedEncodingException { this(new XMLWriter(out, format)); } public XMLResult(XMLWriter xmlWriter) { super(xmlWriter); this.xmlWriter = xmlWriter; setLexicalHandler(xmlWriter); } public XMLWriter getXMLWriter() { return xmlWriter; } public void setXMLWriter(XMLWriter writer) { this.xmlWriter = writer; setHandler(xmlWriter); setLexicalHandler(xmlWriter); } public ContentHandler getHandler() { return xmlWriter; } public LexicalHandler getLexicalHandler() { return xmlWriter; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/SAXReader.java0000644000175000017500000010237010242120015020416 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.Reader; import java.io.Serializable; import java.net.URL; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentFactory; import org.dom4j.ElementHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; /** *

* SAXReader creates a DOM4J tree from SAX parsing events. *

* *

* The actual SAX parser that is used by this class is configurable so you can * use your favourite SAX parser if you wish. DOM4J comes configured with its * own SAX parser so you do not need to worry about configuring the SAX parser. *

* *

* To explicitly configure the SAX parser that is used via Java code you can use * a constructor or use the {@link #setXMLReader(XMLReader)}or {@link * #setXMLReaderClassName(String)} methods. *

* *

* If the parser is not specified explicitly then the standard SAX policy of * using the org.xml.sax.driver system property is used to * determine the implementation class of {@link XMLReader}. *

* *

* If the org.xml.sax.driver system property is not defined then * JAXP is used via reflection (so that DOM4J is not explicitly dependent on the * JAXP classes) to load the JAXP configured SAXParser. If there is any error * creating a JAXP SAXParser an informational message is output and then the * default (Aelfred) SAX parser is used instead. *

* *

* If you are trying to use JAXP to explicitly set your SAX parser and are * experiencing problems, you can turn on verbose error reporting by defining * the system property org.dom4j.verbose to be "true" which will * output a more detailed description of why JAXP could not find a SAX parser *

* *

* For more information on JAXP please go to Sun's Java & XML site *

* * @author James Strachan * @version $Revision: 1.58 $ */ public class SAXReader { private static final String SAX_STRING_INTERNING = "http://xml.org/sax/features/string-interning"; private static final String SAX_NAMESPACE_PREFIXES = "http://xml.org/sax/features/namespace-prefixes"; private static final String SAX_NAMESPACES = "http://xml.org/sax/features/namespaces"; private static final String SAX_DECL_HANDLER = "http://xml.org/sax/properties/declaration-handler"; private static final String SAX_LEXICAL_HANDLER = "http://xml.org/sax/properties/lexical-handler"; private static final String SAX_LEXICALHANDLER = "http://xml.org/sax/handlers/LexicalHandler"; /** DocumentFactory used to create new document objects */ private DocumentFactory factory; /** XMLReader used to parse the SAX events */ private XMLReader xmlReader; /** Whether validation should occur */ private boolean validating; /** DispatchHandler to call when each Element is encountered */ private DispatchHandler dispatchHandler; /** ErrorHandler class to use */ private ErrorHandler errorHandler; /** The entity resolver */ private EntityResolver entityResolver; /** Should element & attribute names and namespace URIs be interned? */ private boolean stringInternEnabled = true; /** Should internal DTD declarations be expanded into a List in the DTD */ private boolean includeInternalDTDDeclarations = false; /** Should external DTD declarations be expanded into a List in the DTD */ private boolean includeExternalDTDDeclarations = false; /** Whether adjacent text nodes should be merged */ private boolean mergeAdjacentText = false; /** Holds value of property stripWhitespaceText. */ private boolean stripWhitespaceText = false; /** Should we ignore comments */ private boolean ignoreComments = false; /** Encoding of InputSource - null means system default encoding */ private String encoding = null; // private boolean includeExternalGeneralEntities = false; // private boolean includeExternalParameterEntities = false; /** The SAX filter used to filter SAX events */ private XMLFilter xmlFilter; public SAXReader() { } public SAXReader(boolean validating) { this.validating = validating; } public SAXReader(DocumentFactory factory) { this.factory = factory; } public SAXReader(DocumentFactory factory, boolean validating) { this.factory = factory; this.validating = validating; } public SAXReader(XMLReader xmlReader) { this.xmlReader = xmlReader; } public SAXReader(XMLReader xmlReader, boolean validating) { this.xmlReader = xmlReader; this.validating = validating; } public SAXReader(String xmlReaderClassName) throws SAXException { if (xmlReaderClassName != null) { this.xmlReader = XMLReaderFactory .createXMLReader(xmlReaderClassName); } } public SAXReader(String xmlReaderClassName, boolean validating) throws SAXException { if (xmlReaderClassName != null) { this.xmlReader = XMLReaderFactory .createXMLReader(xmlReaderClassName); } this.validating = validating; } /** * Allows a SAX property to be set on the underlying SAX parser. This can be * useful to set parser-specific properties such as the location of schema * or DTD resources. Though use this method with caution as it has the * possibility of breaking the standard behaviour. An alternative to calling * this method is to correctly configure an XMLReader object instance and * call the {@link #setXMLReader(XMLReader)}method * * @param name * is the SAX property name * @param value * is the value of the SAX property * * @throws SAXException * if the XMLReader could not be created or the property could * not be changed. */ public void setProperty(String name, Object value) throws SAXException { getXMLReader().setProperty(name, value); } /** * Sets a SAX feature on the underlying SAX parser. This can be useful to * set parser-specific features. Though use this method with caution as it * has the possibility of breaking the standard behaviour. An alternative to * calling this method is to correctly configure an XMLReader object * instance and call the {@link #setXMLReader(XMLReader)}method * * @param name * is the SAX feature name * @param value * is the value of the SAX feature * * @throws SAXException * if the XMLReader could not be created or the feature could * not be changed. */ public void setFeature(String name, boolean value) throws SAXException { getXMLReader().setFeature(name, value); } /** *

* Reads a Document from the given File *

* * @param file * is the File to read from. * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. */ public Document read(File file) throws DocumentException { try { /* * We cannot convert the file to an URL because if the filename * contains '#' characters, there will be problems with the URL in * the InputSource (because a URL like * http://myhost.com/index#anchor is treated the same as * http://myhost.com/index) Thanks to Christian Oetterli */ InputSource source = new InputSource(new FileInputStream(file)); if (this.encoding != null) { source.setEncoding(this.encoding); } String path = file.getAbsolutePath(); if (path != null) { // Code taken from Ant FileUtils StringBuffer sb = new StringBuffer("file://"); // add an extra slash for filesystems with drive-specifiers if (!path.startsWith(File.separator)) { sb.append("/"); } path = path.replace('\\', '/'); sb.append(path); source.setSystemId(sb.toString()); } return read(source); } catch (FileNotFoundException e) { throw new DocumentException(e.getMessage(), e); } } /** *

* Reads a Document from the given URL using SAX *

* * @param url * URL to read from. * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. */ public Document read(URL url) throws DocumentException { String systemID = url.toExternalForm(); InputSource source = new InputSource(systemID); if (this.encoding != null) { source.setEncoding(this.encoding); } return read(source); } /** *

* Reads a Document from the given URL or filename using SAX. *

* *

* If the systemId contains a ':' character then it is * assumed to be a URL otherwise its assumed to be a file name. If you want * finer grained control over this mechansim then please explicitly pass in * either a {@link URL}or a {@link File}instance instead of a {@link * String} to denote the source of the document. *

* * @param systemId * is a URL for a document or a file name. * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. */ public Document read(String systemId) throws DocumentException { InputSource source = new InputSource(systemId); if (this.encoding != null) { source.setEncoding(this.encoding); } return read(source); } /** *

* Reads a Document from the given stream using SAX *

* * @param in * InputStream to read from. * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. */ public Document read(InputStream in) throws DocumentException { InputSource source = new InputSource(in); if (this.encoding != null) { source.setEncoding(this.encoding); } return read(source); } /** *

* Reads a Document from the given Reader using SAX *

* * @param reader * is the reader for the input * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. */ public Document read(Reader reader) throws DocumentException { InputSource source = new InputSource(reader); if (this.encoding != null) { source.setEncoding(this.encoding); } return read(source); } /** *

* Reads a Document from the given stream using SAX *

* * @param in * InputStream to read from. * @param systemId * is the URI for the input * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. */ public Document read(InputStream in, String systemId) throws DocumentException { InputSource source = new InputSource(in); source.setSystemId(systemId); if (this.encoding != null) { source.setEncoding(this.encoding); } return read(source); } /** *

* Reads a Document from the given Reader using SAX *

* * @param reader * is the reader for the input * @param systemId * is the URI for the input * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. */ public Document read(Reader reader, String systemId) throws DocumentException { InputSource source = new InputSource(reader); source.setSystemId(systemId); if (this.encoding != null) { source.setEncoding(this.encoding); } return read(source); } /** *

* Reads a Document from the given InputSource using SAX *

* * @param in * InputSource to read from. * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. */ public Document read(InputSource in) throws DocumentException { try { XMLReader reader = getXMLReader(); reader = installXMLFilter(reader); EntityResolver thatEntityResolver = this.entityResolver; if (thatEntityResolver == null) { thatEntityResolver = createDefaultEntityResolver(in .getSystemId()); this.entityResolver = thatEntityResolver; } reader.setEntityResolver(thatEntityResolver); SAXContentHandler contentHandler = createContentHandler(reader); contentHandler.setEntityResolver(thatEntityResolver); contentHandler.setInputSource(in); boolean internal = isIncludeInternalDTDDeclarations(); boolean external = isIncludeExternalDTDDeclarations(); contentHandler.setIncludeInternalDTDDeclarations(internal); contentHandler.setIncludeExternalDTDDeclarations(external); contentHandler.setMergeAdjacentText(isMergeAdjacentText()); contentHandler.setStripWhitespaceText(isStripWhitespaceText()); contentHandler.setIgnoreComments(isIgnoreComments()); reader.setContentHandler(contentHandler); configureReader(reader, contentHandler); reader.parse(in); return contentHandler.getDocument(); } catch (Exception e) { if (e instanceof SAXParseException) { // e.printStackTrace(); SAXParseException parseException = (SAXParseException) e; String systemId = parseException.getSystemId(); if (systemId == null) { systemId = ""; } String message = "Error on line " + parseException.getLineNumber() + " of document " + systemId + " : " + parseException.getMessage(); throw new DocumentException(message, e); } else { throw new DocumentException(e.getMessage(), e); } } } // Properties // ------------------------------------------------------------------------- /** * DOCUMENT ME! * * @return the validation mode, true if validating will be done otherwise * false. */ public boolean isValidating() { return validating; } /** * Sets the validation mode. * * @param validation * indicates whether or not validation should occur. */ public void setValidation(boolean validation) { this.validating = validation; } /** * DOCUMENT ME! * * @return whether internal DTD declarations should be expanded into the * DocumentType object or not. */ public boolean isIncludeInternalDTDDeclarations() { return includeInternalDTDDeclarations; } /** * Sets whether internal DTD declarations should be expanded into the * DocumentType object or not. * * @param include * whether or not DTD declarations should be expanded and * included into the DocumentType object. */ public void setIncludeInternalDTDDeclarations(boolean include) { this.includeInternalDTDDeclarations = include; } /** * DOCUMENT ME! * * @return whether external DTD declarations should be expanded into the * DocumentType object or not. */ public boolean isIncludeExternalDTDDeclarations() { return includeExternalDTDDeclarations; } /** * Sets whether DTD external declarations should be expanded into the * DocumentType object or not. * * @param include * whether or not DTD declarations should be expanded and * included into the DocumentType object. */ public void setIncludeExternalDTDDeclarations(boolean include) { this.includeExternalDTDDeclarations = include; } /** * Sets whether String interning is enabled or disabled for element & * attribute names and namespace URIs. This proprety is enabled by default. * * @return DOCUMENT ME! */ public boolean isStringInternEnabled() { return stringInternEnabled; } /** * Sets whether String interning is enabled or disabled for element & * attribute names and namespace URIs * * @param stringInternEnabled * DOCUMENT ME! */ public void setStringInternEnabled(boolean stringInternEnabled) { this.stringInternEnabled = stringInternEnabled; } /** * Returns whether adjacent text nodes should be merged together. * * @return Value of property mergeAdjacentText. */ public boolean isMergeAdjacentText() { return mergeAdjacentText; } /** * Sets whether or not adjacent text nodes should be merged together when * parsing. * * @param mergeAdjacentText * New value of property mergeAdjacentText. */ public void setMergeAdjacentText(boolean mergeAdjacentText) { this.mergeAdjacentText = mergeAdjacentText; } /** * Sets whether whitespace between element start and end tags should be * ignored * * @return Value of property stripWhitespaceText. */ public boolean isStripWhitespaceText() { return stripWhitespaceText; } /** * Sets whether whitespace between element start and end tags should be * ignored. * * @param stripWhitespaceText * New value of property stripWhitespaceText. */ public void setStripWhitespaceText(boolean stripWhitespaceText) { this.stripWhitespaceText = stripWhitespaceText; } /** * Returns whether we should ignore comments or not. * * @return boolean */ public boolean isIgnoreComments() { return ignoreComments; } /** * Sets whether we should ignore comments or not. * * @param ignoreComments * whether we should ignore comments or not. */ public void setIgnoreComments(boolean ignoreComments) { this.ignoreComments = ignoreComments; } /** * DOCUMENT ME! * * @return the DocumentFactory used to create document * objects */ public DocumentFactory getDocumentFactory() { if (factory == null) { factory = DocumentFactory.getInstance(); } return factory; } /** *

* This sets the DocumentFactory used to create new * documents. This method allows the building of custom DOM4J tree objects * to be implemented easily using a custom derivation of * {@link DocumentFactory} *

* * @param documentFactory * DocumentFactory used to create DOM4J objects */ public void setDocumentFactory(DocumentFactory documentFactory) { this.factory = documentFactory; } /** * DOCUMENT ME! * * @return the ErrorHandler used by SAX */ public ErrorHandler getErrorHandler() { return errorHandler; } /** * Sets the ErrorHandler used by the SAX * XMLReader. * * @param errorHandler * is the ErrorHandler used by SAX */ public void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; } /** * Returns the current entity resolver used to resolve entities * * @return DOCUMENT ME! */ public EntityResolver getEntityResolver() { return entityResolver; } /** * Sets the entity resolver used to resolve entities. * * @param entityResolver * DOCUMENT ME! */ public void setEntityResolver(EntityResolver entityResolver) { this.entityResolver = entityResolver; } /** * DOCUMENT ME! * * @return the XMLReader used to parse SAX events * * @throws SAXException * DOCUMENT ME! */ public XMLReader getXMLReader() throws SAXException { if (xmlReader == null) { xmlReader = createXMLReader(); } return xmlReader; } /** * Sets the XMLReader used to parse SAX events * * @param reader * is the XMLReader to parse SAX events */ public void setXMLReader(XMLReader reader) { this.xmlReader = reader; } /** * Returns encoding used for InputSource (null means system default * encoding) * * @return encoding used for InputSource * */ public String getEncoding() { return encoding; } /** * Sets encoding used for InputSource (null means system default encoding) * * @param encoding * is encoding used for InputSource */ public void setEncoding(String encoding) { this.encoding = encoding; } /** * Sets the class name of the XMLReader to be used to parse * SAX events. * * @param xmlReaderClassName * is the class name of the XMLReader to parse SAX * events * * @throws SAXException * DOCUMENT ME! */ public void setXMLReaderClassName(String xmlReaderClassName) throws SAXException { setXMLReader(XMLReaderFactory.createXMLReader(xmlReaderClassName)); } /** * Adds the ElementHandler to be called when the specified * path is encounted. * * @param path * is the path to be handled * @param handler * is the ElementHandler to be called by the event * based processor. */ public void addHandler(String path, ElementHandler handler) { getDispatchHandler().addHandler(path, handler); } /** * Removes the ElementHandler from the event based processor, * for the specified path. * * @param path * is the path to remove the ElementHandler for. */ public void removeHandler(String path) { getDispatchHandler().removeHandler(path); } /** * When multiple ElementHandler instances have been * registered, this will set a default ElementHandler to be * called for any path which does NOT have a handler registered. * * @param handler * is the ElementHandler to be called by the event * based processor. */ public void setDefaultHandler(ElementHandler handler) { getDispatchHandler().setDefaultHandler(handler); } /** * This method clears out all the existing handlers and default handler * setting things back as if no handler existed. Useful when reusing an * object instance. */ public void resetHandlers() { getDispatchHandler().resetHandlers(); } /** * Returns the SAX filter being used to filter SAX events. * * @return the SAX filter being used or null if no SAX filter is installed */ public XMLFilter getXMLFilter() { return xmlFilter; } /** * Sets the SAX filter to be used when filtering SAX events * * @param filter * is the SAX filter to use or null to disable filtering */ public void setXMLFilter(XMLFilter filter) { this.xmlFilter = filter; } // Implementation methods // ------------------------------------------------------------------------- /** * Installs any XMLFilter objects required to allow the SAX event stream to * be filtered and preprocessed before it gets to dom4j. * * @param reader * DOCUMENT ME! * * @return the new XMLFilter if applicable or the original XMLReader if no * filter is being used. */ protected XMLReader installXMLFilter(XMLReader reader) { XMLFilter filter = getXMLFilter(); if (filter != null) { // find the root XMLFilter XMLFilter root = filter; while (true) { XMLReader parent = root.getParent(); if (parent instanceof XMLFilter) { root = (XMLFilter) parent; } else { break; } } root.setParent(reader); return filter; } return reader; } protected DispatchHandler getDispatchHandler() { if (dispatchHandler == null) { dispatchHandler = new DispatchHandler(); } return dispatchHandler; } protected void setDispatchHandler(DispatchHandler dispatchHandler) { this.dispatchHandler = dispatchHandler; } /** * Factory Method to allow alternate methods of creating and configuring * XMLReader objects * * @return DOCUMENT ME! * * @throws SAXException * DOCUMENT ME! */ protected XMLReader createXMLReader() throws SAXException { return SAXHelper.createXMLReader(isValidating()); } /** * Configures the XMLReader before use * * @param reader * DOCUMENT ME! * @param handler * DOCUMENT ME! * * @throws DocumentException * DOCUMENT ME! */ protected void configureReader(XMLReader reader, DefaultHandler handler) throws DocumentException { // configure lexical handling SAXHelper.setParserProperty(reader, SAX_LEXICALHANDLER, handler); // try alternate property just in case SAXHelper.setParserProperty(reader, SAX_LEXICAL_HANDLER, handler); // register the DeclHandler if (includeInternalDTDDeclarations || includeExternalDTDDeclarations) { SAXHelper.setParserProperty(reader, SAX_DECL_HANDLER, handler); } // configure namespace support SAXHelper.setParserFeature(reader, SAX_NAMESPACES, true); SAXHelper.setParserFeature(reader, SAX_NAMESPACE_PREFIXES, false); // string interning SAXHelper.setParserFeature(reader, SAX_STRING_INTERNING, isStringInternEnabled()); // external entites /* * SAXHelper.setParserFeature( reader, * "http://xml.org/sax/properties/external-general-entities", * includeExternalGeneralEntities ); SAXHelper.setParserFeature( reader, * "http://xml.org/sax/properties/external-parameter-entities", * includeExternalParameterEntities ); */ // use Locator2 if possible SAXHelper.setParserFeature(reader, "http://xml.org/sax/features/use-locator2", true); try { // configure validation support reader.setFeature("http://xml.org/sax/features/validation", isValidating()); if (errorHandler != null) { reader.setErrorHandler(errorHandler); } else { reader.setErrorHandler(handler); } } catch (Exception e) { if (isValidating()) { throw new DocumentException("Validation not supported for" + " XMLReader: " + reader, e); } } } /** * Factory Method to allow user derived SAXContentHandler objects to be used * * @param reader * DOCUMENT ME! * * @return DOCUMENT ME! */ protected SAXContentHandler createContentHandler(XMLReader reader) { return new SAXContentHandler(getDocumentFactory(), dispatchHandler); } protected EntityResolver createDefaultEntityResolver(String systemId) { String prefix = null; if ((systemId != null) && (systemId.length() > 0)) { int idx = systemId.lastIndexOf('/'); if (idx > 0) { prefix = systemId.substring(0, idx + 1); } } return new SAXEntityResolver(prefix); } protected static class SAXEntityResolver implements EntityResolver, Serializable { protected String uriPrefix; public SAXEntityResolver(String uriPrefix) { this.uriPrefix = uriPrefix; } public InputSource resolveEntity(String publicId, String systemId) { // try create a relative URI reader... if ((systemId != null) && (systemId.length() > 0)) { if ((uriPrefix != null) && (systemId.indexOf(':') <= 0)) { systemId = uriPrefix + systemId; } } return new InputSource(systemId); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/HTMLWriter.java0000644000175000017500000007222510242120025020607 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.io.IOException; import java.io.OutputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.Stack; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Entity; import org.dom4j.Node; import org.xml.sax.SAXException; /** *

* HTMLWriter takes a DOM4J tree and formats it to a stream as * HTML. This formatter is similar to XMLWriter but it outputs the text of CDATA * and Entity sections rather than the serialised format as in XML, it has an * XHTML mode, it retains whitespace in certain elements such as <PRE>, * and it supports certain elements which have no corresponding close tag such * as for <BR> and <P>. *

* *

* The OutputFormat passed in to the constructor is checked for isXHTML() and * isExpandEmptyElements(). See {@link OutputFormat OutputFormat}for details. * Here are the rules for this class based on an OutputFormat, "format", * passed in to the constructor:

* *

    *
  • If an element is in {@link #getOmitElementCloseSet() * getOmitElementCloseSet}, then it is treated specially: * *
      *
    • It never expands, since some browsers treat this as two separate * Horizontal Rules: <HR></HR>
    • *
    • If {@link org.dom4j.io.OutputFormat#isXHTML() format.isXHTML()}, then * it has a space before the closing single-tag slash, since Netscape 4.x- * treats this: <HR /> as an element named "HR" with an attribute named * "/", but that's better than when it refuses to recognize this: <hr/> * which it thinks is an element named "HR/".
    • *
    * *
  • *
  • If {@link org.dom4j.io.OutputFormat#isXHTML() format.isXHTML()}, all * elements must have either a close element, or be a closed single tag.
  • *
  • If {@link org.dom4j.io.OutputFormat#isExpandEmptyElements() * format.isExpandEmptyElements()}() is true, all elements are expanded except * as above.
  • *
* * Examples *

* *

*

* *

* If isXHTML == true, CDATA sections look like this: * *

 * 
 * <myelement><![CDATA[My data]]></myelement> 
 * 
 * 
* * Otherwise, they look like this: * *
 * 
 * <myelement>My data</myelement> 
 * 
 * 
* *

* *

* Basically, {@link OutputFormat.isXHTML() OutputFormat.isXHTML()} == * true will produce valid XML, while {@link * org.dom4j.io.OutputFormat#isExpandEmptyElements() * format.isExpandEmptyElements()} determines whether empty elements are * expanded if isXHTML is true, excepting the special HTML single tags. *

* *

* Also, HTMLWriter handles tags whose contents should be preformatted, that is, * whitespace-preserved. By default, this set includes the tags <PRE>, * <SCRIPT>, <STYLE>, and <TEXTAREA>, case insensitively. It * does not include <IFRAME>. Other tags, such as <CODE>, * <KBD>, <TT>, <VAR>, are usually rendered in a different * font in most browsers, but don't preserve whitespace, so they also don't * appear in the default list. HTML Comments are always whitespace-preserved. * However, the parser you use may store comments with linefeed-only text nodes * (\n) even if your platform uses another line.separator character, and * HTMLWriter outputs Comment nodes exactly as the DOM is set up by the parser. * See examples and discussion here: {@link#setPreformattedTags(java.util.Set) * setPreformattedTags} *

* *

* Examples *

*
*

* Pretty Printing *

* *

* This example shows how to pretty print a string containing a valid HTML * document to a string. You can also just call the static methods of this * class:
* {@link #prettyPrintHTML(String) prettyPrintHTML(String)}or
* {@link #prettyPrintHTML(String,boolean,boolean,boolean,boolean) * prettyPrintHTML(String,boolean,boolean,boolean,boolean)} or,
* {@link #prettyPrintXHTML(String) prettyPrintXHTML(String)}for XHTML (note * the X) *

* *
 * String testPrettyPrint(String html) {
 *     StringWriter sw = new StringWriter();
 *     OutputFormat format = OutputFormat.createPrettyPrint();
 *     // These are the default values for createPrettyPrint,
 *     // so you needn't set them:
 *     // format.setNewlines(true);
 *     // format.setTrimText(true);</font>
 *     format.setXHTML(true);
 *     HTMLWriter writer = new HTMLWriter(sw, format);
 *     Document document = DocumentHelper.parseText(html);
 *     writer.write(document);
 *     writer.flush();
 *     return sw.toString();
 * }
 * 
* *

* This example shows how to create a "squeezed" document, but one that will * work in browsers even if the browser line length is limited. No newlines are * included, no extra whitespace at all, except where it it required by * {@link #setPreformattedTags(java.util.Set) setPreformattedTags}. *

* *
 * String testCrunch(String html) {
 *     StringWriter sw = new StringWriter();
 *     OutputFormat format = OutputFormat.createPrettyPrint();
 *     format.setNewlines(false);
 *     format.setTrimText(true);
 *     format.setIndent("");
 *     format.setXHTML(true);
 *     format.setExpandEmptyElements(false);
 *     format.setNewLineAfterNTags(20);
 *     org.dom4j.io.HTMLWriter writer = new HTMLWriter(sw, format);
 *     org.dom4j.Document document = DocumentHelper.parseText(html);
 *     writer.write(document);
 *     writer.flush();
 *     return sw.toString();
 * }
 * 
* *
* * @author James Strachan * @author Laramie Crocker * @version $Revision: 1.21 $ */ public class HTMLWriter extends XMLWriter { private static String lineSeparator = System.getProperty("line.separator"); protected static final HashSet DEFAULT_PREFORMATTED_TAGS; static { // If you change this list, update the javadoc examples, above in the // class javadoc, in writeElement, and in setPreformattedTags(). DEFAULT_PREFORMATTED_TAGS = new HashSet(); DEFAULT_PREFORMATTED_TAGS.add("PRE"); DEFAULT_PREFORMATTED_TAGS.add("SCRIPT"); DEFAULT_PREFORMATTED_TAGS.add("STYLE"); DEFAULT_PREFORMATTED_TAGS.add("TEXTAREA"); } protected static final OutputFormat DEFAULT_HTML_FORMAT; static { DEFAULT_HTML_FORMAT = new OutputFormat(" ", true); DEFAULT_HTML_FORMAT.setTrimText(true); DEFAULT_HTML_FORMAT.setSuppressDeclaration(true); } private Stack formatStack = new Stack(); private String lastText = ""; private int tagsOuput = 0; // legal values are 0+, but -1 signifies lazy initialization. private int newLineAfterNTags = -1; private HashSet preformattedTags = DEFAULT_PREFORMATTED_TAGS; /** * Used to store the qualified element names which should have no close * element tag */ private HashSet omitElementCloseSet; public HTMLWriter(Writer writer) { super(writer, DEFAULT_HTML_FORMAT); } public HTMLWriter(Writer writer, OutputFormat format) { super(writer, format); } public HTMLWriter() throws UnsupportedEncodingException { super(DEFAULT_HTML_FORMAT); } public HTMLWriter(OutputFormat format) throws UnsupportedEncodingException { super(format); } public HTMLWriter(OutputStream out) throws UnsupportedEncodingException { super(out, DEFAULT_HTML_FORMAT); } public HTMLWriter(OutputStream out, OutputFormat format) throws UnsupportedEncodingException { super(out, format); } public void startCDATA() throws SAXException { } public void endCDATA() throws SAXException { } // Overloaded methods // added isXHTML() stuff so you get the CDATA brackets if you desire. protected void writeCDATA(String text) throws IOException { // XXX: Should we escape entities? // writer.write( escapeElementEntities( text ) ); if (getOutputFormat().isXHTML()) { super.writeCDATA(text); } else { writer.write(text); } lastOutputNodeType = Node.CDATA_SECTION_NODE; } protected void writeEntity(Entity entity) throws IOException { writer.write(entity.getText()); lastOutputNodeType = Node.ENTITY_REFERENCE_NODE; } protected void writeDeclaration() throws IOException { } protected void writeString(String text) throws IOException { /* * DOM stores \n at the end of text nodes that are newlines. This is * significant if we are in a PRE section. However, we only want to * output the system line.separator, not \n. This is a little brittle, * but this function appears to be called with these lineseparators as a * separate TEXT_NODE. If we are in a preformatted section, output the * right line.separator, otherwise ditch. If the single \n character is * not the text, then do the super thing to output the text. * * Also, we store the last text that was not a \n since it may be used * by writeElement in this class to line up preformatted tags. */ if (text.equals("\n")) { if (!formatStack.empty()) { super.writeString(lineSeparator); } return; } lastText = text; if (formatStack.empty()) { super.writeString(text.trim()); } else { super.writeString(text); } } /** * Overriden method to not close certain element names to avoid wierd * behaviour from browsers for versions up to 5.x * * @param qualifiedName * DOCUMENT ME! * * @throws IOException * DOCUMENT ME! */ protected void writeClose(String qualifiedName) throws IOException { if (!omitElementClose(qualifiedName)) { super.writeClose(qualifiedName); } } protected void writeEmptyElementClose(String qualifiedName) throws IOException { if (getOutputFormat().isXHTML()) { // xhtml, always check with format object whether to expand or not. if (omitElementClose(qualifiedName)) { // it was a special omit tag, do it the XHTML way: "
", // ignoring the expansion option, since

is OK XML, // but produces twice the linefeeds desired in the browser. // for netscape 4.7, though all are fine with it, write a space // before the close slash. writer.write(" />"); } else { super.writeEmptyElementClose(qualifiedName); } } else { // html, not xhtml if (omitElementClose(qualifiedName)) { // it was a special omit tag, do it the old html way: "
". writer.write(">"); } else { // it was NOT a special omit tag, check with format object // whether to expand or not. super.writeEmptyElementClose(qualifiedName); } } } protected boolean omitElementClose(String qualifiedName) { return internalGetOmitElementCloseSet().contains( qualifiedName.toUpperCase()); } private HashSet internalGetOmitElementCloseSet() { if (omitElementCloseSet == null) { omitElementCloseSet = new HashSet(); loadOmitElementCloseSet(omitElementCloseSet); } return omitElementCloseSet; } // If you change this, change the javadoc for getOmitElementCloseSet. protected void loadOmitElementCloseSet(Set set) { set.add("AREA"); set.add("BASE"); set.add("BR"); set.add("COL"); set.add("HR"); set.add("IMG"); set.add("INPUT"); set.add("LINK"); set.add("META"); set.add("P"); set.add("PARAM"); } // let the people see the set, but not modify it. /** * A clone of the Set of elements that can have their close-tags omitted. By * default it should be "AREA", "BASE", "BR", "COL", "HR", "IMG", "INPUT", * "LINK", "META", "P", "PARAM" * * @return A clone of the Set. */ public Set getOmitElementCloseSet() { return (Set) (internalGetOmitElementCloseSet().clone()); } /** * To use the empty set, pass an empty Set, or null: * *
     * 
     * 
     *       setOmitElementCloseSet(new HashSet());
     *     or
     *       setOmitElementCloseSet(null);
     * 
     *  
     * 
* * @param newSet * DOCUMENT ME! */ public void setOmitElementCloseSet(Set newSet) { // resets, and safely empties it out if newSet is null. omitElementCloseSet = new HashSet(); if (newSet != null) { omitElementCloseSet = new HashSet(); Object aTag; Iterator iter = newSet.iterator(); while (iter.hasNext()) { aTag = iter.next(); if (aTag != null) { omitElementCloseSet.add(aTag.toString().toUpperCase()); } } } } /** * @see #setPreformattedTags(java.util.Set) setPreformattedTags */ public Set getPreformattedTags() { return (Set) (preformattedTags.clone()); } /** *

* Override the default set, which includes PRE, SCRIPT, STYLE, and * TEXTAREA, case insensitively. *

* *

* Setting Preformatted Tags *

* *

* Pass in a Set of Strings, one for each tag name that should be treated * like a PRE tag. You may pass in null or an empty Set to assign the empty * set, in which case no tags will be treated as preformatted, except that * HTML Comments will continue to be preformatted. If a tag is included in * the set of preformatted tags, all whitespace within the tag will be * preserved, including whitespace on the same line preceding the close tag. * This will generally make the close tag not line up with the start tag, * but it preserves the intention of the whitespace within the tag. *

* *

* The browser considers leading whitespace before the close tag to be * significant, but leading whitespace before the open tag to be * insignificant. For example, if the HTML author doesn't put the close * TEXTAREA tag flush to the left margin, then the TEXTAREA control in the * browser will have spaces on the last line inside the control. This may be * the HTML author's intent. Similarly, in a PRE, the browser treats a * flushed left close PRE tag as different from a close tag with leading * whitespace. Again, this must be left up to the HTML author. *

* *

* Examples *

*
*

* Here is an example of how you can set the PreformattedTags list using * setPreformattedTags to include IFRAME, as well as the default set, if you * have an instance of this class named myHTMLWriter: * *

     * Set current = myHTMLWriter.getPreformattedTags();
     * current.add("IFRAME");
     * myHTMLWriter.setPreformattedTags(current);
     * 
     * //The set is now <b>PRE, SCRIPT, STYLE, TEXTAREA, IFRAME</b>
     * 
     * 
     * 
* * Similarly, you can simply replace it with your own: * *
     * 
     * 
     *       HashSet newset = new HashSet();
     *       newset.add("PRE");
     *       newset.add("TEXTAREA");
     *       myHTMLWriter.setPreformattedTags(newset);
     * 
     *       //The set is now <b>{PRE, TEXTAREA}</b>
     * 
     *  
     * 
* * You can remove all tags from the preformatted tags list, with an empty * set, like this: * *
     * 
     * 
     *       myHTMLWriter.setPreformattedTags(new HashSet());
     * 
     *       //The set is now <b>{}</b>
     * 
     *  
     * 
* * or with null, like this: * *
     * 
     * 
     *       myHTMLWriter.setPreformattedTags(null);
     * 
     *       //The set is now <b>{}</b>
     * 
     *  
     * 
* *

*
* * @param newSet * DOCUMENT ME! */ public void setPreformattedTags(Set newSet) { // no fancy merging, just set it, assuming they did a // getExcludeTrimTags() first if they wanted to preserve the default // set. // resets, and safely empties it out if newSet is null. preformattedTags = new HashSet(); if (newSet != null) { Object aTag; Iterator iter = newSet.iterator(); while (iter.hasNext()) { aTag = iter.next(); if (aTag != null) { preformattedTags.add(aTag.toString().toUpperCase()); } } } } /** * DOCUMENT ME! * * @param qualifiedName * DOCUMENT ME! * * @return true if the qualifiedName passed in matched (case-insensitively) * a tag in the preformattedTags set, or false if not found or if * the set is empty or null. * * @see #setPreformattedTags(java.util.Set) setPreformattedTags */ public boolean isPreformattedTag(String qualifiedName) { // A null set implies that the user called setPreformattedTags(null), // which means they want no tags to be preformatted. return (preformattedTags != null) && (preformattedTags.contains(qualifiedName.toUpperCase())); } /** * This override handles any elements that should not remove whitespace, * such as <PRE>, <SCRIPT>, <STYLE>, and <TEXTAREA>. * Note: the close tags won't line up with the open tag, but we can't alter * that. See javadoc note at setPreformattedTags. * * @param element * DOCUMENT ME! * * @throws IOException * When the stream could not be written to. * * @see #setPreformattedTags(java.util.Set) setPreformattedTags */ protected void writeElement(Element element) throws IOException { if (newLineAfterNTags == -1) { // lazy initialization check lazyInitNewLinesAfterNTags(); } if (newLineAfterNTags > 0) { if ((tagsOuput > 0) && ((tagsOuput % newLineAfterNTags) == 0)) { super.writer.write(lineSeparator); } } tagsOuput++; String qualifiedName = element.getQualifiedName(); String saveLastText = lastText; int size = element.nodeCount(); if (isPreformattedTag(qualifiedName)) { OutputFormat currentFormat = getOutputFormat(); boolean saveNewlines = currentFormat.isNewlines(); boolean saveTrimText = currentFormat.isTrimText(); String currentIndent = currentFormat.getIndent(); // You could have nested PREs, or SCRIPTS within PRE... etc., // therefore use push and pop. formatStack.push(new FormatState(saveNewlines, saveTrimText, currentIndent)); try { // do this manually, since it won't be done while outputting // the tag. super.writePrintln(); if ((saveLastText.trim().length() == 0) && (currentIndent != null) && (currentIndent.length() > 0)) { // We are indenting, but we want to line up with the close // tag. lastText was the indent (whitespace, no \n) before // the preformatted start tag. So write it out instead of // the current indent level. This makes it line up with its // close tag. super.writer.write(justSpaces(saveLastText)); } // actually, newlines are handled in this class by writeString, // depending on if the stack is empty. currentFormat.setNewlines(false); currentFormat.setTrimText(false); currentFormat.setIndent(""); // This line is the recursive one: super.writeElement(element); } finally { FormatState state = (FormatState) formatStack.pop(); currentFormat.setNewlines(state.isNewlines()); currentFormat.setTrimText(state.isTrimText()); currentFormat.setIndent(state.getIndent()); } } else { super.writeElement(element); } } private String justSpaces(String text) { int size = text.length(); StringBuffer res = new StringBuffer(size); char c; for (int i = 0; i < size; i++) { c = text.charAt(i); switch (c) { case '\r': case '\n': continue; default: res.append(c); } } return res.toString(); } private void lazyInitNewLinesAfterNTags() { if (getOutputFormat().isNewlines()) { // don't bother, newlines are going to happen anyway. newLineAfterNTags = 0; } else { newLineAfterNTags = getOutputFormat().getNewLineAfterNTags(); } } // Convenience methods, static, with bunch-o-defaults /** * Convenience method to just get a String result. * * @param html * DOCUMENT ME! * * @return a pretty printed String from the source string, preserving * whitespace in the defaultPreformattedTags set, and leaving the * close tags off of the default omitElementCloseSet set. Use one of * the write methods if you want stream output. * * @throws java.io.IOException * @throws java.io.UnsupportedEncodingException * @throws org.dom4j.DocumentException */ public static String prettyPrintHTML(String html) throws java.io.IOException, java.io.UnsupportedEncodingException, org.dom4j.DocumentException { return prettyPrintHTML(html, true, true, false, true); } /** * Convenience method to just get a String result, but As XHTML . * * @param html * DOCUMENT ME! * * @return a pretty printed String from the source string, preserving * whitespace in the defaultPreformattedTags set, but conforming to * XHTML: no close tags are omitted (though if empty, they will be * converted to XHTML empty tags: <HR/> Use one of the write * methods if you want stream output. * * @throws java.io.IOException * @throws java.io.UnsupportedEncodingException * @throws org.dom4j.DocumentException */ public static String prettyPrintXHTML(String html) throws java.io.IOException, java.io.UnsupportedEncodingException, org.dom4j.DocumentException { return prettyPrintHTML(html, true, true, true, false); } /** * DOCUMENT ME! * * @param html * DOCUMENT ME! * @param newlines * DOCUMENT ME! * @param trim * DOCUMENT ME! * @param isXHTML * DOCUMENT ME! * @param expandEmpty * DOCUMENT ME! * * @return a pretty printed String from the source string, preserving * whitespace in the defaultPreformattedTags set, and leaving the * close tags off of the default omitElementCloseSet set. This * override allows you to specify various formatter options. Use one * of the write methods if you want stream output. * * @throws java.io.IOException * @throws java.io.UnsupportedEncodingException * @throws org.dom4j.DocumentException */ public static String prettyPrintHTML(String html, boolean newlines, boolean trim, boolean isXHTML, boolean expandEmpty) throws java.io.IOException, java.io.UnsupportedEncodingException, org.dom4j.DocumentException { StringWriter sw = new StringWriter(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setNewlines(newlines); format.setTrimText(trim); format.setXHTML(isXHTML); format.setExpandEmptyElements(expandEmpty); HTMLWriter writer = new HTMLWriter(sw, format); Document document = DocumentHelper.parseText(html); writer.write(document); writer.flush(); return sw.toString(); } // Allows us to the current state of the format in this struct on the // formatStack. private class FormatState { private boolean newlines = false; private boolean trimText = false; private String indent = ""; public FormatState(boolean newLines, boolean trimText, String indent) { this.newlines = newLines; this.trimText = trimText; this.indent = indent; } public boolean isNewlines() { return newlines; } public boolean isTrimText() { return trimText; } public String getIndent() { return indent; } } } /* * My Title entities:   & * " < > %23

*
 line0 
line1 line2, should line up, indent-wise line * 3 line 4
*/ /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/XPPReader.java0000644000175000017500000003655010242120013020436 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.ElementHandler; import org.dom4j.xpp.ProxyXmlStartTag; import org.gjt.xpp.XmlEndTag; import org.gjt.xpp.XmlPullParser; import org.gjt.xpp.XmlPullParserException; import org.gjt.xpp.XmlPullParserFactory; /** *

* XPPReader is a Reader of DOM4J documents that uses the fast XML Pull Parser 2.x . It * does not currently support comments, CDATA or ProcessingInstructions or * validation but it is very fast for use in SOAP style environments. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public class XPPReader { /** DocumentFactory used to create new document objects */ private DocumentFactory factory; /** XmlPullParser used to parse XML */ private XmlPullParser xppParser; /** XmlPullParser used to parse XML */ private XmlPullParserFactory xppFactory; /** DispatchHandler to call when each Element is encountered */ private DispatchHandler dispatchHandler; public XPPReader() { } public XPPReader(DocumentFactory factory) { this.factory = factory; } /** *

* Reads a Document from the given File *

* * @param file * is the File to read from. * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * if a URL could not be made for the given File * @throws XmlPullParserException * DOCUMENT ME! */ public Document read(File file) throws DocumentException, IOException, XmlPullParserException { String systemID = file.getAbsolutePath(); return read(new BufferedReader(new FileReader(file)), systemID); } /** *

* Reads a Document from the given URL *

* * @param url * URL to read from. * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * DOCUMENT ME! * @throws XmlPullParserException * DOCUMENT ME! */ public Document read(URL url) throws DocumentException, IOException, XmlPullParserException { String systemID = url.toExternalForm(); return read(createReader(url.openStream()), systemID); } /** *

* Reads a Document from the given URL or filename. *

* *

* If the systemID contains a ':' character then it is * assumed to be a URL otherwise its assumed to be a file name. If you want * finer grained control over this mechansim then please explicitly pass in * either a {@link URL}or a {@link File}instance instead of a {@link * String} to denote the source of the document. *

* * @param systemID * is a URL for a document or a file name. * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * if a URL could not be made for the given File * @throws XmlPullParserException * DOCUMENT ME! */ public Document read(String systemID) throws DocumentException, IOException, XmlPullParserException { if (systemID.indexOf(':') >= 0) { // lets assume its a URL return read(new URL(systemID)); } else { // lets assume that we are given a file name return read(new File(systemID)); } } /** *

* Reads a Document from the given stream *

* * @param in * InputStream to read from. * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * DOCUMENT ME! * @throws XmlPullParserException * DOCUMENT ME! */ public Document read(InputStream in) throws DocumentException, IOException, XmlPullParserException { return read(createReader(in)); } /** *

* Reads a Document from the given Reader *

* * @param reader * is the reader for the input * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * DOCUMENT ME! * @throws XmlPullParserException * DOCUMENT ME! */ public Document read(Reader reader) throws DocumentException, IOException, XmlPullParserException { getXPPParser().setInput(reader); return parseDocument(); } /** *

* Reads a Document from the given array of characters *

* * @param text * is the text to parse * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * DOCUMENT ME! * @throws XmlPullParserException * DOCUMENT ME! */ public Document read(char[] text) throws DocumentException, IOException, XmlPullParserException { getXPPParser().setInput(text); return parseDocument(); } /** *

* Reads a Document from the given stream *

* * @param in * InputStream to read from. * @param systemID * is the URI for the input * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * DOCUMENT ME! * @throws XmlPullParserException * DOCUMENT ME! */ public Document read(InputStream in, String systemID) throws DocumentException, IOException, XmlPullParserException { return read(createReader(in), systemID); } /** *

* Reads a Document from the given Reader *

* * @param reader * is the reader for the input * @param systemID * is the URI for the input * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * DOCUMENT ME! * @throws XmlPullParserException * DOCUMENT ME! */ public Document read(Reader reader, String systemID) throws DocumentException, IOException, XmlPullParserException { Document document = read(reader); document.setName(systemID); return document; } // Properties // ------------------------------------------------------------------------- public XmlPullParser getXPPParser() throws XmlPullParserException { if (xppParser == null) { xppParser = getXPPFactory().newPullParser(); } return xppParser; } public XmlPullParserFactory getXPPFactory() throws XmlPullParserException { if (xppFactory == null) { xppFactory = XmlPullParserFactory.newInstance(); } return xppFactory; } public void setXPPFactory(XmlPullParserFactory xPPFactory) { this.xppFactory = xPPFactory; } /** * DOCUMENT ME! * * @return the DocumentFactory used to create document * objects */ public DocumentFactory getDocumentFactory() { if (factory == null) { factory = DocumentFactory.getInstance(); } return factory; } /** *

* This sets the DocumentFactory used to create new * documents. This method allows the building of custom DOM4J tree objects * to be implemented easily using a custom derivation of * {@link DocumentFactory} *

* * @param documentFactory * DocumentFactory used to create DOM4J objects */ public void setDocumentFactory(DocumentFactory documentFactory) { this.factory = documentFactory; } /** * Adds the ElementHandler to be called when the specified * path is encounted. * * @param path * is the path to be handled * @param handler * is the ElementHandler to be called by the event * based processor. */ public void addHandler(String path, ElementHandler handler) { getDispatchHandler().addHandler(path, handler); } /** * Removes the ElementHandler from the event based processor, * for the specified path. * * @param path * is the path to remove the ElementHandler for. */ public void removeHandler(String path) { getDispatchHandler().removeHandler(path); } /** * When multiple ElementHandler instances have been * registered, this will set a default ElementHandler to be * called for any path which does NOT have a handler registered. * * @param handler * is the ElementHandler to be called by the event * based processor. */ public void setDefaultHandler(ElementHandler handler) { getDispatchHandler().setDefaultHandler(handler); } // Implementation methods // ------------------------------------------------------------------------- protected Document parseDocument() throws DocumentException, IOException, XmlPullParserException { Document document = getDocumentFactory().createDocument(); Element parent = null; XmlPullParser parser = getXPPParser(); parser.setNamespaceAware(true); ProxyXmlStartTag startTag = new ProxyXmlStartTag(); XmlEndTag endTag = xppFactory.newEndTag(); while (true) { int type = parser.next(); switch (type) { case XmlPullParser.END_DOCUMENT: return document; case XmlPullParser.START_TAG: { parser.readStartTag(startTag); Element newElement = startTag.getElement(); if (parent != null) { parent.add(newElement); } else { document.add(newElement); } parent = newElement; break; } case XmlPullParser.END_TAG: { parser.readEndTag(endTag); if (parent != null) { parent = parent.getParent(); } break; } case XmlPullParser.CONTENT: { String text = parser.readContent(); if (parent != null) { parent.addText(text); } else { String msg = "Cannot have text content outside of the " + "root document"; throw new DocumentException(msg); } break; } default: throw new DocumentException("Error: unknown type: " + type); } } } protected DispatchHandler getDispatchHandler() { if (dispatchHandler == null) { dispatchHandler = new DispatchHandler(); } return dispatchHandler; } protected void setDispatchHandler(DispatchHandler dispatchHandler) { this.dispatchHandler = dispatchHandler; } /** * Factory method to create a Reader from the given InputStream. * * @param in * DOCUMENT ME! * * @return DOCUMENT ME! * * @throws IOException * DOCUMENT ME! */ protected Reader createReader(InputStream in) throws IOException { return new BufferedReader(new InputStreamReader(in)); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/DocumentSource.java0000644000175000017500000001402410242117777021622 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import javax.xml.transform.sax.SAXSource; import org.dom4j.Document; import org.dom4j.Node; import org.xml.sax.InputSource; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; /** *

* DocumentSource implements a JAXP {@link SAXSource}for a * {@linkDocument}. *

* * @author James Strachan * @version $Revision: 1.10 $ */ public class DocumentSource extends SAXSource { /** * If {@link javax.xml.transform.TransformerFactory#getFeature}returns * true when passed this value as an argument then the * Transformer natively supports dom4j . */ public static final String DOM4J_FEATURE = "http://org.dom4j.io.DoucmentSource/feature"; /** The XMLReader to use */ private XMLReader xmlReader = new SAXWriter(); /** * Creates a JAXP {@link SAXSource}for the given {@link Node}. * * @param node * DOCUMENT ME! */ public DocumentSource(Node node) { setDocument(node.getDocument()); } /** * Creates a JAXP {@link SAXSource}for the given {@link Document}. * * @param document * DOCUMENT ME! */ public DocumentSource(Document document) { setDocument(document); } // Properties // ------------------------------------------------------------------------- /** * DOCUMENT ME! * * @return the document which is being used as the JAXP {@link SAXSource} */ public Document getDocument() { DocumentInputSource source = (DocumentInputSource) getInputSource(); return source.getDocument(); } /** * Sets the document used as the JAXP {@link SAXSource} * * @param document * DOCUMENT ME! */ public void setDocument(Document document) { super.setInputSource(new DocumentInputSource(document)); } // Overloaded methods // ------------------------------------------------------------------------- /** * DOCUMENT ME! * * @return the XMLReader to be used for the JAXP {@link SAXSource}. */ public XMLReader getXMLReader() { return xmlReader; } /** * This method is not supported as this source is always a {@linkDocument} * instance. * * @param inputSource * DOCUMENT ME! * * @throws UnsupportedOperationException * as this method is unsupported */ public void setInputSource(InputSource inputSource) throws UnsupportedOperationException { if (inputSource instanceof DocumentInputSource) { super.setInputSource((DocumentInputSource) inputSource); } else { throw new UnsupportedOperationException(); } } /** * Sets the XMLReader used for the JAXP {@link SAXSource}. * * @param reader * DOCUMENT ME! * * @throws UnsupportedOperationException * DOCUMENT ME! */ public void setXMLReader(XMLReader reader) throws UnsupportedOperationException { if (reader instanceof SAXWriter) { this.xmlReader = (SAXWriter) reader; } else if (reader instanceof XMLFilter) { XMLFilter filter = (XMLFilter) reader; while (true) { XMLReader parent = filter.getParent(); if (parent instanceof XMLFilter) { filter = (XMLFilter) parent; } else { break; } } // install filter in SAXWriter.... filter.setParent(xmlReader); xmlReader = filter; } else { throw new UnsupportedOperationException(); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/SAXHelper.java0000644000175000017500000001531210242120023020431 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** *

* SAXHelper contains some helper methods for working with SAX * and XMLReader objects. *

* * @author James Strachan * @version $Revision: 1.18 $ */ class SAXHelper { private static boolean loggedWarning = true; protected SAXHelper() { } public static boolean setParserProperty(XMLReader reader, String propertyName, Object value) { try { reader.setProperty(propertyName, value); return true; } catch (SAXNotSupportedException e) { // ignore } catch (SAXNotRecognizedException e) { // ignore } return false; } public static boolean setParserFeature(XMLReader reader, String featureName, boolean value) { try { reader.setFeature(featureName, value); return true; } catch (SAXNotSupportedException e) { // ignore } catch (SAXNotRecognizedException e) { // ignore } return false; } /** * Creats a default XMLReader via the org.xml.sax.driver system property or * JAXP if the system property is not set. * * @param validating * DOCUMENT ME! * * @return DOCUMENT ME! * * @throws SAXException * DOCUMENT ME! */ public static XMLReader createXMLReader(boolean validating) throws SAXException { XMLReader reader = null; if (reader == null) { reader = createXMLReaderViaJAXP(validating, true); } if (reader == null) { try { reader = XMLReaderFactory.createXMLReader(); } catch (Exception e) { if (isVerboseErrorReporting()) { // log all exceptions as warnings and carry // on as we have a default SAX parser we can use System.out.println("Warning: Caught exception attempting " + "to use SAX to load a SAX XMLReader "); System.out.println("Warning: Exception was: " + e); System.out .println("Warning: I will print the stack trace " + "then carry on using the default " + "SAX parser"); e.printStackTrace(); } throw new SAXException(e); } } if (reader == null) { throw new SAXException("Couldn't create SAX reader"); } return reader; } /** * This method attempts to use JAXP to locate the SAX2 XMLReader * implementation. This method uses reflection to avoid being dependent * directly on the JAXP classes. * * @param validating * DOCUMENT ME! * @param namespaceAware * DOCUMENT ME! * * @return DOCUMENT ME! */ protected static XMLReader createXMLReaderViaJAXP(boolean validating, boolean namespaceAware) { // try use JAXP to load the XMLReader... try { return JAXPHelper.createXMLReader(validating, namespaceAware); } catch (Throwable e) { if (!loggedWarning) { loggedWarning = true; if (isVerboseErrorReporting()) { // log all exceptions as warnings and carry // on as we have a default SAX parser we can use System.out.println("Warning: Caught exception attempting " + "to use JAXP to load a SAX XMLReader"); System.out.println("Warning: Exception was: " + e); e.printStackTrace(); } } } return null; } protected static boolean isVerboseErrorReporting() { try { String flag = System.getProperty("org.dom4j.verbose"); if ((flag != null) && flag.equalsIgnoreCase("true")) { return true; } } catch (Exception e) { // in case a security exception // happens in an applet or similar JVM } return true; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/SAXWriter.java0000644000175000017500000007250710242120015020500 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.dom4j.Attribute; import org.dom4j.Branch; import org.dom4j.CDATA; import org.dom4j.CharacterData; import org.dom4j.Comment; import org.dom4j.Document; import org.dom4j.DocumentType; import org.dom4j.Element; import org.dom4j.Entity; import org.dom4j.Namespace; import org.dom4j.Node; import org.dom4j.ProcessingInstruction; import org.dom4j.Text; import org.dom4j.tree.NamespaceStack; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.DTDHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.LocatorImpl; /** *

* SAXWriter writes a DOM4J tree to a SAX ContentHandler. *

* * @author James Strachan * @version $Revision: 1.24 $ */ public class SAXWriter implements XMLReader { protected static final String[] LEXICAL_HANDLER_NAMES = { "http://xml.org/sax/properties/lexical-handler", "http://xml.org/sax/handlers/LexicalHandler" }; protected static final String FEATURE_NAMESPACE_PREFIXES = "http://xml.org/sax/features/namespace-prefixes"; protected static final String FEATURE_NAMESPACES = "http://xml.org/sax/features/namespaces"; /** ContentHandler to which SAX events are raised */ private ContentHandler contentHandler; /** DTDHandler fired when a document has a DTD */ private DTDHandler dtdHandler; /** EntityResolver fired when a document has a DTD */ private EntityResolver entityResolver; private ErrorHandler errorHandler; /** LexicalHandler fired on Entity and CDATA sections */ private LexicalHandler lexicalHandler; /** AttributesImpl used when generating the Attributes */ private AttributesImpl attributes = new AttributesImpl(); /** Stores the features */ private Map features = new HashMap(); /** Stores the properties */ private Map properties = new HashMap(); /** Whether namespace declarations are exported as attributes or not */ private boolean declareNamespaceAttributes; public SAXWriter() { properties.put(FEATURE_NAMESPACE_PREFIXES, Boolean.FALSE); properties.put(FEATURE_NAMESPACE_PREFIXES, Boolean.TRUE); } public SAXWriter(ContentHandler contentHandler) { this(); this.contentHandler = contentHandler; } public SAXWriter(ContentHandler contentHandler, LexicalHandler lexicalHandler) { this(); this.contentHandler = contentHandler; this.lexicalHandler = lexicalHandler; } public SAXWriter(ContentHandler contentHandler, LexicalHandler lexicalHandler, EntityResolver entityResolver) { this(); this.contentHandler = contentHandler; this.lexicalHandler = lexicalHandler; this.entityResolver = entityResolver; } /** * A polymorphic method to write any Node to this SAX stream * * @param node * DOCUMENT ME! * * @throws SAXException * DOCUMENT ME! */ public void write(Node node) throws SAXException { int nodeType = node.getNodeType(); switch (nodeType) { case Node.ELEMENT_NODE: write((Element) node); break; case Node.ATTRIBUTE_NODE: write((Attribute) node); break; case Node.TEXT_NODE: write(node.getText()); break; case Node.CDATA_SECTION_NODE: write((CDATA) node); break; case Node.ENTITY_REFERENCE_NODE: write((Entity) node); break; case Node.PROCESSING_INSTRUCTION_NODE: write((ProcessingInstruction) node); break; case Node.COMMENT_NODE: write((Comment) node); break; case Node.DOCUMENT_NODE: write((Document) node); break; case Node.DOCUMENT_TYPE_NODE: write((DocumentType) node); break; case Node.NAMESPACE_NODE: // Will be output with attributes // write((Namespace) node); break; default: throw new SAXException("Invalid node type: " + node); } } /** * Generates SAX events for the given Document and all its content * * @param document * is the Document to parse * * @throws SAXException * if there is a SAX error processing the events */ public void write(Document document) throws SAXException { if (document != null) { checkForNullHandlers(); documentLocator(document); startDocument(); entityResolver(document); dtdHandler(document); writeContent(document, new NamespaceStack()); endDocument(); } } /** * Generates SAX events for the given Element and all its content * * @param element * is the Element to parse * * @throws SAXException * if there is a SAX error processing the events */ public void write(Element element) throws SAXException { write(element, new NamespaceStack()); } /** *

* Writes the opening tag of an {@link Element}, including its {@link * Attribute}s but without its content. *

* * @param element * Element to output. * * @throws SAXException * DOCUMENT ME! */ public void writeOpen(Element element) throws SAXException { startElement(element, null); } /** *

* Writes the closing tag of an {@link Element} *

* * @param element * Element to output. * * @throws SAXException * DOCUMENT ME! */ public void writeClose(Element element) throws SAXException { endElement(element); } /** * Generates SAX events for the given text * * @param text * is the text to send to the SAX ContentHandler * * @throws SAXException * if there is a SAX error processing the events */ public void write(String text) throws SAXException { if (text != null) { char[] chars = text.toCharArray(); contentHandler.characters(chars, 0, chars.length); } } /** * Generates SAX events for the given CDATA * * @param cdata * is the CDATA to parse * * @throws SAXException * if there is a SAX error processing the events */ public void write(CDATA cdata) throws SAXException { String text = cdata.getText(); if (lexicalHandler != null) { lexicalHandler.startCDATA(); write(text); lexicalHandler.endCDATA(); } else { write(text); } } /** * Generates SAX events for the given Comment * * @param comment * is the Comment to parse * * @throws SAXException * if there is a SAX error processing the events */ public void write(Comment comment) throws SAXException { if (lexicalHandler != null) { String text = comment.getText(); char[] chars = text.toCharArray(); lexicalHandler.comment(chars, 0, chars.length); } } /** * Generates SAX events for the given Entity * * @param entity * is the Entity to parse * * @throws SAXException * if there is a SAX error processing the events */ public void write(Entity entity) throws SAXException { String text = entity.getText(); if (lexicalHandler != null) { String name = entity.getName(); lexicalHandler.startEntity(name); write(text); lexicalHandler.endEntity(name); } else { write(text); } } /** * Generates SAX events for the given ProcessingInstruction * * @param pi * is the ProcessingInstruction to parse * * @throws SAXException * if there is a SAX error processing the events */ public void write(ProcessingInstruction pi) throws SAXException { String target = pi.getTarget(); String text = pi.getText(); contentHandler.processingInstruction(target, text); } /** * Should namespace declarations be converted to "xmlns" attributes. This * property defaults to false as per the SAX specification. * This property is set via the SAX feature * "http://xml.org/sax/features/namespace-prefixes" * * @return DOCUMENT ME! */ public boolean isDeclareNamespaceAttributes() { return declareNamespaceAttributes; } /** * Sets whether namespace declarations should be exported as "xmlns" * attributes or not. This property is set from the SAX feature * "http://xml.org/sax/features/namespace-prefixes" * * @param declareNamespaceAttrs * DOCUMENT ME! */ public void setDeclareNamespaceAttributes(boolean declareNamespaceAttrs) { this.declareNamespaceAttributes = declareNamespaceAttrs; } // XMLReader methods // ------------------------------------------------------------------------- /** * DOCUMENT ME! * * @return the ContentHandler called when SAX events are * raised */ public ContentHandler getContentHandler() { return contentHandler; } /** * Sets the ContentHandler called when SAX events are raised * * @param contentHandler * is the ContentHandler called when SAX events * are raised */ public void setContentHandler(ContentHandler contentHandler) { this.contentHandler = contentHandler; } /** * DOCUMENT ME! * * @return the DTDHandler */ public DTDHandler getDTDHandler() { return dtdHandler; } /** * Sets the DTDHandler. * * @param handler * DOCUMENT ME! */ public void setDTDHandler(DTDHandler handler) { this.dtdHandler = handler; } /** * DOCUMENT ME! * * @return the ErrorHandler */ public ErrorHandler getErrorHandler() { return errorHandler; } /** * Sets the ErrorHandler. * * @param errorHandler * DOCUMENT ME! */ public void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; } /** * DOCUMENT ME! * * @return the EntityResolver used when a Document contains a * DTD */ public EntityResolver getEntityResolver() { return entityResolver; } /** * Sets the EntityResolver. * * @param entityResolver * is the EntityResolver */ public void setEntityResolver(EntityResolver entityResolver) { this.entityResolver = entityResolver; } /** * DOCUMENT ME! * * @return the LexicalHandler used when a Document contains a * DTD */ public LexicalHandler getLexicalHandler() { return lexicalHandler; } /** * Sets the LexicalHandler. * * @param lexicalHandler * is the LexicalHandler */ public void setLexicalHandler(LexicalHandler lexicalHandler) { this.lexicalHandler = lexicalHandler; } /** * Sets the XMLReader used to write SAX events to * * @param xmlReader * is the XMLReader */ public void setXMLReader(XMLReader xmlReader) { setContentHandler(xmlReader.getContentHandler()); setDTDHandler(xmlReader.getDTDHandler()); setEntityResolver(xmlReader.getEntityResolver()); setErrorHandler(xmlReader.getErrorHandler()); } /** * Looks up the value of a feature. * * @param name * DOCUMENT ME! * * @return DOCUMENT ME! * * @throws SAXNotRecognizedException * DOCUMENT ME! * @throws SAXNotSupportedException * DOCUMENT ME! */ public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException { Boolean answer = (Boolean) features.get(name); return (answer != null) && answer.booleanValue(); } /** * This implementation does actually use any features but just stores them * for later retrieval * * @param name * DOCUMENT ME! * @param value * DOCUMENT ME! * * @throws SAXNotRecognizedException * DOCUMENT ME! * @throws SAXNotSupportedException * DOCUMENT ME! */ public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { if (FEATURE_NAMESPACE_PREFIXES.equals(name)) { setDeclareNamespaceAttributes(value); } else if (FEATURE_NAMESPACE_PREFIXES.equals(name)) { if (!value) { String msg = "Namespace feature is always supported in dom4j"; throw new SAXNotSupportedException(msg); } } features.put(name, (value) ? Boolean.TRUE : Boolean.FALSE); } /** * Sets the given SAX property * * @param name * DOCUMENT ME! * @param value * DOCUMENT ME! */ public void setProperty(String name, Object value) { for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) { if (LEXICAL_HANDLER_NAMES[i].equals(name)) { setLexicalHandler((LexicalHandler) value); return; } } properties.put(name, value); } /** * Gets the given SAX property * * @param name * DOCUMENT ME! * * @return DOCUMENT ME! * * @throws SAXNotRecognizedException * DOCUMENT ME! * @throws SAXNotSupportedException * DOCUMENT ME! */ public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException { for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) { if (LEXICAL_HANDLER_NAMES[i].equals(name)) { return getLexicalHandler(); } } return properties.get(name); } /** * This method is not supported. * * @param systemId * DOCUMENT ME! * * @throws SAXNotSupportedException * DOCUMENT ME! */ public void parse(String systemId) throws SAXNotSupportedException { throw new SAXNotSupportedException("This XMLReader can only accept" + " InputSource objects"); } /** * Parses an XML document. This method can only accept DocumentInputSource * inputs otherwise a {@link SAXNotSupportedException}exception is thrown. * * @param input * DOCUMENT ME! * * @throws SAXException * DOCUMENT ME! * @throws SAXNotSupportedException * if the input source is not wrapping a dom4j document */ public void parse(InputSource input) throws SAXException { if (input instanceof DocumentInputSource) { DocumentInputSource documentInput = (DocumentInputSource) input; Document document = documentInput.getDocument(); write(document); } else { throw new SAXNotSupportedException( "This XMLReader can only accept " + " InputSource objects"); } } // Implementation methods // ------------------------------------------------------------------------- protected void writeContent(Branch branch, NamespaceStack namespaceStack) throws SAXException { for (Iterator iter = branch.nodeIterator(); iter.hasNext();) { Object object = iter.next(); if (object instanceof Element) { write((Element) object, namespaceStack); } else if (object instanceof CharacterData) { if (object instanceof Text) { Text text = (Text) object; write(text.getText()); } else if (object instanceof CDATA) { write((CDATA) object); } else if (object instanceof Comment) { write((Comment) object); } else { throw new SAXException("Invalid Node in DOM4J content: " + object + " of type: " + object.getClass()); } } else if (object instanceof String) { write((String) object); } else if (object instanceof Entity) { write((Entity) object); } else if (object instanceof ProcessingInstruction) { write((ProcessingInstruction) object); } else if (object instanceof Namespace) { write((Namespace) object); } else { throw new SAXException("Invalid Node in DOM4J content: " + object); } } } /** * The {@link org.xml.sax.Locator}is only really useful when parsing a * textual document as its main purpose is to identify the line and column * number. Since we are processing an in memory tree which will probably * have its line number information removed, we'll just use -1 for the line * and column numbers. * * @param document * DOCUMENT ME! * * @throws SAXException * DOCUMENT ME! */ protected void documentLocator(Document document) throws SAXException { LocatorImpl locator = new LocatorImpl(); String publicID = null; String systemID = null; DocumentType docType = document.getDocType(); if (docType != null) { publicID = docType.getPublicID(); systemID = docType.getSystemID(); } if (publicID != null) { locator.setPublicId(publicID); } if (systemID != null) { locator.setSystemId(systemID); } locator.setLineNumber(-1); locator.setColumnNumber(-1); contentHandler.setDocumentLocator(locator); } protected void entityResolver(Document document) throws SAXException { if (entityResolver != null) { DocumentType docType = document.getDocType(); if (docType != null) { String publicID = docType.getPublicID(); String systemID = docType.getSystemID(); if ((publicID != null) || (systemID != null)) { try { entityResolver.resolveEntity(publicID, systemID); } catch (IOException e) { throw new SAXException("Could not resolve publicID: " + publicID + " systemID: " + systemID, e); } } } } } /** * We do not yet support DTD or XML Schemas so this method does nothing * right now. * * @param document * DOCUMENT ME! * * @throws SAXException * DOCUMENT ME! */ protected void dtdHandler(Document document) throws SAXException { } protected void startDocument() throws SAXException { contentHandler.startDocument(); } protected void endDocument() throws SAXException { contentHandler.endDocument(); } protected void write(Element element, NamespaceStack namespaceStack) throws SAXException { int stackSize = namespaceStack.size(); AttributesImpl namespaceAttributes = startPrefixMapping(element, namespaceStack); startElement(element, namespaceAttributes); writeContent(element, namespaceStack); endElement(element); endPrefixMapping(namespaceStack, stackSize); } /** * Fires a SAX startPrefixMapping event for all the namespaceStack which * have just come into scope * * @param element * DOCUMENT ME! * @param namespaceStack * DOCUMENT ME! * * @return DOCUMENT ME! * * @throws SAXException * DOCUMENT ME! */ protected AttributesImpl startPrefixMapping(Element element, NamespaceStack namespaceStack) throws SAXException { AttributesImpl namespaceAttributes = null; // start with the namespace of the element Namespace elementNamespace = element.getNamespace(); if ((elementNamespace != null) && !isIgnoreableNamespace(elementNamespace, namespaceStack)) { namespaceStack.push(elementNamespace); contentHandler.startPrefixMapping(elementNamespace.getPrefix(), elementNamespace.getURI()); namespaceAttributes = addNamespaceAttribute(namespaceAttributes, elementNamespace); } List declaredNamespaces = element.declaredNamespaces(); for (int i = 0, size = declaredNamespaces.size(); i < size; i++) { Namespace namespace = (Namespace) declaredNamespaces.get(i); if (!isIgnoreableNamespace(namespace, namespaceStack)) { namespaceStack.push(namespace); contentHandler.startPrefixMapping(namespace.getPrefix(), namespace.getURI()); namespaceAttributes = addNamespaceAttribute( namespaceAttributes, namespace); } } return namespaceAttributes; } /** * Fires a SAX endPrefixMapping event for all the namespaceStack which have * gone out of scope * * @param stack * DOCUMENT ME! * @param stackSize * DOCUMENT ME! * * @throws SAXException * DOCUMENT ME! */ protected void endPrefixMapping(NamespaceStack stack, int stackSize) throws SAXException { while (stack.size() > stackSize) { Namespace namespace = stack.pop(); if (namespace != null) { contentHandler.endPrefixMapping(namespace.getPrefix()); } } } protected void startElement(Element element, AttributesImpl namespaceAttributes) throws SAXException { contentHandler.startElement(element.getNamespaceURI(), element .getName(), element.getQualifiedName(), createAttributes( element, namespaceAttributes)); } protected void endElement(Element element) throws SAXException { contentHandler.endElement(element.getNamespaceURI(), element.getName(), element.getQualifiedName()); } protected Attributes createAttributes(Element element, Attributes namespaceAttributes) throws SAXException { attributes.clear(); if (namespaceAttributes != null) { attributes.setAttributes(namespaceAttributes); } for (Iterator iter = element.attributeIterator(); iter.hasNext();) { Attribute attribute = (Attribute) iter.next(); attributes.addAttribute(attribute.getNamespaceURI(), attribute .getName(), attribute.getQualifiedName(), "CDATA", attribute.getValue()); } return attributes; } /** * If isDelcareNamespaceAttributes() is enabled then this method will add * the given namespace declaration to the supplied attributes object, * creating one if it does not exist. * * @param attrs * DOCUMENT ME! * @param namespace * DOCUMENT ME! * * @return DOCUMENT ME! */ protected AttributesImpl addNamespaceAttribute(AttributesImpl attrs, Namespace namespace) { if (declareNamespaceAttributes) { if (attrs == null) { attrs = new AttributesImpl(); } String prefix = namespace.getPrefix(); String qualifiedName = "xmlns"; if ((prefix != null) && (prefix.length() > 0)) { qualifiedName = "xmlns:" + prefix; } String uri = ""; String localName = prefix; String type = "CDATA"; String value = namespace.getURI(); attrs.addAttribute(uri, localName, qualifiedName, type, value); } return attrs; } /** * DOCUMENT ME! * * @param namespace * DOCUMENT ME! * @param namespaceStack * DOCUMENT ME! * * @return true if the given namespace is an ignorable namespace (such as * Namespace.NO_NAMESPACE or Namespace.XML_NAMESPACE) or if the * namespace has already been declared in the current scope */ protected boolean isIgnoreableNamespace(Namespace namespace, NamespaceStack namespaceStack) { if (namespace.equals(Namespace.NO_NAMESPACE) || namespace.equals(Namespace.XML_NAMESPACE)) { return true; } String uri = namespace.getURI(); if ((uri == null) || (uri.length() <= 0)) { return true; } return namespaceStack.contains(namespace); } /** * Ensures non-null content handlers? */ protected void checkForNullHandlers() { } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/SAXContentHandler.java0000644000175000017500000010032410242120007022122 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.dom4j.Branch; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.DocumentType; import org.dom4j.Element; import org.dom4j.ElementHandler; import org.dom4j.Namespace; import org.dom4j.QName; import org.dom4j.dtd.AttributeDecl; import org.dom4j.dtd.ElementDecl; import org.dom4j.dtd.ExternalEntityDecl; import org.dom4j.dtd.InternalEntityDecl; import org.dom4j.tree.AbstractElement; import org.dom4j.tree.NamespaceStack; import org.xml.sax.Attributes; import org.xml.sax.DTDHandler; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.ext.DeclHandler; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.DefaultHandler; /** *

* SAXContentHandler builds a dom4j tree via SAX events. *

* * @author James Strachan * @version $Revision: 1.61 $ */ public class SAXContentHandler extends DefaultHandler implements LexicalHandler, DeclHandler, DTDHandler { /** The factory used to create new Document instances */ private DocumentFactory documentFactory; /** The document that is being built */ private Document document; /** stack of Element objects */ private ElementStack elementStack; /** stack of Namespace and QName objects */ private NamespaceStack namespaceStack; /** the ElementHandler called as the elements are complete */ private ElementHandler elementHandler; /** the Locator */ private Locator locator; /** The name of the current entity */ private String entity; /** Flag used to indicate that we are inside a DTD section */ private boolean insideDTDSection; /** Flag used to indicate that we are inside a CDATA section */ private boolean insideCDATASection; /** * buffer to hold contents of cdata section across multiple characters * events */ private StringBuffer cdataText; /** namespaces that are available for use */ private Map availableNamespaceMap = new HashMap(); /** declared namespaces that are not yet available for use */ private List declaredNamespaceList = new ArrayList(); /** internal DTD declarations */ private List internalDTDDeclarations; /** external DTD declarations */ private List externalDTDDeclarations; /** The number of namespaces that are declared in the current scope */ private int declaredNamespaceIndex; /** The entity resolver */ private EntityResolver entityResolver; private InputSource inputSource; /** The current element we are on */ private Element currentElement; /** Should internal DTD declarations be expanded into a List in the DTD */ private boolean includeInternalDTDDeclarations = false; /** Should external DTD declarations be expanded into a List in the DTD */ private boolean includeExternalDTDDeclarations = false; /** The number of levels deep we are inside a startEntity/endEntity call */ private int entityLevel; /** Are we in an internal DTD subset? */ private boolean internalDTDsubset = false; /** Whether adjacent text nodes should be merged */ private boolean mergeAdjacentText = false; /** Have we added text to the buffer */ private boolean textInTextBuffer = false; /** Should we ignore comments */ private boolean ignoreComments = false; /** Buffer used to concatenate text together */ private StringBuffer textBuffer; /** Holds value of property stripWhitespaceText. */ private boolean stripWhitespaceText = false; public SAXContentHandler() { this(DocumentFactory.getInstance()); } public SAXContentHandler(DocumentFactory documentFactory) { this(documentFactory, null); } public SAXContentHandler(DocumentFactory documentFactory, ElementHandler elementHandler) { this(documentFactory, elementHandler, null); this.elementStack = createElementStack(); } public SAXContentHandler(DocumentFactory documentFactory, ElementHandler elementHandler, ElementStack elementStack) { this.documentFactory = documentFactory; this.elementHandler = elementHandler; this.elementStack = elementStack; this.namespaceStack = new NamespaceStack(documentFactory); } /** * DOCUMENT ME! * * @return the document that has been or is being built */ public Document getDocument() { if (document == null) { document = createDocument(); } return document; } // ContentHandler interface // ------------------------------------------------------------------------- public void setDocumentLocator(Locator documentLocator) { this.locator = documentLocator; } public void processingInstruction(String target, String data) throws SAXException { if (mergeAdjacentText && textInTextBuffer) { completeCurrentTextNode(); } if (currentElement != null) { currentElement.addProcessingInstruction(target, data); } else { getDocument().addProcessingInstruction(target, data); } } public void startPrefixMapping(String prefix, String uri) throws SAXException { namespaceStack.push(prefix, uri); } public void endPrefixMapping(String prefix) throws SAXException { namespaceStack.pop(prefix); declaredNamespaceIndex = namespaceStack.size(); } public void startDocument() throws SAXException { // document = createDocument(); document = null; currentElement = null; elementStack.clear(); if ((elementHandler != null) && (elementHandler instanceof DispatchHandler)) { elementStack.setDispatchHandler((DispatchHandler) elementHandler); } namespaceStack.clear(); declaredNamespaceIndex = 0; if (mergeAdjacentText && (textBuffer == null)) { textBuffer = new StringBuffer(); } textInTextBuffer = false; } public void endDocument() throws SAXException { namespaceStack.clear(); elementStack.clear(); currentElement = null; textBuffer = null; } public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes attributes) throws SAXException { if (mergeAdjacentText && textInTextBuffer) { completeCurrentTextNode(); } QName qName = namespaceStack.getQName(namespaceURI, localName, qualifiedName); Branch branch = currentElement; if (branch == null) { branch = getDocument(); } Element element = branch.addElement(qName); // add all declared namespaces addDeclaredNamespaces(element); // now lets add all attribute values addAttributes(element, attributes); elementStack.pushElement(element); currentElement = element; entity = null; // fixes bug527062 if (elementHandler != null) { elementHandler.onStart(elementStack); } } public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (mergeAdjacentText && textInTextBuffer) { completeCurrentTextNode(); } if ((elementHandler != null) && (currentElement != null)) { elementHandler.onEnd(elementStack); } elementStack.popElement(); currentElement = elementStack.peekElement(); } public void characters(char[] ch, int start, int end) throws SAXException { if (end == 0) { return; } if (currentElement != null) { if (entity != null) { if (mergeAdjacentText && textInTextBuffer) { completeCurrentTextNode(); } currentElement.addEntity(entity, new String(ch, start, end)); entity = null; } else if (insideCDATASection) { if (mergeAdjacentText && textInTextBuffer) { completeCurrentTextNode(); } cdataText.append(new String(ch, start, end)); } else { if (mergeAdjacentText) { textBuffer.append(ch, start, end); textInTextBuffer = true; } else { currentElement.addText(new String(ch, start, end)); } } } } // ErrorHandler interface // ------------------------------------------------------------------------- /** * This method is called when a warning occurs during the parsing of the * document. This method does nothing. * * @param exception * DOCUMENT ME! * * @throws SAXException * DOCUMENT ME! */ public void warning(SAXParseException exception) throws SAXException { // ignore warnings by default } /** * This method is called when an error is detected during parsing such as a * validation error. This method rethrows the exception * * @param exception * DOCUMENT ME! * * @throws SAXException * DOCUMENT ME! */ public void error(SAXParseException exception) throws SAXException { throw exception; } /** * This method is called when a fatal error occurs during parsing. This * method rethrows the exception * * @param exception * DOCUMENT ME! * * @throws SAXException * DOCUMENT ME! */ public void fatalError(SAXParseException exception) throws SAXException { throw exception; } // LexicalHandler interface // ------------------------------------------------------------------------- public void startDTD(String name, String publicId, String systemId) throws SAXException { getDocument().addDocType(name, publicId, systemId); insideDTDSection = true; internalDTDsubset = true; } public void endDTD() throws SAXException { insideDTDSection = false; DocumentType docType = getDocument().getDocType(); if (docType != null) { if (internalDTDDeclarations != null) { docType.setInternalDeclarations(internalDTDDeclarations); } if (externalDTDDeclarations != null) { docType.setExternalDeclarations(externalDTDDeclarations); } } internalDTDDeclarations = null; externalDTDDeclarations = null; } public void startEntity(String name) throws SAXException { ++entityLevel; // Ignore DTD references entity = null; if (!insideDTDSection) { if (!isIgnorableEntity(name)) { entity = name; } } // internal DTD subsets can only appear outside of a // startEntity/endEntity block // see the startDTD method in // http://dom4j.org/javadoc/org/xml/sax/ext/LexicalHandler.html internalDTDsubset = false; } public void endEntity(String name) throws SAXException { --entityLevel; entity = null; if (entityLevel == 0) { internalDTDsubset = true; } } public void startCDATA() throws SAXException { insideCDATASection = true; cdataText = new StringBuffer(); } public void endCDATA() throws SAXException { insideCDATASection = false; currentElement.addCDATA(cdataText.toString()); } public void comment(char[] ch, int start, int end) throws SAXException { if (!ignoreComments) { if (mergeAdjacentText && textInTextBuffer) { completeCurrentTextNode(); } String text = new String(ch, start, end); if (!insideDTDSection && (text.length() > 0)) { if (currentElement != null) { currentElement.addComment(text); } else { getDocument().addComment(text); } } } } // DeclHandler interface // ------------------------------------------------------------------------- /** * Report an element type declaration. * *

* The content model will consist of the string "EMPTY", the string "ANY", * or a parenthesised group, optionally followed by an occurrence indicator. * The model will be normalized so that all parameter entities are fully * resolved and all whitespace is removed,and will include the enclosing * parentheses. Other normalization (such as removing redundant parentheses * or simplifying occurrence indicators) is at the discretion of the parser. *

* * @param name * The element type name. * @param model * The content model as a normalized string. * * @exception SAXException * The application may raise an exception. */ public void elementDecl(String name, String model) throws SAXException { if (internalDTDsubset) { if (includeInternalDTDDeclarations) { addDTDDeclaration(new ElementDecl(name, model)); } } else { if (includeExternalDTDDeclarations) { addExternalDTDDeclaration(new ElementDecl(name, model)); } } } /** * Report an attribute type declaration. * *

* Only the effective (first) declaration for an attribute will be reported. * The type will be one of the strings "CDATA", "ID", "IDREF", "IDREFS", * "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", a parenthesized token group * with the separator "|" and all whitespace removed, or the word "NOTATION" * followed by a space followed by a parenthesized token group with all * whitespace removed. *

* *

* Any parameter entities in the attribute value will be expanded, but * general entities will not. *

* * @param eName * The name of the associated element. * @param aName * The name of the attribute. * @param type * A string representing the attribute type. * @param valueDefault * A string representing the attribute default ("#IMPLIED", * "#REQUIRED", or "#FIXED") or null if none of these applies. * @param val * A string representing the attribute's default value, or null * if there is none. * * @exception SAXException * The application may raise an exception. */ public void attributeDecl(String eName, String aName, String type, String valueDefault, String val) throws SAXException { if (internalDTDsubset) { if (includeInternalDTDDeclarations) { addDTDDeclaration(new AttributeDecl(eName, aName, type, valueDefault, val)); } } else { if (includeExternalDTDDeclarations) { addExternalDTDDeclaration(new AttributeDecl(eName, aName, type, valueDefault, val)); } } } /** * Report an internal entity declaration. * *

* Only the effective (first) declaration for each entity will be reported. * All parameter entities in the value will be expanded, but general * entities will not. *

* * @param name * The name of the entity. If it is a parameter entity, the name * will begin with '%'. * @param value * The replacement text of the entity. * * @exception SAXException * The application may raise an exception. * * @see #externalEntityDecl * @see org.xml.sax.DTDHandler#unparsedEntityDecl */ public void internalEntityDecl(String name, String value) throws SAXException { if (internalDTDsubset) { if (includeInternalDTDDeclarations) { addDTDDeclaration(new InternalEntityDecl(name, value)); } } else { if (includeExternalDTDDeclarations) { addExternalDTDDeclaration(new InternalEntityDecl(name, value)); } } } /** * Report a parsed external entity declaration. * *

* Only the effective (first) declaration for each entity will be reported. *

* * @param name * The name of the entity. If it is a parameter entity, the name * will begin with '%'. * @param publicId * The declared public identifier of the entity, or null if none * was declared. * @param sysId * The declared system identifier of the entity. * * @exception SAXException * The application may raise an exception. * * @see #internalEntityDecl * @see org.xml.sax.DTDHandler#unparsedEntityDecl */ public void externalEntityDecl(String name, String publicId, String sysId) throws SAXException { ExternalEntityDecl declaration = new ExternalEntityDecl(name, publicId, sysId); if (internalDTDsubset) { if (includeInternalDTDDeclarations) { addDTDDeclaration(declaration); } } else { if (includeExternalDTDDeclarations) { addExternalDTDDeclaration(declaration); } } } // DTDHandler interface // ------------------------------------------------------------------------- /** * Receive notification of a notation declaration event. * *

* It is up to the application to record the notation for later reference, * if necessary. *

* *

* At least one of publicId and systemId must be non-null. If a system * identifier is present, and it is a URL, the SAX parser must resolve it * fully before passing it to the application through this event. *

* *

* There is no guarantee that the notation declaration will be reported * before any unparsed entities that use it. *

* * @param name * The notation name. * @param publicId * The notation's public identifier, or null if none was given. * @param systemId * The notation's system identifier, or null if none was given. * * @exception SAXException * Any SAX exception, possibly wrapping another exception. * * @see #unparsedEntityDecl * @see org.xml.sax.AttributeList */ public void notationDecl(String name, String publicId, String systemId) throws SAXException { // #### not supported yet! } /** * Receive notification of an unparsed entity declaration event. * *

* Note that the notation name corresponds to a notation reported by the * {@link #notationDecl notationDecl}event. It is up to the application to * record the entity for later reference, if necessary. *

* *

* If the system identifier is a URL, the parser must resolve it fully * before passing it to the application. *

* * @param name * The unparsed entity's name. * @param publicId * The entity's public identifier, or null if none was given. * @param systemId * The entity's system identifier. * @param notationName * The name of the associated notation. * * @exception SAXException * Any SAX exception, possibly wrapping another exception. * * @see #notationDecl * @see org.xml.sax.AttributeList */ public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { // #### not supported yet! } // Properties // ------------------------------------------------------------------------- public ElementStack getElementStack() { return elementStack; } public void setElementStack(ElementStack elementStack) { this.elementStack = elementStack; } public EntityResolver getEntityResolver() { return entityResolver; } public void setEntityResolver(EntityResolver entityResolver) { this.entityResolver = entityResolver; } public InputSource getInputSource() { return inputSource; } public void setInputSource(InputSource inputSource) { this.inputSource = inputSource; } /** * DOCUMENT ME! * * @return whether internal DTD declarations should be expanded into the * DocumentType object or not. */ public boolean isIncludeInternalDTDDeclarations() { return includeInternalDTDDeclarations; } /** * Sets whether internal DTD declarations should be expanded into the * DocumentType object or not. * * @param include * whether or not DTD declarations should be expanded and * included into the DocumentType object. */ public void setIncludeInternalDTDDeclarations(boolean include) { this.includeInternalDTDDeclarations = include; } /** * DOCUMENT ME! * * @return whether external DTD declarations should be expanded into the * DocumentType object or not. */ public boolean isIncludeExternalDTDDeclarations() { return includeExternalDTDDeclarations; } /** * Sets whether DTD external declarations should be expanded into the * DocumentType object or not. * * @param include * whether or not DTD declarations should be expanded and * included into the DocumentType object. */ public void setIncludeExternalDTDDeclarations(boolean include) { this.includeExternalDTDDeclarations = include; } /** * Returns whether adjacent text nodes should be merged together. * * @return Value of property mergeAdjacentText. */ public boolean isMergeAdjacentText() { return mergeAdjacentText; } /** * Sets whether or not adjacent text nodes should be merged together when * parsing. * * @param mergeAdjacentText * New value of property mergeAdjacentText. */ public void setMergeAdjacentText(boolean mergeAdjacentText) { this.mergeAdjacentText = mergeAdjacentText; } /** * Sets whether whitespace between element start and end tags should be * ignored * * @return Value of property stripWhitespaceText. */ public boolean isStripWhitespaceText() { return stripWhitespaceText; } /** * Sets whether whitespace between element start and end tags should be * ignored. * * @param stripWhitespaceText * New value of property stripWhitespaceText. */ public void setStripWhitespaceText(boolean stripWhitespaceText) { this.stripWhitespaceText = stripWhitespaceText; } /** * Returns whether we should ignore comments or not. * * @return boolean */ public boolean isIgnoreComments() { return ignoreComments; } /** * Sets whether we should ignore comments or not. * * @param ignoreComments * whether we should ignore comments or not. */ public void setIgnoreComments(boolean ignoreComments) { this.ignoreComments = ignoreComments; } // Implementation methods // ------------------------------------------------------------------------- /** * If the current text buffer contains any text then create a new text node * with it and add it to the current element */ protected void completeCurrentTextNode() { if (stripWhitespaceText) { boolean whitespace = true; for (int i = 0, size = textBuffer.length(); i < size; i++) { if (!Character.isWhitespace(textBuffer.charAt(i))) { whitespace = false; break; } } if (!whitespace) { currentElement.addText(textBuffer.toString()); } } else { currentElement.addText(textBuffer.toString()); } textBuffer.setLength(0); textInTextBuffer = false; } /** * DOCUMENT ME! * * @return the current document */ protected Document createDocument() { String encoding = getEncoding(); Document doc = documentFactory.createDocument(encoding); // set the EntityResolver doc.setEntityResolver(entityResolver); if (inputSource != null) { doc.setName(inputSource.getSystemId()); } return doc; } private String getEncoding() { if (locator == null) { return null; } // use reflection to avoid dependency on Locator2 // or other locator implemenations. try { Method m = locator.getClass().getMethod("getEncoding", new Class[] {}); if (m != null) { return (String) m.invoke(locator, null); } } catch (Exception e) { // do nothing } // couldn't determine encoding, returning null... return null; } /** * a Strategy Method to determine if a given entity name is ignorable * * @param name * DOCUMENT ME! * * @return DOCUMENT ME! */ protected boolean isIgnorableEntity(String name) { return "amp".equals(name) || "apos".equals(name) || "gt".equals(name) || "lt".equals(name) || "quot".equals(name); } /** * Add all namespaces declared before the startElement() SAX event to the * current element so that they are available to child elements and * attributes * * @param element * DOCUMENT ME! */ protected void addDeclaredNamespaces(Element element) { Namespace elementNamespace = element.getNamespace(); for (int size = namespaceStack.size(); declaredNamespaceIndex < size; declaredNamespaceIndex++) { Namespace namespace = namespaceStack .getNamespace(declaredNamespaceIndex); // if ( namespace != elementNamespace ) { element.add(namespace); // } } } /** * Add all the attributes to the given elements * * @param element * DOCUMENT ME! * @param attributes * DOCUMENT ME! */ protected void addAttributes(Element element, Attributes attributes) { // XXXX: as an optimisation, we could deduce this value from the current // SAX parser settings, the SAX namespaces-prefixes feature boolean noNamespaceAttributes = false; if (element instanceof AbstractElement) { // optimised method AbstractElement baseElement = (AbstractElement) element; baseElement.setAttributes(attributes, namespaceStack, noNamespaceAttributes); } else { int size = attributes.getLength(); for (int i = 0; i < size; i++) { String attributeQName = attributes.getQName(i); if (noNamespaceAttributes || !attributeQName.startsWith("xmlns")) { String attributeURI = attributes.getURI(i); String attributeLocalName = attributes.getLocalName(i); String attributeValue = attributes.getValue(i); QName qName = namespaceStack.getAttributeQName( attributeURI, attributeLocalName, attributeQName); element.addAttribute(qName, attributeValue); } } } } /** * Adds an internal DTD declaration to the list of declarations * * @param declaration * DOCUMENT ME! */ protected void addDTDDeclaration(Object declaration) { if (internalDTDDeclarations == null) { internalDTDDeclarations = new ArrayList(); } internalDTDDeclarations.add(declaration); } /** * Adds an external DTD declaration to the list of declarations * * @param declaration * DOCUMENT ME! */ protected void addExternalDTDDeclaration(Object declaration) { if (externalDTDDeclarations == null) { externalDTDDeclarations = new ArrayList(); } externalDTDDeclarations.add(declaration); } protected ElementStack createElementStack() { return new ElementStack(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/OutputFormat.java0000644000175000017500000004633610242120020021316 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; /** *

* OutputFormat represents the format configuration used by * {@linkXMLWriter}and its base classes to format the XML output *

* * @author James Strachan * @version $Revision: 1.17 $ */ public class OutputFormat implements Cloneable { /** standard value to indent by, if we are indenting */ protected static final String STANDARD_INDENT = " "; /** * Whether or not to suppress the XML declaration - default is * false */ private boolean suppressDeclaration = false; /** * Whether or not to print new line after the XML declaration - default is * true */ private boolean newLineAfterDeclaration = true; /** The encoding format */ private String encoding = "UTF-8"; /** * Whether or not to output the encoding in the XML declaration - default is * false */ private boolean omitEncoding = false; /** The default indent is no spaces (as original document) */ private String indent = null; /** * Whether or not to expand empty elements to * <tagName></tagName> - default is false */ private boolean expandEmptyElements = false; /** * The default new line flag, set to do new lines only as in original * document */ private boolean newlines = false; /** New line separator */ private String lineSeparator = "\n"; /** should we preserve whitespace or not in text nodes? */ private boolean trimText = false; /** pad string-element boundaries with whitespace */ private boolean padText = false; /** Whether or not to use XHTML standard. */ private boolean doXHTML = false; /** * Controls when to output a line.separtor every so many tags in case of no * lines and total text trimming. */ private int newLineAfterNTags = 0; // zero means don't bother. /** Quote character to use when writing attributes. */ private char attributeQuoteChar = '\"'; /** * Creates an OutputFormat with no additional whitespace * (indent or new lines) added. The whitespace from the element text content * is fully preserved. */ public OutputFormat() { } /** * Creates an OutputFormat with the given indent added but no * new lines added. All whitespace from element text will be included. * * @param indent * is the indent string to be used for indentation (usually a * number of spaces). */ public OutputFormat(String indent) { this.indent = indent; } /** * Creates an OutputFormat with the given indent added with * optional newlines between the Elements. All whitespace from element text * will be included. * * @param indent * is the indent string to be used for indentation (usually a * number of spaces). * @param newlines * whether new lines are added to layout the */ public OutputFormat(String indent, boolean newlines) { this.indent = indent; this.newlines = newlines; } /** * Creates an OutputFormat with the given indent added with * optional newlines between the Elements and the given encoding format. * * @param indent * is the indent string to be used for indentation (usually a * number of spaces). * @param newlines * whether new lines are added to layout the * @param encoding * is the text encoding to use for writing the XML */ public OutputFormat(String indent, boolean newlines, String encoding) { this.indent = indent; this.newlines = newlines; this.encoding = encoding; } public String getLineSeparator() { return lineSeparator; } /** *

* This will set the new-line separator. The default is \n. * Note that if the "newlines" property is false, this value is irrelevant. * To make it output the system default line ending string, call * setLineSeparator(System.getProperty("line.separator")) *

* * @param separator * String line separator to use. * * @see #setNewlines(boolean) */ public void setLineSeparator(String separator) { lineSeparator = separator; } public boolean isNewlines() { return newlines; } /** * DOCUMENT ME! * * @param newlines * true indicates new lines should be printed, * else new lines are ignored (compacted). * * @see #setLineSeparator(String) */ public void setNewlines(boolean newlines) { this.newlines = newlines; } public String getEncoding() { return encoding; } /** * DOCUMENT ME! * * @param encoding * encoding format */ public void setEncoding(String encoding) { if (encoding != null) { this.encoding = encoding; } } public boolean isOmitEncoding() { return omitEncoding; } /** *

* This will set whether the XML declaration (<?xml version="1.0" * encoding="UTF-8"?>) * includes the encoding of the document. It is common to suppress this in * protocols such as WML and SOAP. *

* * @param omitEncoding * boolean indicating whether or not the XML * declaration should indicate the document encoding. */ public void setOmitEncoding(boolean omitEncoding) { this.omitEncoding = omitEncoding; } /** *

* This will set whether the XML declaration (<?xml version="1.0" * encoding="UTF-8"?>) * is included or not. It is common to suppress this in protocols such as * WML and SOAP. *

* * @param suppressDeclaration * boolean indicating whether or not the XML * declaration should be suppressed. */ public void setSuppressDeclaration(boolean suppressDeclaration) { this.suppressDeclaration = suppressDeclaration; } /** * DOCUMENT ME! * * @return true if the output of the XML declaration (<?xml * version="1.0"?>) * should be suppressed else false. */ public boolean isSuppressDeclaration() { return suppressDeclaration; } /** *

* This will set whether a new line is printed after the XML declaration * (assuming it is not supressed.) *

* * @param newLineAfterDeclaration * boolean indicating whether or not to print new * line following the XML declaration. The default is true. */ public void setNewLineAfterDeclaration(boolean newLineAfterDeclaration) { this.newLineAfterDeclaration = newLineAfterDeclaration; } /** * DOCUMENT ME! * * @return true if a new line should be printed following XML declaration */ public boolean isNewLineAfterDeclaration() { return newLineAfterDeclaration; } public boolean isExpandEmptyElements() { return expandEmptyElements; } /** *

* This will set whether empty elements are expanded from * <tagName> to * <tagName></tagName>. *

* * @param expandEmptyElements * boolean indicating whether or not empty * elements should be expanded. */ public void setExpandEmptyElements(boolean expandEmptyElements) { this.expandEmptyElements = expandEmptyElements; } public boolean isTrimText() { return trimText; } /** *

* This will set whether the text is output verbatim (false) or with * whitespace stripped as per {@link * org.dom4j.Element#getTextTrim()}. *

* *

*

* *

* Default: false *

* * @param trimText * boolean true=>trim the whitespace, false=>use * text verbatim */ public void setTrimText(boolean trimText) { this.trimText = trimText; } public boolean isPadText() { return padText; } /** *

* Ensure that text immediately preceded by or followed by an element will * be "padded" with a single space. This is used to allow make * browser-friendly HTML, avoiding trimText's transformation of, e.g., * The quick <b>brown</b> fox into The * quick<b>brown</b>fox * (the latter will run the three separate words together into a single * word). This setting is not too useful if you haven't also called * {@link #setTrimText}. *

* *

* The padding string will only be added if the text itself starts or ends * with some whitespace characters. *

* *

* Default: false *

* * @param padText * boolean if true, pad string-element boundaries */ public void setPadText(boolean padText) { this.padText = padText; } public String getIndent() { return indent; } /** *

* This will set the indent String to use; this is usually a * String of empty spaces. If you pass null, or the empty * string (""), then no indentation will happen. *

* Default: none (null) * * @param indent * String to use for indentation. */ public void setIndent(String indent) { // nullify empty string to void unnecessary indentation code if ((indent != null) && (indent.length() <= 0)) { indent = null; } this.indent = indent; } /** * Set the indent on or off. If setting on, will use the value of * STANDARD_INDENT, which is usually two spaces. * * @param doIndent * if true, set indenting on; if false, set indenting off */ public void setIndent(boolean doIndent) { if (doIndent) { this.indent = STANDARD_INDENT; } else { this.indent = null; } } /** *

* This will set the indent String's size; an indentSize of * 4 would result in the indention being equivalent to the * String "    " (four space characters). *

* * @param indentSize * int number of spaces in indentation. */ public void setIndentSize(int indentSize) { StringBuffer indentBuffer = new StringBuffer(); for (int i = 0; i < indentSize; i++) { indentBuffer.append(" "); } this.indent = indentBuffer.toString(); } /** *

* Whether or not to use the XHTML standard: like HTML but passes an XML * parser with real, closed tags. Also, XHTML CDATA sections will be output * with the CDATA delimiters: ( " <![CDATA[ " and " * ]]> " ) otherwise, the class HTMLWriter will output the * CDATA text, but not the delimiters. *

* *

* Default is false *

* * @return DOCUMENT ME! */ public boolean isXHTML() { return doXHTML; } /** *

* This will set whether or not to use the XHTML standard: like HTML but * passes an XML parser with real, closed tags. Also, XHTML CDATA sections * will be output with the CDATA delimiters: ( " <[CDATA[ * " and " ]]< ) otherwise, the class HTMLWriter * will output the CDATA text, but not the delimiters. *

* *

* Default: false *

* * @param xhtml * boolean true=>conform to XHTML, false=>conform * to HTML, can have unclosed tags, etc. */ public void setXHTML(boolean xhtml) { doXHTML = xhtml; } public int getNewLineAfterNTags() { return newLineAfterNTags; } /** * Controls output of a line.separator every tagCount tags when isNewlines * is false. If tagCount equals zero, it means don't do anything special. If * greater than zero, then a line.separator will be output after tagCount * tags have been output. Used when you would like to squeeze the html as * much as possible, but some browsers don't like really long lines. A tag * count of 10 would produce a line.separator in the output after 10 close * tags (including single tags). * * @param tagCount * DOCUMENT ME! */ public void setNewLineAfterNTags(int tagCount) { newLineAfterNTags = tagCount; } public char getAttributeQuoteCharacter() { return attributeQuoteChar; } /** * Sets the character used to quote attribute values. The specified * character must be a valid XML attribute quote character, otherwise an * IllegalArgumentException will be thrown. * * @param quoteChar * The character to use when quoting attribute values. * * @throws IllegalArgumentException * If the specified character is not a valid XML attribute quote * character. */ public void setAttributeQuoteCharacter(char quoteChar) { if ((quoteChar == '\'') || (quoteChar == '"')) { attributeQuoteChar = quoteChar; } else { throw new IllegalArgumentException("Invalid attribute quote " + "character (" + quoteChar + ")"); } } /** * Parses command line arguments of the form -omitEncoding * -indentSize 3 -newlines -trimText * * @param args * is the array of command line arguments * @param i * is the index in args to start parsing options * * @return the index of first parameter that we didn't understand */ public int parseOptions(String[] args, int i) { for (int size = args.length; i < size; i++) { if (args[i].equals("-suppressDeclaration")) { setSuppressDeclaration(true); } else if (args[i].equals("-omitEncoding")) { setOmitEncoding(true); } else if (args[i].equals("-indent")) { setIndent(args[++i]); } else if (args[i].equals("-indentSize")) { setIndentSize(Integer.parseInt(args[++i])); } else if (args[i].startsWith("-expandEmpty")) { setExpandEmptyElements(true); } else if (args[i].equals("-encoding")) { setEncoding(args[++i]); } else if (args[i].equals("-newlines")) { setNewlines(true); } else if (args[i].equals("-lineSeparator")) { setLineSeparator(args[++i]); } else if (args[i].equals("-trimText")) { setTrimText(true); } else if (args[i].equals("-padText")) { setPadText(true); } else if (args[i].startsWith("-xhtml")) { setXHTML(true); } else { return i; } } return i; } /** * A static helper method to create the default pretty printing format. This * format consists of an indent of 2 spaces, newlines after each element and * all other whitespace trimmed, and XMTML is false. * * @return DOCUMENT ME! */ public static OutputFormat createPrettyPrint() { OutputFormat format = new OutputFormat(); format.setIndentSize(2); format.setNewlines(true); format.setTrimText(true); format.setPadText(true); return format; } /** * A static helper method to create the default compact format. This format * does not have any indentation or newlines after an alement and all other * whitespace trimmed * * @return DOCUMENT ME! */ public static OutputFormat createCompactFormat() { OutputFormat format = new OutputFormat(); format.setIndent(false); format.setNewlines(false); format.setTrimText(true); return format; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/XMLWriter.java0000644000175000017500000016227210242120012020501 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.dom4j.Attribute; import org.dom4j.CDATA; import org.dom4j.Comment; import org.dom4j.Document; import org.dom4j.DocumentType; import org.dom4j.Element; import org.dom4j.Entity; import org.dom4j.Namespace; import org.dom4j.Node; import org.dom4j.ProcessingInstruction; import org.dom4j.Text; import org.dom4j.tree.NamespaceStack; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.XMLFilterImpl; /** *

* XMLWriter takes a DOM4J tree and formats it to a stream as * XML. It can also take SAX events too so can be used by SAX clients as this * object implements the {@link org.xml.sax.ContentHandler}and {@link * LexicalHandler} interfaces. as well. This formatter performs typical document * formatting. The XML declaration and processing instructions are always on * their own lines. An {@link OutputFormat}object can be used to define how * whitespace is handled when printing and allows various configuration options, * such as to allow suppression of the XML declaration, the encoding declaration * or whether empty documents are collapsed. *

* *

* There are write(...) methods to print any of the standard * DOM4J classes, including Document and Element, * to either a Writer or an OutputStream. * Warning: using your own Writer may cause the writer's * preferred character encoding to be ignored. If you use encodings other than * UTF8, we recommend using the method that takes an OutputStream instead. *

* * @author James Strachan * @author Joseph Bowbeer * @version $Revision: 1.83.2.2 $ */ public class XMLWriter extends XMLFilterImpl implements LexicalHandler { private static final String PAD_TEXT = " "; protected static final String[] LEXICAL_HANDLER_NAMES = { "http://xml.org/sax/properties/lexical-handler", "http://xml.org/sax/handlers/LexicalHandler"}; protected static final OutputFormat DEFAULT_FORMAT = new OutputFormat(); /** Should entityRefs by resolved when writing ? */ private boolean resolveEntityRefs = true; /** * Stores the last type of node written so algorithms can refer to the * previous node type */ protected int lastOutputNodeType; /** * Stores if the last written element node was a closing tag or an opening * tag. */ private boolean lastElementClosed = false; /** Stores the xml:space attribute value of preserve for whitespace flag */ protected boolean preserve = false; /** The Writer used to output to */ protected Writer writer; /** The Stack of namespaceStack written so far */ private NamespaceStack namespaceStack = new NamespaceStack(); /** The format used by this writer */ private OutputFormat format; /** whether we should escape text */ private boolean escapeText = true; /** * The initial number of indentations (so you can print a whole document * indented, if you like) */ private int indentLevel = 0; /** buffer used when escaping strings */ private StringBuffer buffer = new StringBuffer(); /** * whether we have added characters before from the same chunk of characters */ private boolean charsAdded = false; private char lastChar; /** Whether a flush should occur after writing a document */ private boolean autoFlush; /** Lexical handler we should delegate to */ private LexicalHandler lexicalHandler; /** * Whether comments should appear inside DTD declarations - defaults to * false */ private boolean showCommentsInDTDs; /** Is the writer curerntly inside a DTD definition? */ private boolean inDTD; /** The namespaces used for the current element when consuming SAX events */ private Map namespacesMap; /** * what is the maximum allowed character code such as 127 in US-ASCII (7 * bit) or 255 in ISO- (8 bit) or -1 to not escape any characters (other * than the special XML characters like < > &) */ private int maximumAllowedCharacter; public XMLWriter(Writer writer) { this(writer, DEFAULT_FORMAT); } public XMLWriter(Writer writer, OutputFormat format) { this.writer = writer; this.format = format; namespaceStack.push(Namespace.NO_NAMESPACE); } public XMLWriter() { this.format = DEFAULT_FORMAT; this.writer = new BufferedWriter(new OutputStreamWriter(System.out)); this.autoFlush = true; namespaceStack.push(Namespace.NO_NAMESPACE); } public XMLWriter(OutputStream out) throws UnsupportedEncodingException { this.format = DEFAULT_FORMAT; this.writer = createWriter(out, format.getEncoding()); this.autoFlush = true; namespaceStack.push(Namespace.NO_NAMESPACE); } public XMLWriter(OutputStream out, OutputFormat format) throws UnsupportedEncodingException { this.format = format; this.writer = createWriter(out, format.getEncoding()); this.autoFlush = true; namespaceStack.push(Namespace.NO_NAMESPACE); } public XMLWriter(OutputFormat format) throws UnsupportedEncodingException { this.format = format; this.writer = createWriter(System.out, format.getEncoding()); this.autoFlush = true; namespaceStack.push(Namespace.NO_NAMESPACE); } public void setWriter(Writer writer) { this.writer = writer; this.autoFlush = false; } public void setOutputStream(OutputStream out) throws UnsupportedEncodingException { this.writer = createWriter(out, format.getEncoding()); this.autoFlush = true; } /** * DOCUMENT ME! * * @return true if text thats output should be escaped. This is enabled by * default. It could be disabled if the output format is textual, * like in XSLT where we can have xml, html or text output. */ public boolean isEscapeText() { return escapeText; } /** * Sets whether text output should be escaped or not. This is enabled by * default. It could be disabled if the output format is textual, like in * XSLT where we can have xml, html or text output. * * @param escapeText * DOCUMENT ME! */ public void setEscapeText(boolean escapeText) { this.escapeText = escapeText; } /** * Set the initial indentation level. This can be used to output a document * (or, more likely, an element) starting at a given indent level, so it's * not always flush against the left margin. Default: 0 * * @param indentLevel * the number of indents to start with */ public void setIndentLevel(int indentLevel) { this.indentLevel = indentLevel; } /** * Returns the maximum allowed character code that should be allowed * unescaped which defaults to 127 in US-ASCII (7 bit) or 255 in ISO- (8 * bit). * * @return DOCUMENT ME! */ public int getMaximumAllowedCharacter() { if (maximumAllowedCharacter == 0) { maximumAllowedCharacter = defaultMaximumAllowedCharacter(); } return maximumAllowedCharacter; } /** * Sets the maximum allowed character code that should be allowed unescaped * such as 127 in US-ASCII (7 bit) or 255 in ISO- (8 bit) or -1 to not * escape any characters (other than the special XML characters like < * > &) If this is not explicitly set then it is defaulted from the * encoding. * * @param maximumAllowedCharacter * The maximumAllowedCharacter to set */ public void setMaximumAllowedCharacter(int maximumAllowedCharacter) { this.maximumAllowedCharacter = maximumAllowedCharacter; } /** * Flushes the underlying Writer * * @throws IOException * DOCUMENT ME! */ public void flush() throws IOException { writer.flush(); } /** * Closes the underlying Writer * * @throws IOException * DOCUMENT ME! */ public void close() throws IOException { writer.close(); } /** * Writes the new line text to the underlying Writer * * @throws IOException * DOCUMENT ME! */ public void println() throws IOException { writer.write(format.getLineSeparator()); } /** * Writes the given {@link Attribute}. * * @param attribute * Attribute to output. * * @throws IOException * DOCUMENT ME! */ public void write(Attribute attribute) throws IOException { writeAttribute(attribute); if (autoFlush) { flush(); } } /** *

* This will print the Document to the current Writer. *

* *

* Warning: using your own Writer may cause the writer's preferred character * encoding to be ignored. If you use encodings other than UTF8, we * recommend using the method that takes an OutputStream instead. *

* *

* Note: as with all Writers, you may need to flush() yours after this * method returns. *

* * @param doc * Document to format. * * @throws IOException * if there's any problem writing. */ public void write(Document doc) throws IOException { writeDeclaration(); if (doc.getDocType() != null) { indent(); writeDocType(doc.getDocType()); } for (int i = 0, size = doc.nodeCount(); i < size; i++) { Node node = doc.node(i); writeNode(node); } writePrintln(); if (autoFlush) { flush(); } } /** *

* Writes the {@link Element}, including its {@link * Attribute} * s, and its value, and all its content (child nodes) to the current * Writer. *

* * @param element * Element to output. * * @throws IOException * DOCUMENT ME! */ public void write(Element element) throws IOException { writeElement(element); if (autoFlush) { flush(); } } /** * Writes the given {@link CDATA}. * * @param cdata * CDATA to output. * * @throws IOException * DOCUMENT ME! */ public void write(CDATA cdata) throws IOException { writeCDATA(cdata.getText()); if (autoFlush) { flush(); } } /** * Writes the given {@link Comment}. * * @param comment * Comment to output. * * @throws IOException * DOCUMENT ME! */ public void write(Comment comment) throws IOException { writeComment(comment.getText()); if (autoFlush) { flush(); } } /** * Writes the given {@link DocumentType}. * * @param docType * DocumentType to output. * * @throws IOException * DOCUMENT ME! */ public void write(DocumentType docType) throws IOException { writeDocType(docType); if (autoFlush) { flush(); } } /** * Writes the given {@link Entity}. * * @param entity * Entity to output. * * @throws IOException * DOCUMENT ME! */ public void write(Entity entity) throws IOException { writeEntity(entity); if (autoFlush) { flush(); } } /** * Writes the given {@link Namespace}. * * @param namespace * Namespace to output. * * @throws IOException * DOCUMENT ME! */ public void write(Namespace namespace) throws IOException { writeNamespace(namespace); if (autoFlush) { flush(); } } /** * Writes the given {@link ProcessingInstruction}. * * @param processingInstruction * ProcessingInstruction to output. * * @throws IOException * DOCUMENT ME! */ public void write(ProcessingInstruction processingInstruction) throws IOException { writeProcessingInstruction(processingInstruction); if (autoFlush) { flush(); } } /** *

* Print out a {@link String}, Perfoms the necessary entity escaping and * whitespace stripping. *

* * @param text * is the text to output * * @throws IOException * DOCUMENT ME! */ public void write(String text) throws IOException { writeString(text); if (autoFlush) { flush(); } } /** * Writes the given {@link Text}. * * @param text * Text to output. * * @throws IOException * DOCUMENT ME! */ public void write(Text text) throws IOException { writeString(text.getText()); if (autoFlush) { flush(); } } /** * Writes the given {@link Node}. * * @param node * Node to output. * * @throws IOException * DOCUMENT ME! */ public void write(Node node) throws IOException { writeNode(node); if (autoFlush) { flush(); } } /** * Writes the given object which should be a String, a Node or a List of * Nodes. * * @param object * is the object to output. * * @throws IOException * DOCUMENT ME! */ public void write(Object object) throws IOException { if (object instanceof Node) { write((Node) object); } else if (object instanceof String) { write((String) object); } else if (object instanceof List) { List list = (List) object; for (int i = 0, size = list.size(); i < size; i++) { write(list.get(i)); } } else if (object != null) { throw new IOException("Invalid object: " + object); } } /** *

* Writes the opening tag of an {@link Element}, including its {@link * Attribute}s but without its content. *

* * @param element * Element to output. * * @throws IOException * DOCUMENT ME! */ public void writeOpen(Element element) throws IOException { writer.write("<"); writer.write(element.getQualifiedName()); writeAttributes(element); writer.write(">"); } /** *

* Writes the closing tag of an {@link Element} *

* * @param element * Element to output. * * @throws IOException * DOCUMENT ME! */ public void writeClose(Element element) throws IOException { writeClose(element.getQualifiedName()); } // XMLFilterImpl methods // ------------------------------------------------------------------------- public void parse(InputSource source) throws IOException, SAXException { installLexicalHandler(); super.parse(source); } public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) { if (LEXICAL_HANDLER_NAMES[i].equals(name)) { setLexicalHandler((LexicalHandler) value); return; } } super.setProperty(name, value); } public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException { for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) { if (LEXICAL_HANDLER_NAMES[i].equals(name)) { return getLexicalHandler(); } } return super.getProperty(name); } public void setLexicalHandler(LexicalHandler handler) { if (handler == null) { throw new NullPointerException("Null lexical handler"); } else { this.lexicalHandler = handler; } } public LexicalHandler getLexicalHandler() { return lexicalHandler; } // ContentHandler interface // ------------------------------------------------------------------------- public void setDocumentLocator(Locator locator) { super.setDocumentLocator(locator); } public void startDocument() throws SAXException { try { writeDeclaration(); super.startDocument(); } catch (IOException e) { handleException(e); } } public void endDocument() throws SAXException { super.endDocument(); if (autoFlush) { try { flush(); } catch (IOException e) { } } } public void startPrefixMapping(String prefix, String uri) throws SAXException { if (namespacesMap == null) { namespacesMap = new HashMap(); } namespacesMap.put(prefix, uri); super.startPrefixMapping(prefix, uri); } public void endPrefixMapping(String prefix) throws SAXException { super.endPrefixMapping(prefix); } public void startElement(String namespaceURI, String localName, String qName, Attributes attributes) throws SAXException { try { charsAdded = false; writePrintln(); indent(); writer.write("<"); writer.write(qName); writeNamespaces(); writeAttributes(attributes); writer.write(">"); ++indentLevel; lastOutputNodeType = Node.ELEMENT_NODE; lastElementClosed = false; super.startElement(namespaceURI, localName, qName, attributes); } catch (IOException e) { handleException(e); } } public void endElement(String namespaceURI, String localName, String qName) throws SAXException { try { charsAdded = false; --indentLevel; if (lastElementClosed) { writePrintln(); indent(); } // XXXX: need to determine this using a stack and checking for // content / children boolean hadContent = true; if (hadContent) { writeClose(qName); } else { writeEmptyElementClose(qName); } lastOutputNodeType = Node.ELEMENT_NODE; lastElementClosed = true; super.endElement(namespaceURI, localName, qName); } catch (IOException e) { handleException(e); } } public void characters(char[] ch, int start, int length) throws SAXException { if ((ch == null) || (ch.length == 0) || (length <= 0)) { return; } try { /* * we can't use the writeString method here because it's possible we * don't receive all characters at once and calling writeString * would cause unwanted spaces to be added in between these chunks * of character arrays. */ String string = String.valueOf(ch, start, length); if (escapeText) { string = escapeElementEntities(string); } if (format.isTrimText()) { if ((lastOutputNodeType == Node.TEXT_NODE) && !charsAdded) { writer.write(' '); } else if (charsAdded && Character.isWhitespace(lastChar)) { writer.write(' '); } else if (lastOutputNodeType == Node.ELEMENT_NODE && format.isPadText() && lastElementClosed && Character.isWhitespace(ch[0])) { writer.write(PAD_TEXT); } String delim = ""; StringTokenizer tokens = new StringTokenizer(string); while (tokens.hasMoreTokens()) { writer.write(delim); writer.write(tokens.nextToken()); delim = " "; } } else { writer.write(string); } charsAdded = true; lastChar = ch[(start + length) - 1]; lastOutputNodeType = Node.TEXT_NODE; super.characters(ch, start, length); } catch (IOException e) { handleException(e); } } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { super.ignorableWhitespace(ch, start, length); } public void processingInstruction(String target, String data) throws SAXException { try { indent(); writer.write(""); writePrintln(); lastOutputNodeType = Node.PROCESSING_INSTRUCTION_NODE; super.processingInstruction(target, data); } catch (IOException e) { handleException(e); } } // DTDHandler interface // ------------------------------------------------------------------------- public void notationDecl(String name, String publicID, String systemID) throws SAXException { super.notationDecl(name, publicID, systemID); } public void unparsedEntityDecl(String name, String publicID, String systemID, String notationName) throws SAXException { super.unparsedEntityDecl(name, publicID, systemID, notationName); } // LexicalHandler interface // ------------------------------------------------------------------------- public void startDTD(String name, String publicID, String systemID) throws SAXException { inDTD = true; try { writeDocType(name, publicID, systemID); } catch (IOException e) { handleException(e); } if (lexicalHandler != null) { lexicalHandler.startDTD(name, publicID, systemID); } } public void endDTD() throws SAXException { inDTD = false; if (lexicalHandler != null) { lexicalHandler.endDTD(); } } public void startCDATA() throws SAXException { try { writer.write(""); } catch (IOException e) { handleException(e); } if (lexicalHandler != null) { lexicalHandler.endCDATA(); } } public void startEntity(String name) throws SAXException { try { writeEntityRef(name); } catch (IOException e) { handleException(e); } if (lexicalHandler != null) { lexicalHandler.startEntity(name); } } public void endEntity(String name) throws SAXException { if (lexicalHandler != null) { lexicalHandler.endEntity(name); } } public void comment(char[] ch, int start, int length) throws SAXException { if (showCommentsInDTDs || !inDTD) { try { charsAdded = false; writeComment(new String(ch, start, length)); } catch (IOException e) { handleException(e); } } if (lexicalHandler != null) { lexicalHandler.comment(ch, start, length); } } // Implementation methods // ------------------------------------------------------------------------- protected void writeElement(Element element) throws IOException { int size = element.nodeCount(); String qualifiedName = element.getQualifiedName(); writePrintln(); indent(); writer.write("<"); writer.write(qualifiedName); int previouslyDeclaredNamespaces = namespaceStack.size(); Namespace ns = element.getNamespace(); if (isNamespaceDeclaration(ns)) { namespaceStack.push(ns); writeNamespace(ns); } // Print out additional namespace declarations boolean textOnly = true; for (int i = 0; i < size; i++) { Node node = element.node(i); if (node instanceof Namespace) { Namespace additional = (Namespace) node; if (isNamespaceDeclaration(additional)) { namespaceStack.push(additional); writeNamespace(additional); } } else if (node instanceof Element) { textOnly = false; } else if (node instanceof Comment) { textOnly = false; } } writeAttributes(element); lastOutputNodeType = Node.ELEMENT_NODE; if (size <= 0) { writeEmptyElementClose(qualifiedName); } else { writer.write(">"); if (textOnly) { // we have at least one text node so lets assume // that its non-empty writeElementContent(element); } else { // we know it's not null or empty from above ++indentLevel; writeElementContent(element); --indentLevel; writePrintln(); indent(); } writer.write(""); } // remove declared namespaceStack from stack while (namespaceStack.size() > previouslyDeclaredNamespaces) { namespaceStack.pop(); } lastOutputNodeType = Node.ELEMENT_NODE; } /** * Determines if element is a special case of XML elements where it contains * an xml:space attribute of "preserve". If it does, then retain whitespace. * * @param element * DOCUMENT ME! * * @return DOCUMENT ME! */ protected final boolean isElementSpacePreserved(Element element) { final Attribute attr = (Attribute) element.attribute("space"); boolean preserveFound = preserve; // default to global state if (attr != null) { if ("xml".equals(attr.getNamespacePrefix()) && "preserve".equals(attr.getText())) { preserveFound = true; } else { preserveFound = false; } } return preserveFound; } /** * Outputs the content of the given element. If whitespace trimming is * enabled then all adjacent text nodes are appended together before the * whitespace trimming occurs to avoid problems with multiple text nodes * being created due to text content that spans parser buffers in a SAX * parser. * * @param element * DOCUMENT ME! * * @throws IOException * DOCUMENT ME! */ protected void writeElementContent(Element element) throws IOException { boolean trim = format.isTrimText(); boolean oldPreserve = preserve; if (trim) { // verify we have to before more expensive test preserve = isElementSpacePreserved(element); trim = !preserve; } if (trim) { // concatenate adjacent text nodes together // so that whitespace trimming works properly Text lastTextNode = null; StringBuffer buff = null; boolean textOnly = true; for (int i = 0, size = element.nodeCount(); i < size; i++) { Node node = element.node(i); if (node instanceof Text) { if (lastTextNode == null) { lastTextNode = (Text) node; } else { if (buff == null) { buff = new StringBuffer(lastTextNode.getText()); } buff.append(((Text) node).getText()); } } else { if (!textOnly && format.isPadText()) { // only add the PAD_TEXT if the text itself starts with // whitespace char firstChar = 'a'; if (buff != null) { firstChar = buff.charAt(0); } else if (lastTextNode != null) { firstChar = lastTextNode.getText().charAt(0); } if (Character.isWhitespace(firstChar)) { writer.write(PAD_TEXT); } } if (lastTextNode != null) { if (buff != null) { writeString(buff.toString()); buff = null; } else { writeString(lastTextNode.getText()); } if (format.isPadText()) { // only add the PAD_TEXT if the text itself ends // with whitespace char lastTextChar = 'a'; if (buff != null) { lastTextChar = buff.charAt(buff.length() - 1); } else if (lastTextNode != null) { String txt = lastTextNode.getText(); lastTextChar = txt.charAt(txt.length() - 1); } if (Character.isWhitespace(lastTextChar)) { writer.write(PAD_TEXT); } } lastTextNode = null; } textOnly = false; writeNode(node); } } if (lastTextNode != null) { if (!textOnly && format.isPadText()) { // only add the PAD_TEXT if the text itself starts with // whitespace char firstChar = 'a'; if (buff != null) { firstChar = buff.charAt(0); } else { firstChar = lastTextNode.getText().charAt(0); } if (Character.isWhitespace(firstChar)) { writer.write(PAD_TEXT); } } if (buff != null) { writeString(buff.toString()); buff = null; } else { writeString(lastTextNode.getText()); } lastTextNode = null; } } else { Node lastTextNode = null; for (int i = 0, size = element.nodeCount(); i < size; i++) { Node node = element.node(i); if (node instanceof Text) { writeNode(node); lastTextNode = node; } else { if ((lastTextNode != null) && format.isPadText()) { // only add the PAD_TEXT if the text itself ends with // whitespace String txt = lastTextNode.getText(); char lastTextChar = txt.charAt(txt.length() - 1); if (Character.isWhitespace(lastTextChar)) { writer.write(PAD_TEXT); } } writeNode(node); // if ((lastTextNode != null) && format.isPadText()) { // writer.write(PAD_TEXT); // } lastTextNode = null; } } } preserve = oldPreserve; } protected void writeCDATA(String text) throws IOException { writer.write(""); lastOutputNodeType = Node.CDATA_SECTION_NODE; } protected void writeDocType(DocumentType docType) throws IOException { if (docType != null) { docType.write(writer); writePrintln(); } } protected void writeNamespace(Namespace namespace) throws IOException { if (namespace != null) { writeNamespace(namespace.getPrefix(), namespace.getURI()); } } /** * Writes the SAX namepsaces * * @throws IOException * DOCUMENT ME! */ protected void writeNamespaces() throws IOException { if (namespacesMap != null) { for (Iterator iter = namespacesMap.entrySet().iterator(); iter .hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String prefix = (String) entry.getKey(); String uri = (String) entry.getValue(); writeNamespace(prefix, uri); } namespacesMap = null; } } /** * Writes the SAX namepsaces * * @param prefix * the prefix * @param uri * the namespace uri * * @throws IOException */ protected void writeNamespace(String prefix, String uri) throws IOException { if ((prefix != null) && (prefix.length() > 0)) { writer.write(" xmlns:"); writer.write(prefix); writer.write("=\""); } else { writer.write(" xmlns=\""); } writer.write(uri); writer.write("\""); } protected void writeProcessingInstruction(ProcessingInstruction pi) throws IOException { // indent(); writer.write(""); writePrintln(); lastOutputNodeType = Node.PROCESSING_INSTRUCTION_NODE; } protected void writeString(String text) throws IOException { if ((text != null) && (text.length() > 0)) { if (escapeText) { text = escapeElementEntities(text); } // if (format.isPadText()) { // if (lastOutputNodeType == Node.ELEMENT_NODE) { // writer.write(PAD_TEXT); // } // } if (format.isTrimText()) { boolean first = true; StringTokenizer tokenizer = new StringTokenizer(text); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (first) { first = false; if (lastOutputNodeType == Node.TEXT_NODE) { writer.write(" "); } } else { writer.write(" "); } writer.write(token); lastOutputNodeType = Node.TEXT_NODE; lastChar = token.charAt(token.length() - 1); } } else { lastOutputNodeType = Node.TEXT_NODE; writer.write(text); lastChar = text.charAt(text.length() - 1); } } } /** * This method is used to write out Nodes that contain text and still allow * for xml:space to be handled properly. * * @param node * DOCUMENT ME! * * @throws IOException * DOCUMENT ME! */ protected void writeNodeText(Node node) throws IOException { String text = node.getText(); if ((text != null) && (text.length() > 0)) { if (escapeText) { text = escapeElementEntities(text); } lastOutputNodeType = Node.TEXT_NODE; writer.write(text); lastChar = text.charAt(text.length() - 1); } } protected void writeNode(Node node) throws IOException { int nodeType = node.getNodeType(); switch (nodeType) { case Node.ELEMENT_NODE: writeElement((Element) node); break; case Node.ATTRIBUTE_NODE: writeAttribute((Attribute) node); break; case Node.TEXT_NODE: writeNodeText(node); // write((Text) node); break; case Node.CDATA_SECTION_NODE: writeCDATA(node.getText()); break; case Node.ENTITY_REFERENCE_NODE: writeEntity((Entity) node); break; case Node.PROCESSING_INSTRUCTION_NODE: writeProcessingInstruction((ProcessingInstruction) node); break; case Node.COMMENT_NODE: writeComment(node.getText()); break; case Node.DOCUMENT_NODE: write((Document) node); break; case Node.DOCUMENT_TYPE_NODE: writeDocType((DocumentType) node); break; case Node.NAMESPACE_NODE: // Will be output with attributes // write((Namespace) node); break; default: throw new IOException("Invalid node type: " + node); } } protected void installLexicalHandler() { XMLReader parent = getParent(); if (parent == null) { throw new NullPointerException("No parent for filter"); } // try to register for lexical events for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) { try { parent.setProperty(LEXICAL_HANDLER_NAMES[i], this); break; } catch (SAXNotRecognizedException ex) { // ignore } catch (SAXNotSupportedException ex) { // ignore } } } protected void writeDocType(String name, String publicID, String systemID) throws IOException { boolean hasPublic = false; writer.write(""); writePrintln(); } protected void writeEntity(Entity entity) throws IOException { if (!resolveEntityRefs()) { writeEntityRef(entity.getName()); } else { writer.write(entity.getText()); } } protected void writeEntityRef(String name) throws IOException { writer.write("&"); writer.write(name); writer.write(";"); lastOutputNodeType = Node.ENTITY_REFERENCE_NODE; } protected void writeComment(String text) throws IOException { if (format.isNewlines()) { println(); indent(); } writer.write(""); lastOutputNodeType = Node.COMMENT_NODE; } /** * Writes the attributes of the given element * * @param element * DOCUMENT ME! * * @throws IOException * DOCUMENT ME! */ protected void writeAttributes(Element element) throws IOException { // I do not yet handle the case where the same prefix maps to // two different URIs. For attributes on the same element // this is illegal; but as yet we don't throw an exception // if someone tries to do this for (int i = 0, size = element.attributeCount(); i < size; i++) { Attribute attribute = element.attribute(i); Namespace ns = attribute.getNamespace(); if ((ns != null) && (ns != Namespace.NO_NAMESPACE) && (ns != Namespace.XML_NAMESPACE)) { String prefix = ns.getPrefix(); String uri = namespaceStack.getURI(prefix); if (!ns.getURI().equals(uri)) { writeNamespace(ns); namespaceStack.push(ns); } } // If the attribute is a namespace declaration, check if we have // already written that declaration elsewhere (if that's the case, // it must be in the namespace stack String attName = attribute.getName(); if (attName.startsWith("xmlns:")) { String prefix = attName.substring(6); if (namespaceStack.getNamespaceForPrefix(prefix) == null) { String uri = attribute.getValue(); namespaceStack.push(prefix, uri); writeNamespace(prefix, uri); } } else if (attName.equals("xmlns")) { if (namespaceStack.getDefaultNamespace() == null) { String uri = attribute.getValue(); namespaceStack.push(null, uri); writeNamespace(null, uri); } } else { char quote = format.getAttributeQuoteCharacter(); writer.write(" "); writer.write(attribute.getQualifiedName()); writer.write("="); writer.write(quote); writeEscapeAttributeEntities(attribute.getValue()); writer.write(quote); } } } protected void writeAttribute(Attribute attribute) throws IOException { writer.write(" "); writer.write(attribute.getQualifiedName()); writer.write("="); char quote = format.getAttributeQuoteCharacter(); writer.write(quote); writeEscapeAttributeEntities(attribute.getValue()); writer.write(quote); lastOutputNodeType = Node.ATTRIBUTE_NODE; } protected void writeAttributes(Attributes attributes) throws IOException { for (int i = 0, size = attributes.getLength(); i < size; i++) { writeAttribute(attributes, i); } } protected void writeAttribute(Attributes attributes, int index) throws IOException { char quote = format.getAttributeQuoteCharacter(); writer.write(" "); writer.write(attributes.getQName(index)); writer.write("="); writer.write(quote); writeEscapeAttributeEntities(attributes.getValue(index)); writer.write(quote); } protected void indent() throws IOException { String indent = format.getIndent(); if ((indent != null) && (indent.length() > 0)) { for (int i = 0; i < indentLevel; i++) { writer.write(indent); } } } /** *

* This will print a new line only if the newlines flag was set to true *

* * @throws IOException * DOCUMENT ME! */ protected void writePrintln() throws IOException { if (format.isNewlines()) { String seperator = format.getLineSeparator(); if (lastChar != seperator.charAt(seperator.length() - 1)) { writer.write(format.getLineSeparator()); } } } /** * Get an OutputStreamWriter, use preferred encoding. * * @param outStream * DOCUMENT ME! * @param encoding * DOCUMENT ME! * * @return DOCUMENT ME! * * @throws UnsupportedEncodingException * DOCUMENT ME! */ protected Writer createWriter(OutputStream outStream, String encoding) throws UnsupportedEncodingException { return new BufferedWriter(new OutputStreamWriter(outStream, encoding)); } /** *

* This will write the declaration to the given Writer. Assumes XML version * 1.0 since we don't directly know. *

* * @throws IOException * DOCUMENT ME! */ protected void writeDeclaration() throws IOException { String encoding = format.getEncoding(); // Only print of declaration is not suppressed if (!format.isSuppressDeclaration()) { // Assume 1.0 version if (encoding.equals("UTF8")) { writer.write(""); } else { writer.write(""); } if (format.isNewLineAfterDeclaration()) { println(); } } } protected void writeClose(String qualifiedName) throws IOException { writer.write(""); } protected void writeEmptyElementClose(String qualifiedName) throws IOException { // Simply close up if (!format.isExpandEmptyElements()) { writer.write("/>"); } else { writer.write(">"); } } protected boolean isExpandEmptyElements() { return format.isExpandEmptyElements(); } /** * This will take the pre-defined entities in XML 1.0 and convert their * character representation to the appropriate entity reference, suitable * for XML attributes. * * @param text * DOCUMENT ME! * * @return DOCUMENT ME! */ protected String escapeElementEntities(String text) { char[] block = null; int i; int last = 0; int size = text.length(); for (i = 0; i < size; i++) { String entity = null; char c = text.charAt(i); switch (c) { case '<': entity = "<"; break; case '>': entity = ">"; break; case '&': entity = "&"; break; case '\t': case '\n': case '\r': // don't encode standard whitespace characters if (preserve) { entity = String.valueOf(c); } break; default: if ((c < 32) || shouldEncodeChar(c)) { entity = "&#" + (int) c + ";"; } break; } if (entity != null) { if (block == null) { block = text.toCharArray(); } buffer.append(block, last, i - last); buffer.append(entity); last = i + 1; } } if (last == 0) { return text; } if (last < size) { if (block == null) { block = text.toCharArray(); } buffer.append(block, last, i - last); } String answer = buffer.toString(); buffer.setLength(0); return answer; } protected void writeEscapeAttributeEntities(String txt) throws IOException { if (txt != null) { String escapedText = escapeAttributeEntities(txt); writer.write(escapedText); } } /** * This will take the pre-defined entities in XML 1.0 and convert their * character representation to the appropriate entity reference, suitable * for XML attributes. * * @param text * DOCUMENT ME! * * @return DOCUMENT ME! */ protected String escapeAttributeEntities(String text) { char quote = format.getAttributeQuoteCharacter(); char[] block = null; int i; int last = 0; int size = text.length(); for (i = 0; i < size; i++) { String entity = null; char c = text.charAt(i); switch (c) { case '<': entity = "<"; break; case '>': entity = ">"; break; case '\'': if (quote == '\'') { entity = "'"; } break; case '\"': if (quote == '\"') { entity = """; } break; case '&': entity = "&"; break; case '\t': case '\n': case '\r': // don't encode standard whitespace characters break; default: if ((c < 32) || shouldEncodeChar(c)) { entity = "&#" + (int) c + ";"; } break; } if (entity != null) { if (block == null) { block = text.toCharArray(); } buffer.append(block, last, i - last); buffer.append(entity); last = i + 1; } } if (last == 0) { return text; } if (last < size) { if (block == null) { block = text.toCharArray(); } buffer.append(block, last, i - last); } String answer = buffer.toString(); buffer.setLength(0); return answer; } /** * Should the given character be escaped. This depends on the encoding of * the document. * * @param c * DOCUMENT ME! * * @return boolean */ protected boolean shouldEncodeChar(char c) { int max = getMaximumAllowedCharacter(); return (max > 0) && (c > max); } /** * Returns the maximum allowed character code that should be allowed * unescaped which defaults to 127 in US-ASCII (7 bit) or 255 in ISO- (8 * bit). * * @return DOCUMENT ME! */ protected int defaultMaximumAllowedCharacter() { String encoding = format.getEncoding(); if (encoding != null) { if (encoding.equals("US-ASCII")) { return 127; } } // no encoding for things like ISO-*, UTF-8 or UTF-16 return -1; } protected boolean isNamespaceDeclaration(Namespace ns) { if ((ns != null) && (ns != Namespace.XML_NAMESPACE)) { String uri = ns.getURI(); if (uri != null) { if (!namespaceStack.contains(ns)) { return true; } } } return false; } protected void handleException(IOException e) throws SAXException { throw new SAXException(e); } // Laramie Crocker 4/8/2002 10:38AM /** * Lets subclasses get at the current format object, so they can call * setTrimText, setNewLines, etc. Put in to support the HTMLWriter, in the * way that it pushes the current newline/trim state onto a stack and * overrides the state within preformatted tags. * * @return DOCUMENT ME! */ protected OutputFormat getOutputFormat() { return format; } public boolean resolveEntityRefs() { return resolveEntityRefs; } public void setResolveEntityRefs(boolean resolve) { this.resolveEntityRefs = resolve; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/DispatchHandler.java0000644000175000017500000002133510242120021021673 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.util.ArrayList; import java.util.HashMap; import org.dom4j.Element; import org.dom4j.ElementHandler; import org.dom4j.ElementPath; /** *

* DispatchHandler implements the ElementHandler * interface and provides a means to register multiple * ElementHandler instances to be used by an event based * processor. This is a special ElementHandler in that it's * onStart and onEnd implementation methods are called for every * element encountered during the parse. It then delegates to other * ElementHandler instances registered with it to process the * elements encountered. *

* * @author Dave White * @version $Revision: 1.11 $ */ class DispatchHandler implements ElementHandler { /** Whether the parser is at the root element or not */ private boolean atRoot; /** The current path in the XML tree (i.e. /a/b/c) */ private String path; /** maintains a stack of previously encountered paths */ private ArrayList pathStack; /** maintains a stack of previously encountered handlers */ private ArrayList handlerStack; /** * HashMap maintains the mapping between element paths and * handlers */ private HashMap handlers; /** * ElementHandler to use by default for element paths with no * handlers registered */ private ElementHandler defaultHandler; public DispatchHandler() { atRoot = true; path = "/"; pathStack = new ArrayList(); handlerStack = new ArrayList(); handlers = new HashMap(); } /** * Adds the ElementHandler to be called when the specified * path is encounted. * * @param handlerPath * is the path to be handled * @param handler * is the ElementHandler to be called by the event * based processor. */ public void addHandler(String handlerPath, ElementHandler handler) { handlers.put(handlerPath, handler); } /** * Removes the ElementHandler from the event based processor, * for the specified path. * * @param handlerPath * is the path to remove the ElementHandler for. * * @return DOCUMENT ME! */ public ElementHandler removeHandler(String handlerPath) { return (ElementHandler) handlers.remove(handlerPath); } /** * DOCUMENT ME! * * @param handlerPath * DOCUMENT ME! * * @return true when an ElementHandler is registered for the * specified path. */ public boolean containsHandler(String handlerPath) { return handlers.containsKey(handlerPath); } /** * Get the registered {@link ElementHandler}for the specified path. * * @param handlerPath * XML path to get the handler for * * @return the registered handler */ public ElementHandler getHandler(String handlerPath) { return (ElementHandler) handlers.get(handlerPath); } /** * Returns the number of {@link ElementHandler}objects that are waiting for * their elements closing tag. * * @return number of active handlers */ public int getActiveHandlerCount() { return handlerStack.size(); } /** * When multiple ElementHandler instances have been * registered, this will set a default ElementHandler to be * called for any path which does NOT have a handler registered. * * @param handler * is the ElementHandler to be called by the event * based processor. */ public void setDefaultHandler(ElementHandler handler) { defaultHandler = handler; } /** * Used to remove all the Element Handlers and return things back to the way * they were when object was created. */ public void resetHandlers() { atRoot = true; path = "/"; pathStack.clear(); handlerStack.clear(); handlers.clear(); defaultHandler = null; } /** * DOCUMENT ME! * * @return the current path for the parse */ public String getPath() { return path; } // The following methods implement the ElementHandler interface public void onStart(ElementPath elementPath) { Element element = elementPath.getCurrent(); // Save the location of the last (i.e. parent) path pathStack.add(path); // Calculate the new path if (atRoot) { path = path + element.getName(); atRoot = false; } else { path = path + "/" + element.getName(); } if ((handlers != null) && (handlers.containsKey(path))) { // The current node has a handler associated with it. // Find the handler and save it on the handler stack. ElementHandler handler = (ElementHandler) handlers.get(path); handlerStack.add(handler); // Call the handlers onStart method. handler.onStart(elementPath); } else { // No handler is associated with this node, so use the // defaultHandler it it exists. if (handlerStack.isEmpty() && (defaultHandler != null)) { defaultHandler.onStart(elementPath); } } } public void onEnd(ElementPath elementPath) { if ((handlers != null) && (handlers.containsKey(path))) { // This node has a handler associated with it. // Find the handler and pop it from the handler stack. ElementHandler handler = (ElementHandler) handlers.get(path); handlerStack.remove(handlerStack.size() - 1); // Call the handlers onEnd method handler.onEnd(elementPath); } else { // No handler is associated with this node, so use the // defaultHandler it it exists. if (handlerStack.isEmpty() && (defaultHandler != null)) { defaultHandler.onEnd(elementPath); } } // Set path back to its parent path = (String) pathStack.remove(pathStack.size() - 1); if (pathStack.size() == 0) { atRoot = true; } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/PruningDispatchHandler.java0000644000175000017500000000517410242120022023242 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import org.dom4j.ElementPath; /** * This extension on the {@link DispatchHandler}prunes the current {@link * org.dom4j.Element} when there are no {@link ElementHandler}objects active * the element. * * @author Wonne keysers (Realsoftware) */ class PruningDispatchHandler extends DispatchHandler { public void onEnd(ElementPath elementPath) { super.onEnd(elementPath); if (getActiveHandlerCount() == 0) { elementPath.getCurrent().detach(); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/DOMWriter.java0000644000175000017500000003547310242120010020460 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.util.List; import org.dom4j.Attribute; import org.dom4j.CDATA; import org.dom4j.Comment; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.Entity; import org.dom4j.Namespace; import org.dom4j.ProcessingInstruction; import org.dom4j.Text; import org.dom4j.tree.NamespaceStack; import org.w3c.dom.DOMImplementation; /** *

* DOMWriter takes a DOM4J tree and outputs it as a W3C DOM * object *

* * @author James Strachan * @version $Revision: 1.17 $ */ public class DOMWriter { private static boolean loggedWarning = false; private static final String[] DEFAULT_DOM_DOCUMENT_CLASSES = { "org.apache.xerces.dom.DocumentImpl", // Xerces "gnu.xml.dom.DomDocument", // GNU JAXP "org.apache.crimson.tree.XmlDocument", // Crimson "com.sun.xml.tree.XmlDocument", // Sun's Project X "oracle.xml.parser.v2.XMLDocument", // Oracle V2 "oracle.xml.parser.XMLDocument", // Oracle V1 "org.dom4j.dom.DOMDocument" // Internal DOM implementation }; // the Class used to create new DOM Document instances private Class domDocumentClass; /** stack of Namespace objects */ private NamespaceStack namespaceStack = new NamespaceStack(); public DOMWriter() { } public DOMWriter(Class domDocumentClass) { this.domDocumentClass = domDocumentClass; } public Class getDomDocumentClass() throws DocumentException { Class result = domDocumentClass; if (result == null) { // lets try and find one in the classpath int size = DEFAULT_DOM_DOCUMENT_CLASSES.length; for (int i = 0; i < size; i++) { try { String name = DEFAULT_DOM_DOCUMENT_CLASSES[i]; result = Class.forName(name, true, DOMWriter.class .getClassLoader()); if (result != null) { break; } } catch (Exception e) { // could not load class correctly // lets carry on to the next one } } } return result; } /** * Sets the DOM {@link org.w3c.dom.Document}implementation class used by * the writer when creating DOM documents. * * @param domDocumentClass * is the Class implementing the {@linkorg.w3c.dom.Document} * interface */ public void setDomDocumentClass(Class domDocumentClass) { this.domDocumentClass = domDocumentClass; } /** * Sets the DOM {@link org.w3c.dom.Document}implementation class name used * by the writer when creating DOM documents. * * @param name * is the name of the Class implementing the {@link * org.w3c.dom.Document} interface * * @throws DocumentException * if the class could not be loaded */ public void setDomDocumentClassName(String name) throws DocumentException { try { this.domDocumentClass = Class.forName(name, true, DOMWriter.class .getClassLoader()); } catch (Exception e) { throw new DocumentException("Could not load the DOM Document " + "class: " + name, e); } } public org.w3c.dom.Document write(Document document) throws DocumentException { if (document instanceof org.w3c.dom.Document) { return (org.w3c.dom.Document) document; } resetNamespaceStack(); org.w3c.dom.Document domDocument = createDomDocument(document); appendDOMTree(domDocument, domDocument, document.content()); namespaceStack.clear(); return domDocument; } public org.w3c.dom.Document write(Document document, org.w3c.dom.DOMImplementation domImpl) throws DocumentException { if (document instanceof org.w3c.dom.Document) { return (org.w3c.dom.Document) document; } resetNamespaceStack(); org.w3c.dom.Document domDocument = createDomDocument(document, domImpl); appendDOMTree(domDocument, domDocument, document.content()); namespaceStack.clear(); return domDocument; } protected void appendDOMTree(org.w3c.dom.Document domDocument, org.w3c.dom.Node domCurrent, List content) { int size = content.size(); for (int i = 0; i < size; i++) { Object object = content.get(i); if (object instanceof Element) { appendDOMTree(domDocument, domCurrent, (Element) object); } else if (object instanceof String) { appendDOMTree(domDocument, domCurrent, (String) object); } else if (object instanceof Text) { Text text = (Text) object; appendDOMTree(domDocument, domCurrent, text.getText()); } else if (object instanceof CDATA) { appendDOMTree(domDocument, domCurrent, (CDATA) object); } else if (object instanceof Comment) { appendDOMTree(domDocument, domCurrent, (Comment) object); } else if (object instanceof Entity) { appendDOMTree(domDocument, domCurrent, (Entity) object); } else if (object instanceof ProcessingInstruction) { appendDOMTree(domDocument, domCurrent, (ProcessingInstruction) object); } } } protected void appendDOMTree(org.w3c.dom.Document domDocument, org.w3c.dom.Node domCurrent, Element element) { String elUri = element.getNamespaceURI(); String elName = element.getQualifiedName(); org.w3c.dom.Element domElement = domDocument.createElementNS(elUri, elName); int stackSize = namespaceStack.size(); // add the namespace of the element first Namespace elementNamespace = element.getNamespace(); if (isNamespaceDeclaration(elementNamespace)) { namespaceStack.push(elementNamespace); writeNamespace(domElement, elementNamespace); } // add the additional declared namespaces List declaredNamespaces = element.declaredNamespaces(); for (int i = 0, size = declaredNamespaces.size(); i < size; i++) { Namespace namespace = (Namespace) declaredNamespaces.get(i); if (isNamespaceDeclaration(namespace)) { namespaceStack.push(namespace); writeNamespace(domElement, namespace); } } // add the attributes for (int i = 0, size = element.attributeCount(); i < size; i++) { Attribute attribute = (Attribute) element.attribute(i); String attUri = attribute.getNamespaceURI(); String attName = attribute.getQualifiedName(); String value = attribute.getValue(); domElement.setAttributeNS(attUri, attName, value); } // add content appendDOMTree(domDocument, domElement, element.content()); domCurrent.appendChild(domElement); while (namespaceStack.size() > stackSize) { namespaceStack.pop(); } } protected void appendDOMTree(org.w3c.dom.Document domDocument, org.w3c.dom.Node domCurrent, CDATA cdata) { org.w3c.dom.CDATASection domCDATA = domDocument .createCDATASection(cdata.getText()); domCurrent.appendChild(domCDATA); } protected void appendDOMTree(org.w3c.dom.Document domDocument, org.w3c.dom.Node domCurrent, Comment comment) { org.w3c.dom.Comment domComment = domDocument.createComment(comment .getText()); domCurrent.appendChild(domComment); } protected void appendDOMTree(org.w3c.dom.Document domDocument, org.w3c.dom.Node domCurrent, String text) { org.w3c.dom.Text domText = domDocument.createTextNode(text); domCurrent.appendChild(domText); } protected void appendDOMTree(org.w3c.dom.Document domDocument, org.w3c.dom.Node domCurrent, Entity entity) { org.w3c.dom.EntityReference domEntity = domDocument .createEntityReference(entity.getName()); domCurrent.appendChild(domEntity); } protected void appendDOMTree(org.w3c.dom.Document domDoc, org.w3c.dom.Node domCurrent, ProcessingInstruction pi) { org.w3c.dom.ProcessingInstruction domPI = domDoc .createProcessingInstruction(pi.getTarget(), pi.getText()); domCurrent.appendChild(domPI); } protected void writeNamespace(org.w3c.dom.Element domElement, Namespace namespace) { String attributeName = attributeNameForNamespace(namespace); // domElement.setAttributeNS("", attributeName, namespace.getURI()); domElement.setAttribute(attributeName, namespace.getURI()); } protected String attributeNameForNamespace(Namespace namespace) { String xmlns = "xmlns"; String prefix = namespace.getPrefix(); if (prefix.length() > 0) { return xmlns + ":" + prefix; } return xmlns; } protected org.w3c.dom.Document createDomDocument(Document document) throws DocumentException { org.w3c.dom.Document result = null; // use the given domDocumentClass (if not null) if (domDocumentClass != null) { try { result = (org.w3c.dom.Document) domDocumentClass.newInstance(); } catch (Exception e) { throw new DocumentException( "Could not instantiate an instance " + "of DOM Document with class: " + domDocumentClass.getName(), e); } } else { // lets try JAXP first before using the hardcoded default parsers result = createDomDocumentViaJAXP(); if (result == null) { Class theClass = getDomDocumentClass(); try { result = (org.w3c.dom.Document) theClass.newInstance(); } catch (Exception e) { throw new DocumentException("Could not instantiate an " + "instance of DOM Document " + "with class: " + theClass.getName(), e); } } } return result; } protected org.w3c.dom.Document createDomDocumentViaJAXP() throws DocumentException { try { return JAXPHelper.createDocument(false, true); } catch (Throwable e) { if (!loggedWarning) { loggedWarning = true; if (SAXHelper.isVerboseErrorReporting()) { // log all exceptions as warnings and carry // on as we have a default SAX parser we can use System.out.println("Warning: Caught exception attempting " + "to use JAXP to create a W3C DOM " + "document"); System.out.println("Warning: Exception was: " + e); e.printStackTrace(); } else { System.out.println("Warning: Error occurred using JAXP to " + "create a DOM document."); } } } return null; } protected org.w3c.dom.Document createDomDocument(Document document, DOMImplementation domImpl) throws DocumentException { String namespaceURI = null; String qualifiedName = null; org.w3c.dom.DocumentType docType = null; return domImpl.createDocument(namespaceURI, qualifiedName, docType); } protected boolean isNamespaceDeclaration(Namespace ns) { if ((ns != null) && (ns != Namespace.NO_NAMESPACE) && (ns != Namespace.XML_NAMESPACE)) { String uri = ns.getURI(); if ((uri != null) && (uri.length() > 0)) { if (!namespaceStack.contains(ns)) { return true; } } } return false; } protected void resetNamespaceStack() { namespaceStack.clear(); namespaceStack.push(Namespace.XML_NAMESPACE); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/STAXEventWriter.java0000644000175000017500000005317210242120013021621 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.StringWriter; import java.io.Writer; import java.util.Iterator; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Characters; import javax.xml.stream.events.DTD; import javax.xml.stream.events.EndDocument; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.EntityReference; import javax.xml.stream.events.ProcessingInstruction; import javax.xml.stream.events.StartDocument; import javax.xml.stream.events.StartElement; import javax.xml.stream.util.XMLEventConsumer; import org.dom4j.Attribute; import org.dom4j.Branch; import org.dom4j.CDATA; import org.dom4j.Comment; import org.dom4j.Document; import org.dom4j.DocumentType; import org.dom4j.Element; import org.dom4j.Entity; import org.dom4j.Namespace; import org.dom4j.Node; import org.dom4j.Text; /** * Writes DOM4J {@link Node}s to a StAX event stream. In addition the * createXXX methods are provided to directly create STAX events * from DOM4J nodes. * * @author Christian Niles */ public class STAXEventWriter { /** The event stream to which events are written. */ private XMLEventConsumer consumer; /** The event factory used to construct events. */ private XMLEventFactory factory = XMLEventFactory.newInstance(); private XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); public STAXEventWriter() { } /** * Constructs a STAXEventWriter that writes events to the * provided file. * * @param file * The file to which events will be written. * * @throws XMLStreamException * If an error occurs creating an event writer from the file. * @throws IOException * If an error occurs openin the file for writing. */ public STAXEventWriter(File file) throws XMLStreamException, IOException { consumer = outputFactory.createXMLEventWriter(new FileWriter(file)); } /** * Constructs a STAXEventWriter that writes events to the * provided character stream. * * @param writer * The character stream to which events will be written. * * @throws XMLStreamException * If an error occurs constructing an event writer from the * character stream. */ public STAXEventWriter(Writer writer) throws XMLStreamException { consumer = outputFactory.createXMLEventWriter(writer); } /** * Constructs a STAXEventWriter that writes events to the * provided stream. * * @param stream * The output stream to which events will be written. * * @throws XMLStreamException * If an error occurs constructing an event writer from the * stream. */ public STAXEventWriter(OutputStream stream) throws XMLStreamException { consumer = outputFactory.createXMLEventWriter(stream); } /** * Constructs a STAXEventWriter that writes events to the * provided event stream. * * @param consumer * The event stream to which events will be written. */ public STAXEventWriter(XMLEventConsumer consumer) { this.consumer = consumer; } /** * Returns a reference to the underlying event consumer to which events are * written. * * @return The underlying event consumer to which events are written. */ public XMLEventConsumer getConsumer() { return consumer; } /** * Sets the underlying event consumer to which events are written. * * @param consumer * The event consumer to which events should be written. */ public void setConsumer(XMLEventConsumer consumer) { this.consumer = consumer; } /** * Returns a reference to the event factory used to construct STAX events. * * @return The event factory used to construct STAX events. */ public XMLEventFactory getEventFactory() { return factory; } /** * Sets the event factory used to construct STAX events. * * @param eventFactory * The new event factory. */ public void setEventFactory(XMLEventFactory eventFactory) { this.factory = eventFactory; } /** * Writes a DOM4J {@link Node}to the stream. This method is simply a * gateway to the overloaded methods such as {@link#writeElement(Element)}. * * @param n * The DOM4J {@link Node}to write to the stream. * * @throws XMLStreamException * If an error occurs writing to the stream. */ public void writeNode(Node n) throws XMLStreamException { switch (n.getNodeType()) { case Node.ELEMENT_NODE: writeElement((Element) n); break; case Node.TEXT_NODE: writeText((Text) n); break; case Node.ATTRIBUTE_NODE: writeAttribute((Attribute) n); break; case Node.NAMESPACE_NODE: writeNamespace((Namespace) n); break; case Node.COMMENT_NODE: writeComment((Comment) n); break; case Node.CDATA_SECTION_NODE: writeCDATA((CDATA) n); break; case Node.PROCESSING_INSTRUCTION_NODE: writeProcessingInstruction((org.dom4j.ProcessingInstruction) n); break; case Node.ENTITY_REFERENCE_NODE: writeEntity((Entity) n); break; case Node.DOCUMENT_NODE: writeDocument((Document) n); break; case Node.DOCUMENT_TYPE_NODE: writeDocumentType((DocumentType) n); break; default: throw new XMLStreamException("Unsupported DOM4J Node: " + n); } } /** * Writes each child node within the provided {@link Branch}instance. This * method simply iterates through the {@link Branch}'s nodes and calls * {@link #writeNode(Node)}. * * @param branch * The node whose children will be written to the stream. * * @throws XMLStreamException * If an error occurs writing to the stream. */ public void writeChildNodes(Branch branch) throws XMLStreamException { for (int i = 0, s = branch.nodeCount(); i < s; i++) { Node n = branch.node(i); writeNode(n); } } /** * Writes a DOM4J {@link Element}node and its children to the stream. * * @param elem * The {@link Element}node to write to the stream. * * @throws XMLStreamException * If an error occurs writing to the stream. */ public void writeElement(Element elem) throws XMLStreamException { consumer.add(createStartElement(elem)); writeChildNodes(elem); consumer.add(createEndElement(elem)); } /** * Constructs a STAX {@link StartElement}event from a DOM4J {@link * Element}. * * @param elem * The {@link Element}from which to construct the event. * * @return The newly constructed {@link StartElement}event. */ public StartElement createStartElement(Element elem) { // create name QName tagName = createQName(elem.getQName()); // create attribute & namespace iterators Iterator attrIter = new AttributeIterator(elem.attributeIterator()); Iterator nsIter = new NamespaceIterator(elem.declaredNamespaces() .iterator()); // create start event return factory.createStartElement(tagName, attrIter, nsIter); } /** * Constructs a STAX {@link EndElement}event from a DOM4J {@link Element}. * * @param elem * The {@link Element}from which to construct the event. * * @return The newly constructed {@link EndElement}event. */ public EndElement createEndElement(Element elem) { QName tagName = createQName(elem.getQName()); Iterator nsIter = new NamespaceIterator(elem.declaredNamespaces() .iterator()); return factory.createEndElement(tagName, nsIter); } /** * Writes a DOM4J {@link Attribute}to the stream. * * @param attr * The {@link Attribute}to write to the stream. * * @throws XMLStreamException * If an error occurs writing to the stream. */ public void writeAttribute(Attribute attr) throws XMLStreamException { consumer.add(createAttribute(attr)); } /** * Constructs a STAX {@link javax.xml.stream.events.Attribute}event from a * DOM4J {@link Attribute}. * * @param attr * The {@link Attribute}from which to construct the event. * * @return The newly constructed {@link javax.xml.stream.events.Attribute} * event. */ public javax.xml.stream.events.Attribute createAttribute(Attribute attr) { QName attrName = createQName(attr.getQName()); String value = attr.getValue(); return factory.createAttribute(attrName, value); } /** * Writes a DOM4J {@link Namespace}to the stream. * * @param ns * The {@link Namespace}to write to the stream. * * @throws XMLStreamException * If an error occurs writing to the stream. */ public void writeNamespace(Namespace ns) throws XMLStreamException { consumer.add(createNamespace(ns)); } /** * Constructs a STAX {@link javax.xml.stream.events.Namespace}event from a * DOM4J {@link Namespace}. * * @param ns * The {@link Namespace}from which to construct the event. * * @return The constructed {@link javax.xml.stream.events.Namespace}event. */ public javax.xml.stream.events.Namespace createNamespace(Namespace ns) { String prefix = ns.getPrefix(); String uri = ns.getURI(); return factory.createNamespace(prefix, uri); } /** * Writes a DOM4J {@link Text}to the stream. * * @param text * The {@link Text}to write to the stream. * * @throws XMLStreamException * If an error occurs writing to the stream. */ public void writeText(Text text) throws XMLStreamException { consumer.add(createCharacters(text)); } /** * Constructs a STAX {@link Characters}event from a DOM4J {@link Text}. * * @param text * The {@link Text}from which to construct the event. * * @return The constructed {@link Characters}event. */ public Characters createCharacters(Text text) { return factory.createCharacters(text.getText()); } /** * Writes a DOM4J {@link CDATA}to the event stream. * * @param cdata * The {@link CDATA}to write to the stream. * * @throws XMLStreamException * If an error occurs writing to the stream. */ public void writeCDATA(CDATA cdata) throws XMLStreamException { consumer.add(createCharacters(cdata)); } /** * Constructs a STAX {@link Characters}event from a DOM4J {@link CDATA}. * * @param cdata * The {@link CDATA}from which to construct the event. * * @return The newly constructed {@link Characters}event. */ public Characters createCharacters(CDATA cdata) { return factory.createCData(cdata.getText()); } /** * Writes a DOM4J {@link Comment}to the stream. * * @param comment * The {@link Comment}to write to the stream. * * @throws XMLStreamException * If an error occurs writing to the stream. */ public void writeComment(Comment comment) throws XMLStreamException { consumer.add(createComment(comment)); } /** * Constructs a STAX {@link javax.xml.stream.events.Comment}event from a * DOM4J {@link Comment}. * * @param comment * The {@link Comment}from which to construct the event. * * @return The constructed {@link javax.xml.stream.events.Comment}event. */ public javax.xml.stream.events.Comment createComment(Comment comment) { return factory.createComment(comment.getText()); } /** * Writes a DOM4J {@link ProcessingInstruction}to the stream. * * @param pi * The {@link ProcessingInstruction}to write to the stream. * * @throws XMLStreamException * If an error occurs writing to the stream. */ public void writeProcessingInstruction(org.dom4j.ProcessingInstruction pi) throws XMLStreamException { consumer.add(createProcessingInstruction(pi)); } /** * Constructs a STAX {@link javax.xml.stream.events.ProcessingInstruction} * event from a DOM4J {@link ProcessingInstruction}. * * @param pi * The {@link ProcessingInstruction}from which to construct the * event. * * @return The constructed {@link * javax.xml.stream.events.ProcessingInstruction} event. */ public ProcessingInstruction createProcessingInstruction( org.dom4j.ProcessingInstruction pi) { String target = pi.getTarget(); String data = pi.getText(); return factory.createProcessingInstruction(target, data); } /** * Writes a DOM4J {@link Entity}to the stream. * * @param entity * The {@link Entity}to write to the stream. * * @throws XMLStreamException * If an error occurs writing to the stream. */ public void writeEntity(Entity entity) throws XMLStreamException { consumer.add(createEntityReference(entity)); } /** * Constructs a STAX {@link EntityReference}event from a DOM4J {@link * Entity}. * * @param entity * The {@link Entity}from which to construct the event. * * @return The constructed {@link EntityReference}event. */ private EntityReference createEntityReference(Entity entity) { return factory.createEntityReference(entity.getName(), null); } /** * Writes a DOM4J {@link DocumentType}to the stream. * * @param docType * The {@link DocumentType}to write to the stream. * * @throws XMLStreamException * If an error occurs writing to the stream. */ public void writeDocumentType(DocumentType docType) throws XMLStreamException { consumer.add(createDTD(docType)); } /** * Constructs a STAX {@link DTD}event from a DOM4J {@link DocumentType}. * * @param docType * The {@link DocumentType}from which to construct the event. * * @return The constructed {@link DTD}event. * * @throws RuntimeException * DOCUMENT ME! */ public DTD createDTD(DocumentType docType) { StringWriter decl = new StringWriter(); try { docType.write(decl); } catch (IOException e) { throw new RuntimeException("Error writing DTD", e); } return factory.createDTD(decl.toString()); } /** * Writes a DOM4J {@link Document}node, and all its contents, to the * stream. * * @param doc * The {@link Document}to write to the stream. * * @throws XMLStreamException * If an error occurs writing to the stream. */ public void writeDocument(Document doc) throws XMLStreamException { consumer.add(createStartDocument(doc)); writeChildNodes(doc); consumer.add(createEndDocument(doc)); } /** * Constructs a STAX {@link StartDocument}event from a DOM4J {@link * Document}. * * @param doc * The {@link Document}from which to construct the event. * * @return The constructed {@link StartDocument}event. */ public StartDocument createStartDocument(Document doc) { String encoding = doc.getXMLEncoding(); if (encoding != null) { return factory.createStartDocument(encoding); } else { return factory.createStartDocument(); } } /** * Constructs a STAX {@link EndDocument}event from a DOM4J {@link * Document}. * * @param doc * The {@link Document}from which to construct the event. * * @return The constructed {@link EndDocument}event. */ public EndDocument createEndDocument(Document doc) { return factory.createEndDocument(); } /** * Constructs a STAX {@link QName}from a DOM4J {@link org.dom4j.QName}. * * @param qname * The {@link org.dom4j.QName}from which to construct the STAX * {@link QName}. * * @return The constructed {@link QName}. */ public QName createQName(org.dom4j.QName qname) { return new QName(qname.getNamespaceURI(), qname.getName(), qname .getNamespacePrefix()); } /** * Internal {@link Iterator}implementation used to pass DOM4J {@link * Attribute}s to the stream. */ private class AttributeIterator implements Iterator { /** The underlying DOm4J attribute iterator. */ private Iterator iter; public AttributeIterator(Iterator iter) { this.iter = iter; } public boolean hasNext() { return iter.hasNext(); } public Object next() { Attribute attr = (Attribute) iter.next(); QName attrName = createQName(attr.getQName()); String value = attr.getValue(); return factory.createAttribute(attrName, value); } public void remove() { throw new UnsupportedOperationException(); } } /** * Internal {@link Iterator}implementation used to pass DOM4J {@link * Namespace}s to the stream. */ private class NamespaceIterator implements Iterator { private Iterator iter; public NamespaceIterator(Iterator iter) { this.iter = iter; } public boolean hasNext() { return iter.hasNext(); } public Object next() { Namespace ns = (Namespace) iter.next(); String prefix = ns.getPrefix(); String nsURI = ns.getURI(); return factory.createNamespace(prefix, nsURI); } public void remove() { throw new UnsupportedOperationException(); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/SAXModifyException.java0000644000175000017500000000515510242120005022324 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; /** * Exception internally thrown by the SAX Modification classes. This is a * RuntimeException since the {@link org.dom4j.ElementHandler}methods do not * throw Exceptions. * * @author Wonne Keysers (Realsoftware.be) */ class SAXModifyException extends RuntimeException { /** * DOCUMENT ME! * * @param cause * The causing {@link java.lang.Throwable} */ protected SAXModifyException(Throwable cause) { super(cause); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/SAXModifyContentHandler.java0000644000175000017500000002232110242120011023265 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.io.IOException; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.ElementHandler; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; /** * This extension of the SAXContentHandler writes SAX events immediately to the * provided XMLWriter, unless some {@link org.dom4.ElementHandler}is still * handling the current Element. * * @author Wonne Keysers (Realsoftware.be) * * @see org.dom4j.io.SAXContentHandler */ class SAXModifyContentHandler extends SAXContentHandler { private XMLWriter xmlWriter; public SAXModifyContentHandler() { } public SAXModifyContentHandler(DocumentFactory documentFactory) { super(documentFactory); } public SAXModifyContentHandler(DocumentFactory documentFactory, ElementHandler elementHandler) { super(documentFactory, elementHandler); } public SAXModifyContentHandler(DocumentFactory documentFactory, ElementHandler elementHandler, ElementStack elementStack) { super(documentFactory, elementHandler, elementStack); } public void setXMLWriter(XMLWriter writer) { this.xmlWriter = writer; } public void startCDATA() throws SAXException { super.startCDATA(); if (!activeHandlers() && (xmlWriter != null)) { xmlWriter.startCDATA(); } } public void startDTD(String name, String publicId, String systemId) throws SAXException { super.startDTD(name, publicId, systemId); if (xmlWriter != null) { xmlWriter.startDTD(name, publicId, systemId); } } public void endDTD() throws org.xml.sax.SAXException { super.endDTD(); if (xmlWriter != null) { xmlWriter.endDTD(); } } public void comment(char[] characters, int parm2, int parm3) throws SAXException { super.comment(characters, parm2, parm3); if (!activeHandlers() && (xmlWriter != null)) { xmlWriter.comment(characters, parm2, parm3); } } public void startEntity(String name) throws SAXException { super.startEntity(name); if (xmlWriter != null) { xmlWriter.startEntity(name); } } public void endCDATA() throws org.xml.sax.SAXException { super.endCDATA(); if (!activeHandlers() && (xmlWriter != null)) { xmlWriter.endCDATA(); } } public void endEntity(String name) throws SAXException { super.endEntity(name); if (xmlWriter != null) { xmlWriter.endEntity(name); } } public void unparsedEntityDecl(String name, String publicId, String systemId, String notation) throws SAXException { super.unparsedEntityDecl(name, publicId, systemId, notation); if (!activeHandlers() && (xmlWriter != null)) { xmlWriter.unparsedEntityDecl(name, publicId, systemId, notation); } } public void notationDecl(String name, String publicId, String systemId) throws SAXException { super.notationDecl(name, publicId, systemId); if (xmlWriter != null) { xmlWriter.notationDecl(name, publicId, systemId); } } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { super.startElement(uri, localName, qName, atts); if (!activeHandlers() && (xmlWriter != null)) { xmlWriter.startElement(uri, localName, qName, atts); } } public void startDocument() throws SAXException { super.startDocument(); if (xmlWriter != null) { xmlWriter.startDocument(); } } public void ignorableWhitespace(char[] parm1, int parm2, int parm3) throws SAXException { super.ignorableWhitespace(parm1, parm2, parm3); if (!activeHandlers() && (xmlWriter != null)) { xmlWriter.ignorableWhitespace(parm1, parm2, parm3); } } public void processingInstruction(String target, String data) throws SAXException { super.processingInstruction(target, data); if (!activeHandlers() && (xmlWriter != null)) { xmlWriter.processingInstruction(target, data); } } public void setDocumentLocator(Locator locator) { super.setDocumentLocator(locator); if (xmlWriter != null) { xmlWriter.setDocumentLocator(locator); } } public void skippedEntity(String name) throws SAXException { super.skippedEntity(name); if (!activeHandlers() && (xmlWriter != null)) { xmlWriter.skippedEntity(name); } } public void endDocument() throws SAXException { super.endDocument(); if (xmlWriter != null) { xmlWriter.endDocument(); } } public void startPrefixMapping(String prefix, String uri) throws SAXException { super.startPrefixMapping(prefix, uri); if (xmlWriter != null) { xmlWriter.startPrefixMapping(prefix, uri); } } public void endElement(String uri, String localName, String qName) throws SAXException { ElementHandler currentHandler = getElementStack().getDispatchHandler() .getHandler(getElementStack().getPath()); super.endElement(uri, localName, qName); if (!activeHandlers()) { if (xmlWriter != null) { if (currentHandler == null) { xmlWriter.endElement(uri, localName, qName); } else if (currentHandler instanceof SAXModifyElementHandler) { SAXModifyElementHandler modifyHandler = (SAXModifyElementHandler) currentHandler; Element modifiedElement = modifyHandler .getModifiedElement(); try { xmlWriter.write(modifiedElement); } catch (IOException ex) { throw new SAXModifyException(ex); } } } } } public void endPrefixMapping(String prefix) throws SAXException { super.endPrefixMapping(prefix); if (xmlWriter != null) { xmlWriter.endPrefixMapping(prefix); } } public void characters(char[] parm1, int parm2, int parm3) throws SAXException { super.characters(parm1, parm2, parm3); if (!activeHandlers() && (xmlWriter != null)) { xmlWriter.characters(parm1, parm2, parm3); } } protected XMLWriter getXMLWriter() { return this.xmlWriter; } private boolean activeHandlers() { DispatchHandler handler = getElementStack().getDispatchHandler(); return handler.getActiveHandlerCount() > 0; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/DOMReader.java0000644000175000017500000002512210242120025020402 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.util.ArrayList; import java.util.List; import org.dom4j.Branch; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.QName; import org.dom4j.tree.NamespaceStack; /** *

* DOMReader navigates a W3C DOM tree and creates a DOM4J tree * from it. *

* * @author James Strachan * @version $Revision: 1.17 $ */ public class DOMReader { /** DocumentFactory used to create new document objects */ private DocumentFactory factory; /** stack of Namespace and QName objects */ private NamespaceStack namespaceStack; public DOMReader() { this.factory = DocumentFactory.getInstance(); this.namespaceStack = new NamespaceStack(factory); } public DOMReader(DocumentFactory factory) { this.factory = factory; this.namespaceStack = new NamespaceStack(factory); } /** * DOCUMENT ME! * * @return the DocumentFactory used to create document * objects */ public DocumentFactory getDocumentFactory() { return factory; } /** *

* This sets the DocumentFactory used to create new * documents. This method allows the building of custom DOM4J tree objects * to be implemented easily using a custom derivation of * {@link DocumentFactory} *

* * @param docFactory * DocumentFactory used to create DOM4J objects */ public void setDocumentFactory(DocumentFactory docFactory) { this.factory = docFactory; this.namespaceStack.setDocumentFactory(factory); } public Document read(org.w3c.dom.Document domDocument) { if (domDocument instanceof Document) { return (Document) domDocument; } Document document = createDocument(); clearNamespaceStack(); org.w3c.dom.NodeList nodeList = domDocument.getChildNodes(); for (int i = 0, size = nodeList.getLength(); i < size; i++) { readTree(nodeList.item(i), document); } return document; } // Implementation methods protected void readTree(org.w3c.dom.Node node, Branch current) { Element element = null; Document document = null; if (current instanceof Element) { element = (Element) current; } else { document = (Document) current; } switch (node.getNodeType()) { case org.w3c.dom.Node.ELEMENT_NODE: readElement(node, current); break; case org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE: if (current instanceof Element) { Element currentEl = (Element) current; currentEl.addProcessingInstruction(node.getNodeName(), node .getNodeValue()); } else { Document currentDoc = (Document) current; currentDoc.addProcessingInstruction(node.getNodeName(), node.getNodeValue()); } break; case org.w3c.dom.Node.COMMENT_NODE: if (current instanceof Element) { ((Element) current).addComment(node.getNodeValue()); } else { ((Document) current).addComment(node.getNodeValue()); } break; case org.w3c.dom.Node.DOCUMENT_TYPE_NODE: org.w3c.dom.DocumentType domDocType = (org.w3c.dom.DocumentType) node; document.addDocType(domDocType.getName(), domDocType .getPublicId(), domDocType.getSystemId()); break; case org.w3c.dom.Node.TEXT_NODE: element.addText(node.getNodeValue()); break; case org.w3c.dom.Node.CDATA_SECTION_NODE: element.addCDATA(node.getNodeValue()); break; case org.w3c.dom.Node.ENTITY_REFERENCE_NODE: // is there a better way to get the value of an entity? org.w3c.dom.Node firstChild = node.getFirstChild(); if (firstChild != null) { element.addEntity(node.getNodeName(), firstChild .getNodeValue()); } else { element.addEntity(node.getNodeName(), ""); } break; case org.w3c.dom.Node.ENTITY_NODE: element.addEntity(node.getNodeName(), node.getNodeValue()); break; default: System.out.println("WARNING: Unknown DOM node type: " + node.getNodeType()); } } protected void readElement(org.w3c.dom.Node node, Branch current) { int previouslyDeclaredNamespaces = namespaceStack.size(); String namespaceUri = node.getNamespaceURI(); String elementPrefix = node.getPrefix(); if (elementPrefix == null) { elementPrefix = ""; } org.w3c.dom.NamedNodeMap attributeList = node.getAttributes(); if ((attributeList != null) && (namespaceUri == null)) { // test if we have an "xmlns" attribute org.w3c.dom.Node attribute = attributeList.getNamedItem("xmlns"); if (attribute != null) { namespaceUri = attribute.getNodeValue(); elementPrefix = ""; } } QName qName = namespaceStack.getQName(namespaceUri, node.getLocalName(), node.getNodeName()); Element element = current.addElement(qName); if (attributeList != null) { int size = attributeList.getLength(); List attributes = new ArrayList(size); for (int i = 0; i < size; i++) { org.w3c.dom.Node attribute = attributeList.item(i); // Define all namespaces first then process attributes later String name = attribute.getNodeName(); if (name.startsWith("xmlns")) { String prefix = getPrefix(name); String uri = attribute.getNodeValue(); Namespace namespace = namespaceStack.addNamespace(prefix, uri); element.add(namespace); } else { attributes.add(attribute); } } // now add the attributes, the namespaces should be available size = attributes.size(); for (int i = 0; i < size; i++) { org.w3c.dom.Node attribute = (org.w3c.dom.Node) attributes .get(i); QName attributeQName = namespaceStack.getQName(attribute .getNamespaceURI(), attribute.getLocalName(), attribute .getNodeName()); element.addAttribute(attributeQName, attribute.getNodeValue()); } } // Recurse on child nodes org.w3c.dom.NodeList children = node.getChildNodes(); for (int i = 0, size = children.getLength(); i < size; i++) { org.w3c.dom.Node child = children.item(i); readTree(child, element); } // pop namespaces from the stack while (namespaceStack.size() > previouslyDeclaredNamespaces) { namespaceStack.pop(); } } protected Namespace getNamespace(String prefix, String uri) { return getDocumentFactory().createNamespace(prefix, uri); } protected Document createDocument() { return getDocumentFactory().createDocument(); } protected void clearNamespaceStack() { namespaceStack.clear(); if (!namespaceStack.contains(Namespace.XML_NAMESPACE)) { namespaceStack.push(Namespace.XML_NAMESPACE); } } private String getPrefix(String xmlnsDecl) { int index = xmlnsDecl.indexOf(':', 5); if (index != -1) { return xmlnsDecl.substring(index + 1); } else { return ""; } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/DocumentResult.java0000644000175000017500000000726510242120002021620 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import javax.xml.transform.sax.SAXResult; import org.dom4j.Document; import org.xml.sax.ContentHandler; import org.xml.sax.ext.LexicalHandler; /** *

* DocumentResult implements a JAXP {@link SAXResult}for a * {@link Document}. *

* * @author James Strachan * @version $Revision: 1.8 $ */ public class DocumentResult extends SAXResult { private SAXContentHandler contentHandler; public DocumentResult() { this(new SAXContentHandler()); } public DocumentResult(SAXContentHandler contentHandler) { this.contentHandler = contentHandler; super.setHandler(this.contentHandler); super.setLexicalHandler(this.contentHandler); } /** * DOCUMENT ME! * * @return the Document created by the transformation */ public Document getDocument() { return contentHandler.getDocument(); } // Overloaded methods // ------------------------------------------------------------------------- public void setHandler(ContentHandler handler) { if (handler instanceof SAXContentHandler) { this.contentHandler = (SAXContentHandler) handler; super.setHandler(this.contentHandler); } } public void setLexicalHandler(LexicalHandler handler) { if (handler instanceof SAXContentHandler) { this.contentHandler = (SAXContentHandler) handler; super.setLexicalHandler(this.contentHandler); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/ElementModifier.java0000644000175000017500000000646610242120017021723 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import org.dom4j.Element; /** * ElementModifier defines a modifier of {@link org.dom4j.Element}objects.
* It can be used in the event based {@link org.dom4j.io.SAXModifier}, in order * to modify elements on the fly, rather than waiting until the complete * document is parsed. * * @author Wonne Keysers (Realsoftware.be) */ public interface ElementModifier { /** * Called by an event based processor when an elements closing tag is * encountered. This method must return the modified version of the provided * {@link org.dom4j.Element}or null if it has to be removed from the * document.
* The incoming {@link org.dom4j.Element}is disconnected from the DOM4J * tree. This means that navigation to the elements parent {@link * org.dom4j.Element} and {@link org.dom4j.Document}are not available. Only * the element itself can be modified! * * @param element * {@link org.dom4j.Element}to be parsed * * @return the modified {@link org.dom4j.Element} * * @throws Exception * of any kind */ Element modifyElement(Element element) throws Exception; } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/SAXModifier.java0000644000175000017500000003667710242120014020771 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.io.File; import java.io.InputStream; import java.io.Reader; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * The SAXModifier reads, modifies and writes XML documents using SAX. * *

* Registered {@link ElementModifier}objects can provide modifications to (part * of) the xml tree, while the document is still being processed. This makes it * possible to change large xml documents without having them in memory. *

* *

* The modified document is written when the {@link XMLWriter}is specified. *

* * @author Wonne Keysers (Realsoftware.be) * * @see org.dom4j.io.SAXReader * @see org.dom4j.io.XMLWriter */ public class SAXModifier { private XMLWriter xmlWriter; private XMLReader xmlReader; private boolean pruneElements; private SAXModifyReader modifyReader; private HashMap modifiers = new HashMap(); /** * Creates a new modifier.
* The XMLReader to parse the source will be created via the * org.xml.sax.driver system property or JAXP if the system property is not * set. */ public SAXModifier() { } /** * Creates a new modifier.
* The XMLReader to parse the source will be created via the * org.xml.sax.driver system property or JAXP if the system property is not * set. * * @param pruneElements * Set to true when the modified document must NOT be kept in * memory. */ public SAXModifier(boolean pruneElements) { this.pruneElements = pruneElements; } /** * Creates a new modifier that will the specified {@link * org.xml.sax.XMLReader} to parse the source. * * @param xmlReader * The XMLReader to use */ public SAXModifier(XMLReader xmlReader) { this.xmlReader = xmlReader; } /** * Creates a new modifier that will the specified {@link * org.xml.sax.XMLReader} to parse the source. * * @param xmlReader * The XMLReader to use * @param pruneElements * Set to true when the modified document must NOT be kept in * memory. */ public SAXModifier(XMLReader xmlReader, boolean pruneElements) { this.xmlReader = xmlReader; } /** * Reads a Document from the given {@link java.io.File}and writes it to the * specified {@link XMLWriter}using SAX. Registered {@linkElementModifier} * objects are invoked on the fly. * * @param source * is the File to read from. * * @return the newly created Document instance * * @throws DocumentException * DocumentException org.dom4j.DocumentException} if an error * occurs during parsing. */ public Document modify(File source) throws DocumentException { try { return installModifyReader().read(source); } catch (SAXModifyException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Reads a Document from the given {@link org.xml.sax.InputSource}and * writes it to the specified {@link XMLWriter}using SAX. Registered * {@link ElementModifier}objects are invoked on the fly. * * @param source * is the org.xml.sax.InputSource to read from. * * @return the newly created Document instance * * @throws DocumentException * DocumentException org.dom4j.DocumentException} if an error * occurs during parsing. */ public Document modify(InputSource source) throws DocumentException { try { return installModifyReader().read(source); } catch (SAXModifyException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Reads a Document from the given {@link java.io.InputStream}and writes it * to the specified {@link XMLWriter}using SAX. Registered {@link * ElementModifier} objects are invoked on the fly. * * @param source * is the java.io.InputStream to read from. * * @return the newly created Document instance * * @throws DocumentException * DocumentException org.dom4j.DocumentException} if an error * occurs during parsing. */ public Document modify(InputStream source) throws DocumentException { try { return installModifyReader().read(source); } catch (SAXModifyException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Reads a Document from the given {@link java.io.InputStream}and writes it * to the specified {@link XMLWriter}using SAX. Registered {@link * ElementModifier} objects are invoked on the fly. * * @param source * is the java.io.InputStream to read from. * @param systemId * DOCUMENT ME! * * @return the newly created Document instance * * @throws DocumentException * DocumentException org.dom4j.DocumentException} if an error * occurs during parsing. */ public Document modify(InputStream source, String systemId) throws DocumentException { try { return installModifyReader().read(source); } catch (SAXModifyException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Reads a Document from the given {@link java.io.Reader}and writes it to * the specified {@link XMLWriter}using SAX. Registered {@link * ElementModifier} objects are invoked on the fly. * * @param source * is the java.io.Reader to read from. * * @return the newly created Document instance * * @throws DocumentException * DocumentException org.dom4j.DocumentException} if an error * occurs during parsing. */ public Document modify(Reader source) throws DocumentException { try { return installModifyReader().read(source); } catch (SAXModifyException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Reads a Document from the given {@link java.io.Reader}and writes it to * the specified {@link XMLWriter}using SAX. Registered {@link * ElementModifier} objects are invoked on the fly. * * @param source * is the java.io.Reader to read from. * @param systemId * DOCUMENT ME! * * @return the newly created Document instance * * @throws DocumentException * DocumentException org.dom4j.DocumentException} if an error * occurs during parsing. */ public Document modify(Reader source, String systemId) throws DocumentException { try { return installModifyReader().read(source); } catch (SAXModifyException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Reads a Document from the given {@link java.net.URL}and writes it to the * specified {@link XMLWriter}using SAX. Registered {@linkElementModifier} * objects are invoked on the fly. * * @param source * is the java.net.URL to read from. * * @return the newly created Document instance * * @throws DocumentException * DocumentException org.dom4j.DocumentException} if an error * occurs during parsing. */ public Document modify(URL source) throws DocumentException { try { return installModifyReader().read(source); } catch (SAXModifyException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Reads a Document from the given URL or filename and writes it to the * specified {@link XMLWriter}using SAX. Registered {@linkElementModifier} * objects are invoked on the fly. * * @param source * is the URL or filename to read from. * * @return the newly created Document instance * * @throws DocumentException * DocumentException org.dom4j.DocumentException} if an error * occurs during parsing. */ public Document modify(String source) throws DocumentException { try { return installModifyReader().read(source); } catch (SAXModifyException ex) { Throwable cause = ex.getCause(); throw new DocumentException(cause.getMessage(), cause); } } /** * Adds the {@link ElementModifier}to be called when the specified element * path is encounted while parsing the source. * * @param path * The element path to be handled * @param modifier * The {@link ElementModifier}to be called by the event based * processor. */ public void addModifier(String path, ElementModifier modifier) { this.modifiers.put(path, modifier); } /** * Removes all registered {@link ElementModifier}instances from the event * based processor. */ public void resetModifiers() { this.modifiers.clear(); getSAXModifyReader().resetHandlers(); } /** * Removes the {@link ElementModifier}from the event based processor, for * the specified element path. * * @param path * The path to remove the {@link ElementModifier}for. */ public void removeModifier(String path) { this.modifiers.remove(path); getSAXModifyReader().removeHandler(path); } /** * Get the {@link org.dom4j.DocumentFactory}used to create the DOM4J * document structure * * @return DocumentFactory that will be used */ public DocumentFactory getDocumentFactory() { return getSAXModifyReader().getDocumentFactory(); } /** * Sets the {@link org.dom4j.DocumentFactory}used to create the DOM4J * document tree. * * @param factory * DocumentFactory to be used */ public void setDocumentFactory(DocumentFactory factory) { getSAXModifyReader().setDocumentFactory(factory); } /** * Returns the current {@link XMLWriter}. * * @return XMLWriter */ public XMLWriter getXMLWriter() { return this.xmlWriter; } /** * Sets the {@link XMLWriter}used to write the modified document. * * @param writer * The writer to use. */ public void setXMLWriter(XMLWriter writer) { this.xmlWriter = writer; } /** * Returns true when xml elements are not kept in memory while parsing. The * {@link org.dom4j.Document}returned by the modify methods will be null. * * @return Returns the pruneElements. */ public boolean isPruneElements() { return pruneElements; } private SAXReader installModifyReader() throws DocumentException { try { SAXModifyReader reader = getSAXModifyReader(); if (isPruneElements()) { modifyReader.setDispatchHandler(new PruningDispatchHandler()); } reader.resetHandlers(); Iterator modifierIt = this.modifiers.entrySet().iterator(); while (modifierIt.hasNext()) { Map.Entry entry = (Map.Entry) modifierIt.next(); SAXModifyElementHandler handler = new SAXModifyElementHandler( (ElementModifier) entry.getValue()); reader.addHandler((String) entry.getKey(), handler); } reader.setXMLWriter(getXMLWriter()); reader.setXMLReader(getXMLReader()); return reader; } catch (SAXException ex) { throw new DocumentException(ex.getMessage(), ex); } } private XMLReader getXMLReader() throws SAXException { if (this.xmlReader == null) { xmlReader = SAXHelper.createXMLReader(false); } return this.xmlReader; } private SAXModifyReader getSAXModifyReader() { if (modifyReader == null) { modifyReader = new SAXModifyReader(); } return modifyReader; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/STAXEventReader.java0000644000175000017500000006064210242120006021551 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.io.InputStream; import java.io.Reader; import java.util.Iterator; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Characters; import javax.xml.stream.events.Comment; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.EntityReference; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.ProcessingInstruction; import javax.xml.stream.events.StartDocument; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import org.dom4j.CharacterData; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.Entity; import org.dom4j.Node; /** * Reads a DOM4J {@link Document}, as well as other {@link Node}s, from a StAX * {@link XMLEventReader}. * * @author Christian Niles */ public class STAXEventReader { /** Reference to the DocumentFactory used to build DOM4J nodes. */ private DocumentFactory factory; /** A StAX input factory, used to construct streams from IO streams. */ private XMLInputFactory inputFactory = XMLInputFactory.newInstance(); /** * Constructs a default STAXEventReader instance with a * default {@link DocumentFactory}. */ public STAXEventReader() { this.factory = DocumentFactory.getInstance(); } /** * Constructs a STAXEventReader instance that uses the * specified {@link DocumentFactory}to construct DOM4J {@link Node}s. * * @param factory * The DocumentFactory to use when constructing DOM4J nodes, or * null if a default should be used. */ public STAXEventReader(DocumentFactory factory) { if (factory != null) { this.factory = factory; } else { this.factory = DocumentFactory.getInstance(); } } /** * Sets the DocumentFactory to be used when constructing DOM4J nodes. * * @param documentFactory * The DocumentFactory to use when constructing DOM4J nodes, or * null if a default should be used. */ public void setDocumentFactory(DocumentFactory documentFactory) { if (documentFactory != null) { this.factory = documentFactory; } else { this.factory = DocumentFactory.getInstance(); } } /** * Constructs a StAX event stream from the provided I/O stream and reads a * DOM4J document from it. * * @param is * The I/O stream from which the Document will be read. * * @return The Document that was read from the stream. * * @throws XMLStreamException * If an error occurs reading content from the stream. */ public Document readDocument(InputStream is) throws XMLStreamException { return readDocument(is, null); } /** * Constructs a StAX event stream from the provided I/O character stream and * reads a DOM4J document from it. * * @param reader * The character stream from which the Document will be read. * * @return The Document that was read from the stream. * * @throws XMLStreamException * If an error occurs reading content from the stream. */ public Document readDocument(Reader reader) throws XMLStreamException { return readDocument(reader, null); } /** * Constructs a StAX event stream from the provided I/O stream and reads a * DOM4J document from it. * * @param is * The I/O stream from which the Document will be read. * @param systemId * A system id used to resolve entities. * * @return The Document that was read from the stream. * * @throws XMLStreamException * If an error occurs reading content from the stream. */ public Document readDocument(InputStream is, String systemId) throws XMLStreamException { XMLEventReader eventReader = inputFactory.createXMLEventReader( systemId, is); try { return readDocument(eventReader); } finally { eventReader.close(); } } /** * Constructs a StAX event stream from the provided I/O character stream and * reads a DOM4J document from it. * * @param reader * The character stream from which the Document will be read. * @param systemId * A system id used to resolve entities. * * @return The Document that was read from the stream. * * @throws XMLStreamException * If an error occurs reading content from the stream. */ public Document readDocument(Reader reader, String systemId) throws XMLStreamException { XMLEventReader eventReader = inputFactory.createXMLEventReader( systemId, reader); try { return readDocument(eventReader); } finally { eventReader.close(); } } /** * Reads a {@link Node}from the event stream. If the next event is a * {@link StartElement}, all events until the closing {@link EndElement} * will be read, and the resulting nodes will be added to the returned * {@link Element}. * *

* Pre-Conditions : The stream must be positioned before an * event other than an EndElement,EndDocument, * or any DTD-related events, which are not currently supported. *

* * @param reader * The reader from which events will be read. * * @return A DOM4J {@link Node}constructed from the read events. * * @throws XMLStreamException * If an error occurs reading from the stream, or the stream was * positioned before an unsupported event. */ public Node readNode(XMLEventReader reader) throws XMLStreamException { XMLEvent event = reader.peek(); if (event.isStartElement()) { return readElement(reader); } else if (event.isCharacters()) { return readCharacters(reader); } else if (event.isStartDocument()) { return readDocument(reader); } else if (event.isProcessingInstruction()) { return readProcessingInstruction(reader); } else if (event.isEntityReference()) { return readEntityReference(reader); } else if (event.isAttribute()) { return readAttribute(reader); } else if (event.isNamespace()) { return readNamespace(reader); } else { throw new XMLStreamException("Unsupported event: " + event); } } /** * Reads a DOM4J {@link Document}from the provided stream. The stream * should be positioned at the start of a document, or before a {@link * StartElement} event. * * @param reader * The event stream from which to read the {@link Document}. * * @return The {@link Document}that was read from the stream. * * @throws XMLStreamException * If an error occurs reading events from the stream. */ public Document readDocument(XMLEventReader reader) throws XMLStreamException { Document doc = null; while (reader.hasNext()) { XMLEvent nextEvent = reader.peek(); int type = nextEvent.getEventType(); switch (type) { case XMLStreamConstants.START_DOCUMENT: StartDocument event = (StartDocument) reader.nextEvent(); if (doc == null) { // create document if (event.encodingSet()) { String encodingScheme = event .getCharacterEncodingScheme(); doc = factory.createDocument(encodingScheme); } else { doc = factory.createDocument(); } } else { // duplicate or misplaced xml declaration String msg = "Unexpected StartDocument event"; throw new XMLStreamException(msg, event.getLocation()); } break; case XMLStreamConstants.END_DOCUMENT: case XMLStreamConstants.SPACE: case XMLStreamConstants.CHARACTERS: // skip end document and space outside the root element reader.nextEvent(); break; default: if (doc == null) { // create document doc = factory.createDocument(); } Node n = readNode(reader); doc.add(n); } } return doc; } /** * Reads a DOM4J Element from the provided event stream. The stream must be * positioned before an {@link StartElement}event. In addition to the * initial start event, all events up to and including the closing {@link * EndElement} will be read, and included with the returned element. * * @param eventReader * The event stream from which to read the Element. * * @return The Element that was read from the stream. * * @throws XMLStreamException * If an error occured reading events from the stream, or the * stream was not positioned before a {@linkStartElement}event. */ public Element readElement(XMLEventReader eventReader) throws XMLStreamException { XMLEvent event = eventReader.peek(); if (event.isStartElement()) { // advance the reader and get the StartElement event StartElement startTag = eventReader.nextEvent().asStartElement(); Element elem = createElement(startTag); // read element content while (true) { if (!eventReader.hasNext()) { String msg = "Unexpected end of stream while reading" + " element content"; throw new XMLStreamException(msg); } XMLEvent nextEvent = eventReader.peek(); if (nextEvent.isEndElement()) { EndElement endElem = eventReader.nextEvent().asEndElement(); if (!endElem.getName().equals(startTag.getName())) { throw new XMLStreamException("Expected " + startTag.getName() + " end-tag, but found" + endElem.getName()); } break; } Node child = readNode(eventReader); elem.add(child); } return elem; } else { throw new XMLStreamException("Expected Element event, found: " + event); } } /** * Constructs a DOM4J Attribute from the provided event stream. The stream * must be positioned before an {@link Attribute}event. * * @param reader * The event stream from which to read the Attribute. * * @return The Attribute that was read from the stream. * * @throws XMLStreamException * If an error occured reading events from the stream, or the * stream was not positioned before an {@linkAttribute}event. */ public org.dom4j.Attribute readAttribute(XMLEventReader reader) throws XMLStreamException { XMLEvent event = reader.peek(); if (event.isAttribute()) { Attribute attr = (Attribute) reader.nextEvent(); return createAttribute(null, attr); } else { throw new XMLStreamException("Expected Attribute event, found: " + event); } } /** * Constructs a DOM4J Namespace from the provided event stream. The stream * must be positioned before a {@link Namespace}event. * * @param reader * The event stream from which to read the Namespace. * * @return The Namespace that was read from the stream. * * @throws XMLStreamException * If an error occured reading events from the stream, or the * stream was not positioned before a {@linkNamespace}event. */ public org.dom4j.Namespace readNamespace(XMLEventReader reader) throws XMLStreamException { XMLEvent event = reader.peek(); if (event.isNamespace()) { Namespace ns = (Namespace) reader.nextEvent(); return createNamespace(ns); } else { throw new XMLStreamException("Expected Namespace event, found: " + event); } } /** * Constructs a DOM4J Text or CDATA section from the provided event stream. * The stream must be positioned before a {@link Characters}event. * * @param reader * The event stream from which to read the Text or CDATA. * * @return The Text or CDATA that was read from the stream. * * @throws XMLStreamException * If an error occured reading events from the stream, or the * stream was not positioned before a {@linkCharacters}event. */ public CharacterData readCharacters(XMLEventReader reader) throws XMLStreamException { XMLEvent event = reader.peek(); if (event.isCharacters()) { Characters characters = reader.nextEvent().asCharacters(); return createCharacterData(characters); } else { throw new XMLStreamException("Expected Characters event, found: " + event); } } /** * Constructs a DOM4J Comment from the provided event stream. The stream * must be positioned before a {@link Comment}event. * * @param reader * The event stream from which to read the Comment. * * @return The Comment that was read from the stream. * * @throws XMLStreamException * If an error occured reading events from the stream, or the * stream was not positioned before a {@linkComment}event. */ public org.dom4j.Comment readComment(XMLEventReader reader) throws XMLStreamException { XMLEvent event = reader.peek(); if (event instanceof Comment) { return createComment((Comment) reader.nextEvent()); } else { throw new XMLStreamException("Expected Comment event, found: " + event); } } /** * Constructs a DOM4J Entity from the provided event stream. The stream must * be positioned before an {@link EntityReference}event. * * @param reader * The event stream from which to read the {@link * EntityReference}. * * @return The {@link org.dom4j.Entity}that was read from the stream. * * @throws XMLStreamException * If an error occured reading events from the stream, or the * stream was not positioned before an {@linkEntityReference} * event. */ public Entity readEntityReference(XMLEventReader reader) throws XMLStreamException { XMLEvent event = reader.peek(); if (event.isEntityReference()) { EntityReference entityRef = (EntityReference) reader.nextEvent(); return createEntity(entityRef); } else { throw new XMLStreamException("Expected EntityRef event, found: " + event); } } /** * Constructs a DOM4J ProcessingInstruction from the provided event stream. * The stream must be positioned before a {@link ProcessingInstruction} * event. * * @param reader * The event stream from which to read the ProcessingInstruction. * * @return The ProcessingInstruction that was read from the stream. * * @throws XMLStreamException * If an error occured reading events from the stream, or the * stream was not positioned before a {@link * ProcessingInstruction} event. */ public org.dom4j.ProcessingInstruction readProcessingInstruction( XMLEventReader reader) throws XMLStreamException { XMLEvent event = reader.peek(); if (event.isProcessingInstruction()) { ProcessingInstruction pi = (ProcessingInstruction) reader .nextEvent(); return createProcessingInstruction(pi); } else { throw new XMLStreamException("Expected PI event, found: " + event); } } /** * Constructs a new DOM4J Element from the provided StartElement event. All * attributes and namespaces will be added to the returned element. * * @param startEvent * The StartElement event from which to construct the new DOM4J * Element. * * @return The Element constructed from the provided StartElement event. */ public Element createElement(StartElement startEvent) { QName qname = startEvent.getName(); org.dom4j.QName elemName = createQName(qname); Element elem = factory.createElement(elemName); // create attributes for (Iterator i = startEvent.getAttributes(); i.hasNext();) { Attribute attr = (Attribute) i.next(); elem.addAttribute(createQName(attr.getName()), attr.getValue()); } // create namespaces for (Iterator i = startEvent.getNamespaces(); i.hasNext();) { Namespace ns = (Namespace) i.next(); elem.addNamespace(ns.getPrefix(), ns.getNamespaceURI()); } return elem; } /** * Constructs a new DOM4J Attribute from the provided StAX Attribute event. * * @param elem * DOCUMENT ME! * @param attr * The Attribute event from which to construct the new DOM4J * Attribute. * * @return The Attribute constructed from the provided Attribute event. */ public org.dom4j.Attribute createAttribute(Element elem, Attribute attr) { return factory.createAttribute(elem, createQName(attr.getName()), attr .getValue()); } /** * Constructs a new DOM4J Namespace from the provided StAX Namespace event. * * @param ns * The Namespace event from which to construct the new DOM4J * Namespace. * * @return The Namespace constructed from the provided Namespace event. */ public org.dom4j.Namespace createNamespace(Namespace ns) { return factory.createNamespace(ns.getPrefix(), ns.getNamespaceURI()); } /** * Constructs a new DOM4J Text or CDATA object from the provided Characters * event. * * @param characters * The Characters event from which to construct the new DOM4J * Text or CDATA object. * * @return The Text or CDATA object constructed from the provided Characters * event. */ public CharacterData createCharacterData(Characters characters) { String data = characters.getData(); if (characters.isCData()) { return factory.createCDATA(data); } else { return factory.createText(data); } } /** * Constructs a new DOM4J Comment from the provided StAX Comment event. * * @param comment * The Comment event from which to construct the new DOM4J * Comment. * * @return The Comment constructed from the provided Comment event. */ public org.dom4j.Comment createComment(Comment comment) { return factory.createComment(comment.getText()); } /** * Constructs a new DOM4J Entity from the provided StAX EntityReference * event. * * @param entityRef * The EntityReference event from which to construct the new * DOM4J Entity. * * @return The Entity constructed from the provided EntityReference event. */ public org.dom4j.Entity createEntity(EntityReference entityRef) { return factory.createEntity(entityRef.getName(), entityRef .getDeclaration().getReplacementText()); } /** * Constructs a new DOM4J ProcessingInstruction from the provided StAX * ProcessingInstruction event. * * @param pi * The ProcessingInstruction event from which to construct the * new DOM4J ProcessingInstruction. * * @return The ProcessingInstruction constructed from the provided * ProcessingInstruction event. */ public org.dom4j.ProcessingInstruction createProcessingInstruction( ProcessingInstruction pi) { return factory .createProcessingInstruction(pi.getTarget(), pi.getData()); } /** * Constructs a new DOM4J QName from the provided JAXP QName. * * @param qname * The JAXP QName from which to create a DOM4J QName. * * @return The newly constructed DOM4J QName. */ public org.dom4j.QName createQName(QName qname) { return factory.createQName(qname.getLocalPart(), qname.getPrefix(), qname.getNamespaceURI()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/SAXModifyReader.java0000644000175000017500000001042510242120020021561 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import org.dom4j.DocumentFactory; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * The SAXModifier parses, updates and writes an XML document.
* The input that is parsed is directly written to the specified output, unless * the current xml element has an associated ElementHandler.
* The {@link org.dom4j.ElementHandler}objects make it possible to update the * document on the fly, without having read tje complete document. * * @author Wonne Keysers (Realsoftware.be) * * @see org.dom4j.io.SAXReader * @see org.dom4j.io.XMLWriters */ class SAXModifyReader extends SAXReader { private XMLWriter xmlWriter; private boolean pruneElements; public SAXModifyReader() { } public SAXModifyReader(boolean validating) { super(validating); } public SAXModifyReader(DocumentFactory factory) { super(factory); } public SAXModifyReader(DocumentFactory factory, boolean validating) { super(factory, validating); } public SAXModifyReader(XMLReader xmlReader) { super(xmlReader); } public SAXModifyReader(XMLReader xmlReader, boolean validating) { super(xmlReader, validating); } public SAXModifyReader(String xmlReaderClassName) throws SAXException { super(xmlReaderClassName); } public SAXModifyReader(String xmlReaderClassName, boolean validating) throws SAXException { super(xmlReaderClassName, validating); } public void setXMLWriter(XMLWriter writer) { this.xmlWriter = writer; } public boolean isPruneElements() { return pruneElements; } public void setPruneElements(boolean pruneElements) { this.pruneElements = pruneElements; } protected SAXContentHandler createContentHandler(XMLReader reader) { SAXModifyContentHandler handler = new SAXModifyContentHandler( getDocumentFactory(), getDispatchHandler()); handler.setXMLWriter(xmlWriter); return handler; } protected XMLWriter getXMLWriter() { return this.xmlWriter; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/SAXModifyElementHandler.java0000644000175000017500000001307210242120015023253 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.ElementHandler; import org.dom4j.ElementPath; /** * This {@link org.dom4j.ElementHandler}is used to trigger {@link * ElementModifier} objects in order to modify (parts of) the Document on the * fly. * *

* When an element is completely parsed, a copy is handed to the associated (if * any) {@link ElementModifier}that on his turn returns the modified element * that has to come in the tree. *

* * @author Wonne Keysers (Realsoftware.be) */ class SAXModifyElementHandler implements ElementHandler { private ElementModifier elemModifier; private Element modifiedElement; public SAXModifyElementHandler(ElementModifier elemModifier) { this.elemModifier = elemModifier; } public void onStart(ElementPath elementPath) { this.modifiedElement = elementPath.getCurrent(); } public void onEnd(ElementPath elementPath) { try { Element origElement = elementPath.getCurrent(); Element currentParent = origElement.getParent(); if (currentParent != null) { // Clone sets parent + document to null Element clonedElem = (Element) origElement.clone(); // Ask for modified element modifiedElement = elemModifier.modifyElement(clonedElem); if (modifiedElement != null) { // Restore parent + document modifiedElement.setParent(origElement.getParent()); modifiedElement.setDocument(origElement.getDocument()); // Replace old with new element in parent int contentIndex = currentParent.indexOf(origElement); currentParent.content().set(contentIndex, modifiedElement); } // Remove the old element origElement.detach(); } else { if (origElement.isRootElement()) { // Clone sets parent + document to null Element clonedElem = (Element) origElement.clone(); // Ask for modified element modifiedElement = elemModifier.modifyElement(clonedElem); if (modifiedElement != null) { // Restore parent + document modifiedElement.setDocument(origElement.getDocument()); // Replace old with new element in parent Document doc = origElement.getDocument(); doc.setRootElement(modifiedElement); } // Remove the old element origElement.detach(); } } // Put the new element on the ElementStack, it might get pruned by // the PruningDispatchHandler if (elementPath instanceof ElementStack) { ElementStack elementStack = ((ElementStack) elementPath); elementStack.popElement(); elementStack.pushElement(modifiedElement); } } catch (Exception ex) { throw new SAXModifyException(ex); } } /** * DOCUMENT ME! * * @return Returns the modified Element. */ protected Element getModifiedElement() { return modifiedElement; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/SAXEventRecorder.java0000644000175000017500000005062510242120006021770 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.dom4j.Namespace; import org.dom4j.QName; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.DTDHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.DeclHandler; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.DefaultHandler; /** *

* Records SAX events such that they may be "replayed" at a later time. Provides * an alternative serialization approach when externalizing a DOM4J document. * Rather than serializing a document as text and re-parsing, the sax events may * be serialized instead. *

* Example usage: * *
 * 
 *  
 *  
 *         SAXEventRecorder recorder = new SAXEventRecorder();
 *         SAXWriter saxWriter = new SAXWriter(recorder, recorder);
 *         saxWriter.write(document);
 *         out.writeObject(recorder);
 *         ...
 *         SAXEventRecorder recorder = (SAXEventRecorder)in.readObject();
 *         SAXContentHandler saxContentHandler = new SAXContentHandler();
 *         recorder.replay(saxContentHandler);
 *         Document document = saxContentHandler.getDocument();
 *  
 *   
 *  
 * 
* * @author Todd Wolff (Bluestem Software) */ public class SAXEventRecorder extends DefaultHandler implements LexicalHandler, DeclHandler, DTDHandler, Externalizable { public static final long serialVersionUID = 1; private static final byte STRING = 0; private static final byte OBJECT = 1; private static final byte NULL = 2; private List events = new ArrayList(); private Map prefixMappings = new HashMap(); private static final String XMLNS = "xmlns"; private static final String EMPTY_STRING = ""; public SAXEventRecorder() { } public void replay(ContentHandler handler) throws SAXException { SAXEvent saxEvent; Iterator itr = events.iterator(); while (itr.hasNext()) { saxEvent = (SAXEvent) itr.next(); switch (saxEvent.event) { // replay to ContentHandler case SAXEvent.PROCESSING_INSTRUCTION: handler.processingInstruction((String) saxEvent.getParm(0), (String) saxEvent.getParm(1)); break; case SAXEvent.START_PREFIX_MAPPING: handler.startPrefixMapping((String) saxEvent.getParm(0), (String) saxEvent.getParm(1)); break; case SAXEvent.END_PREFIX_MAPPING: handler.endPrefixMapping((String) saxEvent.getParm(0)); break; case SAXEvent.START_DOCUMENT: handler.startDocument(); break; case SAXEvent.END_DOCUMENT: handler.endDocument(); break; case SAXEvent.START_ELEMENT: AttributesImpl attributes = new AttributesImpl(); List attParmList = (List) saxEvent.getParm(3); if (attParmList != null) { Iterator attsItr = attParmList.iterator(); while (attsItr.hasNext()) { String[] attParms = (String[]) attsItr.next(); attributes.addAttribute(attParms[0], attParms[1], attParms[2], attParms[3], attParms[4]); } } handler.startElement((String) saxEvent.getParm(0), (String) saxEvent.getParm(1), (String) saxEvent .getParm(2), attributes); break; case SAXEvent.END_ELEMENT: handler.endElement((String) saxEvent.getParm(0), (String) saxEvent.getParm(1), (String) saxEvent .getParm(2)); break; case SAXEvent.CHARACTERS: char[] chars = (char[]) saxEvent.getParm(0); int start = ((Integer) saxEvent.getParm(1)).intValue(); int end = ((Integer) saxEvent.getParm(2)).intValue(); handler.characters(chars, start, end); break; // replay to LexicalHandler case SAXEvent.START_DTD: ((LexicalHandler) handler).startDTD((String) saxEvent .getParm(0), (String) saxEvent.getParm(1), (String) saxEvent.getParm(2)); break; case SAXEvent.END_DTD: ((LexicalHandler) handler).endDTD(); break; case SAXEvent.START_ENTITY: ((LexicalHandler) handler).startEntity((String) saxEvent .getParm(0)); break; case SAXEvent.END_ENTITY: ((LexicalHandler) handler).endEntity((String) saxEvent .getParm(0)); break; case SAXEvent.START_CDATA: ((LexicalHandler) handler).startCDATA(); break; case SAXEvent.END_CDATA: ((LexicalHandler) handler).endCDATA(); break; case SAXEvent.COMMENT: char[] cchars = (char[]) saxEvent.getParm(0); int cstart = ((Integer) saxEvent.getParm(1)).intValue(); int cend = ((Integer) saxEvent.getParm(2)).intValue(); ((LexicalHandler) handler).comment(cchars, cstart, cend); break; // replay to DeclHandler case SAXEvent.ELEMENT_DECL: ((DeclHandler) handler).elementDecl((String) saxEvent .getParm(0), (String) saxEvent.getParm(1)); break; case SAXEvent.ATTRIBUTE_DECL: ((DeclHandler) handler).attributeDecl((String) saxEvent .getParm(0), (String) saxEvent.getParm(1), (String) saxEvent.getParm(2), (String) saxEvent .getParm(3), (String) saxEvent.getParm(4)); break; case SAXEvent.INTERNAL_ENTITY_DECL: ((DeclHandler) handler).internalEntityDecl( (String) saxEvent.getParm(0), (String) saxEvent .getParm(1)); break; case SAXEvent.EXTERNAL_ENTITY_DECL: ((DeclHandler) handler).externalEntityDecl( (String) saxEvent.getParm(0), (String) saxEvent .getParm(1), (String) saxEvent.getParm(2)); break; default: throw new SAXException("Unrecognized event: " + saxEvent.event); } } } // ContentHandler interface // ------------------------------------------------------------------------- public void processingInstruction(String target, String data) throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.PROCESSING_INSTRUCTION); saxEvent.addParm(target); saxEvent.addParm(data); events.add(saxEvent); } public void startPrefixMapping(String prefix, String uri) throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.START_PREFIX_MAPPING); saxEvent.addParm(prefix); saxEvent.addParm(uri); events.add(saxEvent); } public void endPrefixMapping(String prefix) throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.END_PREFIX_MAPPING); saxEvent.addParm(prefix); events.add(saxEvent); } public void startDocument() throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.START_DOCUMENT); events.add(saxEvent); } public void endDocument() throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.END_DOCUMENT); events.add(saxEvent); } public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes attributes) throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.START_ELEMENT); saxEvent.addParm(namespaceURI); saxEvent.addParm(localName); saxEvent.addParm(qualifiedName); QName qName = null; if (namespaceURI != null) { qName = new QName(localName, Namespace.get(namespaceURI)); } else { qName = new QName(localName); } if ((attributes != null) && (attributes.getLength() > 0)) { List attParmList = new ArrayList(attributes.getLength()); String[] attParms = null; for (int i = 0; i < attributes.getLength(); i++) { String attLocalName = attributes.getLocalName(i); if (attLocalName.startsWith(XMLNS)) { // if SAXWriter is writing a DOMDocument, namespace // decls are treated as attributes. record a start // prefix mapping event String prefix = null; if (attLocalName.length() > 5) { prefix = attLocalName.substring(6); } else { prefix = EMPTY_STRING; } SAXEvent prefixEvent = new SAXEvent( SAXEvent.START_PREFIX_MAPPING); prefixEvent.addParm(prefix); prefixEvent.addParm(attributes.getValue(i)); events.add(prefixEvent); // 'register' the prefix so that we can generate // an end prefix mapping event within endElement List prefixes = (List) prefixMappings.get(qName); if (prefixes == null) { prefixes = new ArrayList(); prefixMappings.put(qName, prefixes); } prefixes.add(prefix); } else { attParms = new String[5]; attParms[0] = attributes.getURI(i); attParms[1] = attLocalName; attParms[2] = attributes.getQName(i); attParms[3] = attributes.getType(i); attParms[4] = attributes.getValue(i); attParmList.add(attParms); } } saxEvent.addParm(attParmList); } events.add(saxEvent); } public void endElement(String namespaceURI, String localName, String qName) throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.END_ELEMENT); saxEvent.addParm(namespaceURI); saxEvent.addParm(localName); saxEvent.addParm(qName); events.add(saxEvent); // check to see if a we issued a start prefix mapping event // for DOMDocument namespace decls QName elementName = null; if (namespaceURI != null) { elementName = new QName(localName, Namespace.get(namespaceURI)); } else { elementName = new QName(localName); } List prefixes = (List) prefixMappings.get(elementName); if (prefixes != null) { Iterator itr = prefixes.iterator(); while (itr.hasNext()) { SAXEvent prefixEvent = new SAXEvent(SAXEvent.END_PREFIX_MAPPING); prefixEvent.addParm(itr.next()); events.add(prefixEvent); } } } public void characters(char[] ch, int start, int end) throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.CHARACTERS); saxEvent.addParm(ch); saxEvent.addParm(new Integer(start)); saxEvent.addParm(new Integer(end)); events.add(saxEvent); } // LexicalHandler interface // ------------------------------------------------------------------------- public void startDTD(String name, String publicId, String systemId) throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.START_DTD); saxEvent.addParm(name); saxEvent.addParm(publicId); saxEvent.addParm(systemId); events.add(saxEvent); } public void endDTD() throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.END_DTD); events.add(saxEvent); } public void startEntity(String name) throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.START_ENTITY); saxEvent.addParm(name); events.add(saxEvent); } public void endEntity(String name) throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.END_ENTITY); saxEvent.addParm(name); events.add(saxEvent); } public void startCDATA() throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.START_CDATA); events.add(saxEvent); } public void endCDATA() throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.END_CDATA); events.add(saxEvent); } public void comment(char[] ch, int start, int end) throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.COMMENT); saxEvent.addParm(ch); saxEvent.addParm(new Integer(start)); saxEvent.addParm(new Integer(end)); events.add(saxEvent); } // DeclHandler interface // ------------------------------------------------------------------------- public void elementDecl(String name, String model) throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.ELEMENT_DECL); saxEvent.addParm(name); saxEvent.addParm(model); events.add(saxEvent); } public void attributeDecl(String eName, String aName, String type, String valueDefault, String value) throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.ATTRIBUTE_DECL); saxEvent.addParm(eName); saxEvent.addParm(aName); saxEvent.addParm(type); saxEvent.addParm(valueDefault); saxEvent.addParm(value); events.add(saxEvent); } public void internalEntityDecl(String name, String value) throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.INTERNAL_ENTITY_DECL); saxEvent.addParm(name); saxEvent.addParm(value); events.add(saxEvent); } public void externalEntityDecl(String name, String publicId, String sysId) throws SAXException { SAXEvent saxEvent = new SAXEvent(SAXEvent.EXTERNAL_ENTITY_DECL); saxEvent.addParm(name); saxEvent.addParm(publicId); saxEvent.addParm(sysId); events.add(saxEvent); } public void writeExternal(ObjectOutput out) throws IOException { if (events == null) { out.writeByte(NULL); } else { out.writeByte(OBJECT); out.writeObject(events); } } public void readExternal(ObjectInput in) throws ClassNotFoundException, IOException { if (in.readByte() != NULL) { events = (List) in.readObject(); } } // SAXEvent inner class // ------------------------------------------------------------------------- static class SAXEvent implements Externalizable { public static final long serialVersionUID = 1; static final byte PROCESSING_INSTRUCTION = 1; static final byte START_PREFIX_MAPPING = 2; static final byte END_PREFIX_MAPPING = 3; static final byte START_DOCUMENT = 4; static final byte END_DOCUMENT = 5; static final byte START_ELEMENT = 6; static final byte END_ELEMENT = 7; static final byte CHARACTERS = 8; static final byte START_DTD = 9; static final byte END_DTD = 10; static final byte START_ENTITY = 11; static final byte END_ENTITY = 12; static final byte START_CDATA = 13; static final byte END_CDATA = 14; static final byte COMMENT = 15; static final byte ELEMENT_DECL = 16; static final byte ATTRIBUTE_DECL = 17; static final byte INTERNAL_ENTITY_DECL = 18; static final byte EXTERNAL_ENTITY_DECL = 19; protected byte event; protected List parms; public SAXEvent() { } SAXEvent(byte event) { this.event = event; } void addParm(Object parm) { if (parms == null) { parms = new ArrayList(3); } parms.add(parm); } Object getParm(int index) { if ((parms != null) && (index < parms.size())) { return parms.get(index); } else { return null; } } public void writeExternal(ObjectOutput out) throws IOException { out.writeByte(event); if (parms == null) { out.writeByte(NULL); } else { out.writeByte(OBJECT); out.writeObject(parms); } } public void readExternal(ObjectInput in) throws ClassNotFoundException, IOException { event = in.readByte(); if (in.readByte() != NULL) { parms = (List) in.readObject(); } } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/ElementStack.java0000644000175000017500000001456610242120007021231 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import org.dom4j.Element; import org.dom4j.ElementHandler; import org.dom4j.ElementPath; /** *

* ElementStack is used internally inside the {@link * SAXContentHandler} to maintain a stack of {@link Element}instances. It opens * an integration possibility allowing derivations to prune the tree when a node * is complete. *

* * @author James Strachan * @version $Revision: 1.14 $ */ class ElementStack implements ElementPath { /** stack of Element objects */ protected Element[] stack; /** index of the item at the top of the stack or -1 if the stack is empty */ protected int lastElementIndex = -1; private DispatchHandler handler = null; public ElementStack() { this(50); } public ElementStack(int defaultCapacity) { stack = new Element[defaultCapacity]; } public void setDispatchHandler(DispatchHandler dispatchHandler) { this.handler = dispatchHandler; } public DispatchHandler getDispatchHandler() { return this.handler; } /** * Peeks at the top element on the stack without changing the contents of * the stack. */ public void clear() { lastElementIndex = -1; } /** * Peeks at the top element on the stack without changing the contents of * the stack. * * @return the current element on the stack */ public Element peekElement() { if (lastElementIndex < 0) { return null; } return stack[lastElementIndex]; } /** * Pops the element off the stack * * @return the element that has just been popped off the stack */ public Element popElement() { if (lastElementIndex < 0) { return null; } return stack[lastElementIndex--]; } /** * Pushes a new element onto the stack * * @param element * DOCUMENT ME! */ public void pushElement(Element element) { int length = stack.length; if (++lastElementIndex >= length) { reallocate(length * 2); } stack[lastElementIndex] = element; } /** * Reallocates the stack to the given size * * @param size * DOCUMENT ME! */ protected void reallocate(int size) { Element[] oldStack = stack; stack = new Element[size]; System.arraycopy(oldStack, 0, stack, 0, oldStack.length); } // The ElementPath Interface // public int size() { return lastElementIndex + 1; } public Element getElement(int depth) { Element element; try { element = (Element) stack[depth]; } catch (ArrayIndexOutOfBoundsException e) { element = null; } return element; } public String getPath() { if (handler == null) { setDispatchHandler(new DispatchHandler()); } return handler.getPath(); } public Element getCurrent() { return peekElement(); } public void addHandler(String path, ElementHandler elementHandler) { this.handler.addHandler(getHandlerPath(path), elementHandler); } public void removeHandler(String path) { this.handler.removeHandler(getHandlerPath(path)); } /** * DOCUMENT ME! * * @param path * DOCUMENT ME! * * @return true when an ElementHandler is registered for the * specified path. */ public boolean containsHandler(String path) { return this.handler.containsHandler(path); } private String getHandlerPath(String path) { String handlerPath; if (this.handler == null) { setDispatchHandler(new DispatchHandler()); } if (path.startsWith("/")) { handlerPath = path; } else if (getPath().equals("/")) { handlerPath = getPath() + path; } else { handlerPath = getPath() + "/" + path; } return handlerPath; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/JAXPHelper.java0000644000175000017500000000767410242117777020602 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.XMLReader; /** * JAXPHelper contains some helper methods for working with JAXP. * These methods are kept in a seperate class to avoid class loading issues, * such that dom4j can work without JAXP on the CLASSPATH * * @author James Strachan * @version $Revision: 1.7 $ */ class JAXPHelper { protected JAXPHelper() { } /** * This method attempts to use JAXP to locate the SAX2 XMLReader * implementation. This method uses reflection to avoid being dependent * directly on the JAXP classes. * * @param validating * DOCUMENT ME! * @param namespaceAware * DOCUMENT ME! * * @return DOCUMENT ME! * * @throws Exception * DOCUMENT ME! */ public static XMLReader createXMLReader(boolean validating, boolean namespaceAware) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(validating); factory.setNamespaceAware(namespaceAware); SAXParser parser = factory.newSAXParser(); return parser.getXMLReader(); } public static org.w3c.dom.Document createDocument(boolean validating, boolean namespaceAware) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(validating); factory.setNamespaceAware(namespaceAware); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.newDocument(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/SAXValidator.java0000644000175000017500000001512210242120011021133 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.io.IOException; import org.dom4j.Document; import org.xml.sax.ContentHandler; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; /** *

* SAXValidator validates an XML document by writing the document * to a text buffer and parsing it with a validating SAX parser. This could be * implemented much more efficiently by validating against the dom4j object * model directly but at least allows the reuse of existing SAX based validating * parsers. *

* * @author James Strachan * @version $Revision: 1.10 $ */ public class SAXValidator { /** XMLReader used to parse the SAX events */ private XMLReader xmlReader; /** ErrorHandler class to use */ private ErrorHandler errorHandler; public SAXValidator() { } public SAXValidator(XMLReader xmlReader) { this.xmlReader = xmlReader; } /** * Validates the given Document by writing it to a validating * SAX Parser. * * @param document * is the Document to validate * * @throws SAXException * if a validation error occurs * @throws RuntimeException * DOCUMENT ME! */ public void validate(Document document) throws SAXException { if (document != null) { XMLReader reader = getXMLReader(); if (errorHandler != null) { reader.setErrorHandler(errorHandler); } try { reader.parse(new DocumentInputSource(document)); } catch (IOException e) { throw new RuntimeException("Caught and exception that should " + "never happen: " + e); } } } // Properties // ------------------------------------------------------------------------- /** * DOCUMENT ME! * * @return the XMLReader used to parse SAX events * * @throws SAXException * DOCUMENT ME! */ public XMLReader getXMLReader() throws SAXException { if (xmlReader == null) { xmlReader = createXMLReader(); configureReader(); } return xmlReader; } /** * Sets the XMLReader used to parse SAX events * * @param reader * is the XMLReader to parse SAX events * * @throws SAXException * DOCUMENT ME! */ public void setXMLReader(XMLReader reader) throws SAXException { this.xmlReader = reader; configureReader(); } /** * DOCUMENT ME! * * @return the ErrorHandler used by SAX */ public ErrorHandler getErrorHandler() { return errorHandler; } /** * Sets the ErrorHandler used by the SAX * XMLReader. * * @param errorHandler * is the ErrorHandler used by SAX */ public void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; } // Implementation methods // ------------------------------------------------------------------------- /** * Factory Method to allow alternate methods of creating and configuring * XMLReader objects * * @return DOCUMENT ME! * * @throws SAXException * DOCUMENT ME! */ protected XMLReader createXMLReader() throws SAXException { return SAXHelper.createXMLReader(true); } /** * Configures the XMLReader before use * * @throws SAXException * DOCUMENT ME! */ protected void configureReader() throws SAXException { ContentHandler handler = xmlReader.getContentHandler(); if (handler == null) { xmlReader.setContentHandler(new DefaultHandler()); } // configure validation support xmlReader.setFeature("http://xml.org/sax/features/validation", true); // configure namespace support xmlReader.setFeature("http://xml.org/sax/features/namespaces", true); xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/DocumentInputSource.java0000644000175000017500000001177310242120013022623 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import org.dom4j.Document; import org.xml.sax.InputSource; /** *

* DocumentInputSource implements a SAX {@link InputSource}for a * {@link Document}. *

* * @author James Strachan * @version $Revision: 1.8 $ */ class DocumentInputSource extends InputSource { /** The document source */ private Document document; public DocumentInputSource() { } public DocumentInputSource(Document document) { this.document = document; setSystemId(document.getName()); } // Properties // ------------------------------------------------------------------------- /** * DOCUMENT ME! * * @return the document which is being used as the SAX {@link InputSource} */ public Document getDocument() { return document; } /** * Sets the document used as the SAX {@link InputSource} * * @param document * DOCUMENT ME! */ public void setDocument(Document document) { this.document = document; setSystemId(document.getName()); } // Overloaded methods // ------------------------------------------------------------------------- /** * This method is not supported as this source is always a {@linkDocument} * instance. * * @param characterStream * DOCUMENT ME! * * @throws UnsupportedOperationException * as this method is unsupported */ public void setCharacterStream(Reader characterStream) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** * Note this method is quite inefficent, it turns the in memory XML tree * object model into a single block of text which can then be read by other * XML parsers. Should only be used with care. * * @return DOCUMENT ME! */ public Reader getCharacterStream() { try { StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out); writer.write(document); writer.flush(); return new StringReader(out.toString()); } catch (final IOException e) { // this should never really happen // but for completeness we'll return a Reader // with the embedded exception inside it return new Reader() { public int read(char[] ch, int offset, int length) throws IOException { throw e; } public void close() throws IOException { } }; } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/package.html0000644000175000017500000000026610242120006020257 0ustar ebourgebourg

Provides input and output via SAX and DOM together with writing dom4j objects to streams as XML text.

dom4j-1.6.1/src/java/org/dom4j/io/XPP3Reader.java0000644000175000017500000004341310242120003020514 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import java.io.BufferedReader; import java.io.CharArrayReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.ElementHandler; import org.dom4j.QName; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; /** *

* XPP3Reader is a Reader of DOM4J documents that uses the fast * XML Pull Parser 3.x . * It is very fast for use in SOAP style environments. *

* * @author Pelle Braendgaard * @author James Strachan * @version $Revision: 1.3 $ */ public class XPP3Reader { /** DocumentFactory used to create new document objects */ private DocumentFactory factory; /** XmlPullParser used to parse XML */ private XmlPullParser xppParser; /** XmlPullParser used to parse XML */ private XmlPullParserFactory xppFactory; /** DispatchHandler to call when each Element is encountered */ private DispatchHandler dispatchHandler; public XPP3Reader() { } public XPP3Reader(DocumentFactory factory) { this.factory = factory; } /** *

* Reads a Document from the given File *

* * @param file * is the File to read from. * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * if a URL could not be made for the given File * @throws XmlPullParserException * DOCUMENT ME! */ public Document read(File file) throws DocumentException, IOException, XmlPullParserException { String systemID = file.getAbsolutePath(); return read(new BufferedReader(new FileReader(file)), systemID); } /** *

* Reads a Document from the given URL *

* * @param url * URL to read from. * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * DOCUMENT ME! * @throws XmlPullParserException * DOCUMENT ME! */ public Document read(URL url) throws DocumentException, IOException, XmlPullParserException { String systemID = url.toExternalForm(); return read(createReader(url.openStream()), systemID); } /** *

* Reads a Document from the given URL or filename. *

* *

* If the systemID contains a ':' character then it is * assumed to be a URL otherwise its assumed to be a file name. If you want * finer grained control over this mechansim then please explicitly pass in * either a {@link URL}or a {@link File}instance instead of a {@link * String} to denote the source of the document. *

* * @param systemID * is a URL for a document or a file name. * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * if a URL could not be made for the given File * @throws XmlPullParserException * DOCUMENT ME! */ public Document read(String systemID) throws DocumentException, IOException, XmlPullParserException { if (systemID.indexOf(':') >= 0) { // lets assume its a URL return read(new URL(systemID)); } else { // lets assume that we are given a file name return read(new File(systemID)); } } /** *

* Reads a Document from the given stream *

* * @param in * InputStream to read from. * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * DOCUMENT ME! * @throws XmlPullParserException * DOCUMENT ME! */ public Document read(InputStream in) throws DocumentException, IOException, XmlPullParserException { return read(createReader(in)); } /** *

* Reads a Document from the given Reader *

* * @param reader * is the reader for the input * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * DOCUMENT ME! * @throws XmlPullParserException * DOCUMENT ME! */ public Document read(Reader reader) throws DocumentException, IOException, XmlPullParserException { getXPPParser().setInput(reader); return parseDocument(); } /** *

* Reads a Document from the given array of characters *

* * @param text * is the text to parse * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * DOCUMENT ME! * @throws XmlPullParserException * DOCUMENT ME! */ public Document read(char[] text) throws DocumentException, IOException, XmlPullParserException { getXPPParser().setInput(new CharArrayReader(text)); return parseDocument(); } /** *

* Reads a Document from the given stream *

* * @param in * InputStream to read from. * @param systemID * is the URI for the input * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * DOCUMENT ME! * @throws XmlPullParserException * DOCUMENT ME! */ public Document read(InputStream in, String systemID) throws DocumentException, IOException, XmlPullParserException { return read(createReader(in), systemID); } /** *

* Reads a Document from the given Reader *

* * @param reader * is the reader for the input * @param systemID * is the URI for the input * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * DOCUMENT ME! * @throws XmlPullParserException * DOCUMENT ME! */ public Document read(Reader reader, String systemID) throws DocumentException, IOException, XmlPullParserException { Document document = read(reader); document.setName(systemID); return document; } // Properties // ------------------------------------------------------------------------- public XmlPullParser getXPPParser() throws XmlPullParserException { if (xppParser == null) { xppParser = getXPPFactory().newPullParser(); } return xppParser; } public XmlPullParserFactory getXPPFactory() throws XmlPullParserException { if (xppFactory == null) { xppFactory = XmlPullParserFactory.newInstance(); } xppFactory.setNamespaceAware(true); return xppFactory; } public void setXPPFactory(XmlPullParserFactory xPPfactory) { this.xppFactory = xPPfactory; } /** * DOCUMENT ME! * * @return the DocumentFactory used to create document * objects */ public DocumentFactory getDocumentFactory() { if (factory == null) { factory = DocumentFactory.getInstance(); } return factory; } /** *

* This sets the DocumentFactory used to create new * documents. This method allows the building of custom DOM4J tree objects * to be implemented easily using a custom derivation of * {@link DocumentFactory} *

* * @param documentFactory * DocumentFactory used to create DOM4J objects */ public void setDocumentFactory(DocumentFactory documentFactory) { this.factory = documentFactory; } /** * Adds the ElementHandler to be called when the specified * path is encounted. * * @param path * is the path to be handled * @param handler * is the ElementHandler to be called by the event * based processor. */ public void addHandler(String path, ElementHandler handler) { getDispatchHandler().addHandler(path, handler); } /** * Removes the ElementHandler from the event based processor, * for the specified path. * * @param path * is the path to remove the ElementHandler for. */ public void removeHandler(String path) { getDispatchHandler().removeHandler(path); } /** * When multiple ElementHandler instances have been * registered, this will set a default ElementHandler to be * called for any path which does NOT have a handler registered. * * @param handler * is the ElementHandler to be called by the event * based processor. */ public void setDefaultHandler(ElementHandler handler) { getDispatchHandler().setDefaultHandler(handler); } // Implementation methods // ------------------------------------------------------------------------- protected Document parseDocument() throws DocumentException, IOException, XmlPullParserException { DocumentFactory df = getDocumentFactory(); Document document = df.createDocument(); Element parent = null; XmlPullParser pp = getXPPParser(); pp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); while (true) { int type = pp.nextToken(); switch (type) { case XmlPullParser.PROCESSING_INSTRUCTION: { String text = pp.getText(); int loc = text.indexOf(" "); if (loc >= 0) { String target = text.substring(0, loc); String txt = text.substring(loc + 1); document.addProcessingInstruction(target, txt); } else { document.addProcessingInstruction(text, ""); } break; } case XmlPullParser.COMMENT: { if (parent != null) { parent.addComment(pp.getText()); } else { document.addComment(pp.getText()); } break; } case XmlPullParser.CDSECT: { if (parent != null) { parent.addCDATA(pp.getText()); } else { String msg = "Cannot have text content outside of the " + "root document"; throw new DocumentException(msg); } break; } case XmlPullParser.ENTITY_REF: break; case XmlPullParser.END_DOCUMENT: return document; case XmlPullParser.START_TAG: { QName qname = (pp.getPrefix() == null) ? df.createQName(pp .getName(), pp.getNamespace()) : df.createQName(pp .getName(), pp.getPrefix(), pp.getNamespace()); Element newElement = df.createElement(qname); int nsStart = pp.getNamespaceCount(pp.getDepth() - 1); int nsEnd = pp.getNamespaceCount(pp.getDepth()); for (int i = nsStart; i < nsEnd; i++) { if (pp.getNamespacePrefix(i) != null) { newElement.addNamespace(pp.getNamespacePrefix(i), pp.getNamespaceUri(i)); } } for (int i = 0; i < pp.getAttributeCount(); i++) { QName qa = (pp.getAttributePrefix(i) == null) ? df .createQName(pp.getAttributeName(i)) : df .createQName(pp.getAttributeName(i), pp .getAttributePrefix(i), pp .getAttributeNamespace(i)); newElement.addAttribute(qa, pp.getAttributeValue(i)); } if (parent != null) { parent.add(newElement); } else { document.add(newElement); } parent = newElement; break; } case XmlPullParser.END_TAG: { if (parent != null) { parent = parent.getParent(); } break; } case XmlPullParser.TEXT: { String text = pp.getText(); if (parent != null) { parent.addText(text); } else { String msg = "Cannot have text content outside of the " + "root document"; throw new DocumentException(msg); } break; } default: break; } } } protected DispatchHandler getDispatchHandler() { if (dispatchHandler == null) { dispatchHandler = new DispatchHandler(); } return dispatchHandler; } protected void setDispatchHandler(DispatchHandler dispatchHandler) { this.dispatchHandler = dispatchHandler; } /** * Factory method to create a Reader from the given InputStream. * * @param in * DOCUMENT ME! * * @return DOCUMENT ME! * * @throws IOException * DOCUMENT ME! */ protected Reader createReader(InputStream in) throws IOException { return new BufferedReader(new InputStreamReader(in)); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/io/PruningElementStack.java0000644000175000017500000001275010242120023022563 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import org.dom4j.Element; import org.dom4j.ElementHandler; /** *

* PruningElementStack is a stack of {@link Element}instances * which will prune the tree when a path expression is reached. This is useful * for parsing very large documents where children of the root element can be * processed individually rather than keeping them all in memory at the same * time. *

* * @author James Strachan * @version $Revision: 1.11 $ */ class PruningElementStack extends ElementStack { /** ElementHandler to call when pruning occurs */ private ElementHandler elementHandler; /** * the element name path which denotes the node to remove from its parent * when it is complete (i.e. when it is popped from the stack). The first * entry in the path will be a child of the root node */ private String[] path; /** * The level at which a path match can occur. We match when we have popped * the selected node so the and the lastElementIndex points to its parent so * this value should be path.length - 2 */ private int matchingElementIndex; public PruningElementStack(String[] path, ElementHandler elementHandler) { this.path = path; this.elementHandler = elementHandler; checkPath(); } public PruningElementStack(String[] path, ElementHandler elementHandler, int defaultCapacity) { super(defaultCapacity); this.path = path; this.elementHandler = elementHandler; checkPath(); } public Element popElement() { Element answer = super.popElement(); if ((lastElementIndex == matchingElementIndex) && (lastElementIndex >= 0)) { // we are popping the correct level in the tree // lets check if the path fits // // NOTE: this is an inefficient way of doing it - we could // maintain a history of which parts matched? if (validElement(answer, lastElementIndex + 1)) { Element parent = null; for (int i = 0; i <= lastElementIndex; i++) { parent = stack[i]; if (!validElement(parent, i)) { parent = null; break; } } if (parent != null) { pathMatches(parent, answer); } } } return answer; } protected void pathMatches(Element parent, Element selectedNode) { elementHandler.onEnd(this); parent.remove(selectedNode); } protected boolean validElement(Element element, int index) { String requiredName = path[index]; String name = element.getName(); if (requiredName == name) { return true; } if ((requiredName != null) && (name != null)) { return requiredName.equals(name); } return false; } private void checkPath() { if (path.length < 2) { throw new RuntimeException("Invalid path of length: " + path.length + " it must be greater than 2"); } matchingElementIndex = path.length - 2; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/CharacterData.java0000644000175000017500000000555510242120011020722 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; /** *

* CharacterData is a marker interface for character based nodes * such as the CDATA,Comment and * Text nodes. *

* * @author James Strachan * @version $Revision: 1.9 $ */ public interface CharacterData extends Node { /** * Appends the given text to this nodes text value. Calling this method is * equivalent of the code node.setText(node.getText() + text) * but allows for possible implementation optimisations (such as a text * based node storing a StringBuffer internally * * @param text * the text to append */ void appendText(String text); } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/CDATA.java0000644000175000017500000000455110242120004017045 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; /** *

* CDATA defines an XML CDATA section. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public interface CDATA extends CharacterData { } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/XPathException.java0000644000175000017500000000626010242120013021133 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; /** *

* XPathException is thrown when an exception occurs while * evaluating an XPath expression, usually due to some function throwing an * exception. *

* * @version $Revision: 1.6 $ */ public class XPathException extends RuntimeException { /** The XPath expression that caused the exception */ private String xpath; public XPathException(String xpath) { super("Exception occurred evaluting XPath: " + xpath); this.xpath = xpath; } public XPathException(String xpath, String reason) { super("Exception occurred evaluting XPath: " + xpath + " " + reason); this.xpath = xpath; } public XPathException(String xpath, Exception e) { super("Exception occurred evaluting XPath: " + xpath + ". Exception: " + e.getMessage()); this.xpath = xpath; } /** * Returns the XPath expression that caused the problem * * @return DOCUMENT ME! */ public String getXPath() { return xpath; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/Node.java0000644000175000017500000005024410242120017017122 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import java.io.IOException; import java.io.Writer; import java.util.List; /** *

* Node defines the polymorphic behavior for all XML nodes in a * dom4j tree. *

* *

* A node can be output as its XML format, can be detached from its position in * a document and can have XPath expressions evaluated on itself. *

* *

* A node may optionally support the parent relationship and may be read only. *

* * @author James Strachan * @version $Revision: 1.31 $ * * @see #supportsParent * @see #isReadOnly */ public interface Node extends Cloneable { // W3C DOM complient node type codes /** Matches Element nodes */ short ANY_NODE = 0; /** Matches Element nodes */ short ELEMENT_NODE = 1; /** Matches elements nodes */ short ATTRIBUTE_NODE = 2; /** Matches elements nodes */ short TEXT_NODE = 3; /** Matches elements nodes */ short CDATA_SECTION_NODE = 4; /** Matches elements nodes */ short ENTITY_REFERENCE_NODE = 5; /** Matches elements nodes */ // public static final short ENTITY_NODE = 6; /** Matches ProcessingInstruction */ short PROCESSING_INSTRUCTION_NODE = 7; /** Matches Comments nodes */ short COMMENT_NODE = 8; /** Matches Document nodes */ short DOCUMENT_NODE = 9; /** Matches DocumentType nodes */ short DOCUMENT_TYPE_NODE = 10; // public static final short DOCUMENT_FRAGMENT_NODE = 11; // public static final short NOTATION_NODE = 12; /** Matchs a Namespace Node - NOTE this differs from DOM */ // XXXX: ???? short NAMESPACE_NODE = 13; /** Does not match any valid node */ short UNKNOWN_NODE = 14; /** The maximum number of node types for sizing purposes */ short MAX_NODE_TYPE = 14; /** *

* supportsParent returns true if this node supports the * parent relationship. *

* *

* Some XML tree implementations are singly linked and only support downward * navigation through children relationships. The default case is that both * parent and children relationships are supported though for memory and * performance reasons the parent relationship may not be supported. *

* * @return true if this node supports the parent relationship or false it is * not supported */ boolean supportsParent(); /** *

* getParent returns the parent Element if * this node supports the parent relationship or null if it is the root * element or does not support the parent relationship. *

* *

* This method is an optional feature and may not be supported for all * Node implementations. *

* * @return the parent of this node or null if it is the root of the tree or * the parent relationship is not supported. */ Element getParent(); /** *

* setParent sets the parent relationship of this node if the * parent relationship is supported or does nothing if the parent * relationship is not supported. *

* *

* This method should only be called from inside an Element * implementation method and is not intended for general use. *

* * @param parent * is the new parent of this node. */ void setParent(Element parent); /** *

* getDocument returns the Document that this * Node is part of if this node supports the parent * relationship. *

* *

* This method is an optional feature and may not be supported for all * Node implementations. *

* * @return the document of this node or null if this feature is not * supported or the node is not associated with a * Document */ Document getDocument(); /** *

* setDocument sets the document of this node if the parent * relationship is supported or does nothing if the parent relationship is * not supported. *

* *

* This method should only be called from inside a Document * implementation method and is not intended for general use. *

* * @param document * is the new document of this node. */ void setDocument(Document document); /** *

* isReadOnly returns true if this node is read only and * cannot be modified. Any attempt to modify a read-only Node * will result in an UnsupportedOperationException being * thrown. *

* * @return true if this Node is read only and cannot be * modified otherwise false. */ boolean isReadOnly(); /** *

* hasContent returns true if this node is a Branch (either * an Element or a Document) and it contains at least one content node such * as a child Element or Text node. *

* * @return true if this Node is a Branch with a nodeCount() * of one or more. */ boolean hasContent(); /** *

* getName returns the name of this node. This is the XML * local name of the element, attribute, entity or processing instruction. * For CDATA and Text nodes this method will return null. *

* * @return the XML name of this node */ String getName(); /** *

* Sets the text data of this node or this method will throw an * UnsupportedOperationException if it is read-only. *

* * @param name * is the new name of this node */ void setName(String name); /** *

* Returns the text of this node. *

* * @return the text for this node. */ String getText(); /** *

* Sets the text data of this node or this method will throw an * UnsupportedOperationException if it is read-only. *

* * @param text * is the new textual value of this node */ void setText(String text); /** * Returns the XPath string-value of this node. The behaviour of this method * is defined in the XPath * specification . * * @return the text from all the child Text and Element nodes appended * together. */ String getStringValue(); /** *

* Returns the XPath expression which will return a node set containing the * given node such as /a/b/@c. No indexing will be used to restrict the * path if multiple elements with the same name occur on the path. *

* * @return the XPath expression which will return a nodeset containing at * least this node. */ String getPath(); /** * Returns the relative XPath expression which will return a node set * containing the given node such as a/b/@c. No indexing will be used to * restrict the path if multiple elements with the same name occur on the * path. * * @param context * is the parent context from which the relative path should * start. If the context is null or the context is not an * ancestor of this node then the path will be absolute and start * from the document and so begin with the '/' character. * * @return the XPath expression relative to the given context which will * return a nodeset containing at least this node. */ String getPath(Element context); /** *

* Returns the XPath expression which will return a nodeset of one node * which is the current node. This method will use the XPath index operator * to restrict the path if multiple elements with the same name occur on the * path. *

* * @return the XPath expression which will return a nodeset containing just * this node. */ String getUniquePath(); /** *

* Returns the relative unique XPath expression from the given context which * will return a nodeset of one node which is the current node. This method * will use the XPath index operator to restrict the path if multiple * elements with the same name occur on the path. *

* * @param context * is the parent context from which the path should start. If the * context is null or the context is not an ancestor of this node * then the path will start from the document and so begin with * the '/' character. * * @return the XPath expression relative to the given context which will * return a nodeset containing just this node. */ String getUniquePath(Element context); /** *

* asXML returns the textual XML representation of this node. *

* * @return the XML representation of this node */ String asXML(); /** *

* write writes this node as the default XML notation for * this node. If you wish to control the XML output (such as for pretty * printing, changing the indentation policy etc.) then please use {@link * org.dom4j.io.XMLWriter} or its derivations. *

* * @param writer * is the Writer to output the XML to * * @throws IOException * DOCUMENT ME! */ void write(Writer writer) throws IOException; /** * Returns the code according to the type of node. This makes processing * nodes polymorphically much easier as the switch statement can be used * instead of multiple if (instanceof) statements. * * @return a W3C DOM complient code for the node type such as ELEMENT_NODE * or ATTRIBUTE_NODE */ short getNodeType(); /** * DOCUMENT ME! * * @return the name of the type of node such as "Document", "Element", * "Attribute" or "Text" */ String getNodeTypeName(); /** *

* Removes this node from its parent if there is one. If this node is the * root element of a document then it is removed from the document as well. *

* *

* This method is useful if you want to remove a node from its source * document and add it to another document. For example *

* Node node = ...; Element someOtherElement = ...; * someOtherElement.add( node.detach() ); * * @return the node that has been removed from its parent node if any and * its document if any. */ Node detach(); /** *

* selectNodes evaluates an XPath expression and returns the * result as a List of Node instances or * String instances depending on the XPath expression. *

* * @param xpathExpression * is the XPath expression to be evaluated * * @return the list of Node or String * instances depending on the XPath expression */ List selectNodes(String xpathExpression); /** *

* selectObject evaluates an XPath expression and returns the * result as an {@link Object}. The object returned can either be a {@link * List} of one or more {@link Node}instances or a scalar object like a * {@link String}or a {@link Number}instance depending on the XPath * expression. *

* * @param xpathExpression * is the XPath expression to be evaluated * * @return the value of the XPath expression as a {@link List}of {@link * Node} instances, a {@link String}or a {@link Number}instance * depending on the XPath expression. */ Object selectObject(String xpathExpression); /** *

* selectNodes evaluates an XPath expression then sorts the * results using a secondary XPath expression Returns a sorted * List of Node instances. *

* * @param xpathExpression * is the XPath expression to be evaluated * @param comparisonXPathExpression * is the XPath expression used to compare the results by for * sorting * * @return the list of Node instances sorted by the * comparisonXPathExpression */ List selectNodes(String xpathExpression, String comparisonXPathExpression); /** *

* selectNodes evaluates an XPath expression then sorts the * results using a secondary XPath expression Returns a sorted * List of Node instances. *

* * @param xpathExpression * is the XPath expression to be evaluated * @param comparisonXPathExpression * is the XPath expression used to compare the results by for * sorting * @param removeDuplicates * if this parameter is true then duplicate values (using the * comparisonXPathExpression) are removed from the result List. * * @return the list of Node instances sorted by the * comparisonXPathExpression */ List selectNodes(String xpathExpression, String comparisonXPathExpression, boolean removeDuplicates); /** *

* selectSingleNode evaluates an XPath expression and returns * the result as a single Node instance. *

* * @param xpathExpression * is the XPath expression to be evaluated * * @return the Node matching the XPath expression */ Node selectSingleNode(String xpathExpression); /** *

* valueOf evaluates an XPath expression and returns the * textual representation of the results the XPath string-value of this * node. The string-value for a given node type is defined in the XPath specification . *

* * @param xpathExpression * is the XPath expression to be evaluated * * @return the string-value representation of the results of the XPath * expression */ String valueOf(String xpathExpression); /** *

* numberValueOf evaluates an XPath expression and returns * the numeric value of the XPath expression if the XPath expression results * in a number, or null if the result is not a number. *

* * @param xpathExpression * is the XPath expression to be evaluated * * @return the numeric result of the XPath expression or null if the result * is not a number. */ Number numberValueOf(String xpathExpression); /** *

* matches returns true if evaluating the given XPath * expression on this node returns a non-empty node set containing this * node. *

* *

* This method does not behave like the <xsl:if> element - if you want * that behaviour, to evaluate if an XPath expression matches something, * then you can use the following code to be equivalent... *

* if ( node.selectSingleNode( "/some/path" ) != nulll ) * * @param xpathExpression * is an XPath expression * * @return true if this node is returned by the given XPath expression */ boolean matches(String xpathExpression); /** *

* createXPath creates an XPath object for the given * xpathExpression. The XPath object allows the variable context to be * specified. *

* * @param xpathExpression * is the XPath expression to be evaluated * * @return an XPath object represeting the given expression * * @throws InvalidXPathException * if the XPath expression is invalid */ XPath createXPath(String xpathExpression) throws InvalidXPathException; /** *

* asXPathResult returns a version of this node which is * capable of being an XPath result. The result of an XPath expression * should always support the parent relationship, whether the original XML * tree was singly or doubly linked. If the node does not support the parent * relationship then a new node will be created which is linked to its * parent and returned. *

* * @param parent * DOCUMENT ME! * * @return a Node which supports the parent relationship */ Node asXPathResult(Element parent); /** *

* accept is the method used in the Visitor Pattern. *

* * @param visitor * is the visitor in the Visitor Pattern */ void accept(Visitor visitor); /** *

* clone will return a deep clone or if this node is * read-only then clone will return the same instance. *

* * @return a deep clone of myself or myself if I am read only. */ Object clone(); } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/util/0000755000175000017500000000000012133227266016361 5ustar ebourgebourgdom4j-1.6.1/src/java/org/dom4j/util/SingletonStrategy.java0000644000175000017500000000624510242120013022675 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.util; /** *

* SingletonStrategy is an interface used to provide common * factory access for the same object based on an implementation strategy for * singleton. Right now there are two that accompany this interface: * SimpleSingleton and PerThreadSingleton. This will replace previous usage of * ThreadLocal to allow for alternate strategies. *

* * @author David Lucas * @version $Revision: 1.2 $ */ public interface SingletonStrategy { /** * return a singleton instance of the class specified in setSingletonClass */ Object instance(); /** * reset the instance to a new instance for the implemented strategy */ void reset(); /** * set a singleton class name that will be used to create the singleton * based on the strategy implementation of this interface. The default * constructor of the class will be used and must be public. */ void setSingletonClassName(String singletonClassName); } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/util/NodeComparator.java0000644000175000017500000002561310242120010022122 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.util; import java.util.Comparator; import org.dom4j.Attribute; import org.dom4j.Branch; import org.dom4j.CDATA; import org.dom4j.CharacterData; import org.dom4j.Comment; import org.dom4j.Document; import org.dom4j.DocumentType; import org.dom4j.Element; import org.dom4j.Entity; import org.dom4j.Namespace; import org.dom4j.Node; import org.dom4j.ProcessingInstruction; import org.dom4j.QName; import org.dom4j.Text; /** *

* NodeComparator is a {@link Comparator}of Node instances which * is capable of comparing Nodes for equality based on their values. *

* * @author James Strachan * @version $Revision: 1.10 $ */ public class NodeComparator implements Comparator { /** * Compares its two arguments for order. Returns a negative integer, zero, * or a positive integer as the first argument is less than, equal to, or * greater than the second. * *

* The implementor must ensure that sgn(compare(x, y)) == * -sgn(compare(y, x)) * for all x and y. (This implies that * compare(x, y) must throw an exception if and only if * compare(y, x) throws an exception.) *

* *

* The implementor must also ensure that the relation is transitive: * ((compare(x, y)>0) && (compare(y, z)>0)) implies * compare(x, z)>0. *

* *

* Finally, the implementer must ensure that compare(x, y)==0 * implies that sgn(compare(x, z))==sgn(compare(y, z)) for all * z. *

* *

* It is generally the case, but not strictly required that * (compare(x, y)==0) == (x.equals(y)). Generally speaking, any * comparator that violates this condition should clearly indicate this * fact. The recommended language is "Note: this comparator imposes * orderings that are inconsistent with equals." *

* * @param o1 * the first object to be compared. * @param o2 * the second object to be compared. * * @return a negative integer, zero, or a positive integer as the first * argument is less than, equal to, or greater than the second. */ public int compare(Object o1, Object o2) { if (o1 == o2) { return 0; } else if (o1 == null) { // null is less return -1; } else if (o2 == null) { return 1; } if (o1 instanceof Node) { if (o2 instanceof Node) { return compare((Node) o1, (Node) o2); } else { // Node implementations are greater return 1; } } else { if (o2 instanceof Node) { // Node implementations are greater return -1; } else { if (o1 instanceof Comparable) { Comparable c1 = (Comparable) o1; return c1.compareTo(o2); } else { String name1 = o1.getClass().getName(); String name2 = o2.getClass().getName(); return name1.compareTo(name2); } } } } public int compare(Node n1, Node n2) { int nodeType1 = n1.getNodeType(); int nodeType2 = n2.getNodeType(); int answer = nodeType1 - nodeType2; if (answer != 0) { return answer; } else { switch (nodeType1) { case Node.ELEMENT_NODE: return compare((Element) n1, (Element) n2); case Node.DOCUMENT_NODE: return compare((Document) n1, (Document) n2); case Node.ATTRIBUTE_NODE: return compare((Attribute) n1, (Attribute) n2); case Node.TEXT_NODE: return compare((Text) n1, (Text) n2); case Node.CDATA_SECTION_NODE: return compare((CDATA) n1, (CDATA) n2); case Node.ENTITY_REFERENCE_NODE: return compare((Entity) n1, (Entity) n2); case Node.PROCESSING_INSTRUCTION_NODE: return compare((ProcessingInstruction) n1, (ProcessingInstruction) n2); case Node.COMMENT_NODE: return compare((Comment) n1, (Comment) n2); case Node.DOCUMENT_TYPE_NODE: return compare((DocumentType) n1, (DocumentType) n2); case Node.NAMESPACE_NODE: return compare((Namespace) n1, (Namespace) n2); default: throw new RuntimeException("Invalid node types. node1: " + n1 + " and node2: " + n2); } } } public int compare(Document n1, Document n2) { int answer = compare(n1.getDocType(), n2.getDocType()); if (answer == 0) { answer = compareContent(n1, n2); } return answer; } public int compare(Element n1, Element n2) { int answer = compare(n1.getQName(), n2.getQName()); if (answer == 0) { // lets compare attributes int c1 = n1.attributeCount(); int c2 = n2.attributeCount(); answer = c1 - c2; if (answer == 0) { for (int i = 0; i < c1; i++) { Attribute a1 = n1.attribute(i); Attribute a2 = n2.attribute(a1.getQName()); answer = compare(a1, a2); if (answer != 0) { return answer; } } answer = compareContent(n1, n2); } } return answer; } public int compare(Attribute n1, Attribute n2) { int answer = compare(n1.getQName(), n2.getQName()); if (answer == 0) { answer = compare(n1.getValue(), n2.getValue()); } return answer; } public int compare(QName n1, QName n2) { int answer = compare(n1.getNamespaceURI(), n2.getNamespaceURI()); if (answer == 0) { answer = compare(n1.getQualifiedName(), n2.getQualifiedName()); } return answer; } public int compare(Namespace n1, Namespace n2) { int answer = compare(n1.getURI(), n2.getURI()); if (answer == 0) { answer = compare(n1.getPrefix(), n2.getPrefix()); } return answer; } public int compare(CharacterData t1, CharacterData t2) { return compare(t1.getText(), t2.getText()); } public int compare(DocumentType o1, DocumentType o2) { if (o1 == o2) { return 0; } else if (o1 == null) { // null is less return -1; } else if (o2 == null) { return 1; } int answer = compare(o1.getPublicID(), o2.getPublicID()); if (answer == 0) { answer = compare(o1.getSystemID(), o2.getSystemID()); if (answer == 0) { answer = compare(o1.getName(), o2.getName()); } } return answer; } public int compare(Entity n1, Entity n2) { int answer = compare(n1.getName(), n2.getName()); if (answer == 0) { answer = compare(n1.getText(), n2.getText()); } return answer; } public int compare(ProcessingInstruction n1, ProcessingInstruction n2) { int answer = compare(n1.getTarget(), n2.getTarget()); if (answer == 0) { answer = compare(n1.getText(), n2.getText()); } return answer; } public int compareContent(Branch b1, Branch b2) { int c1 = b1.nodeCount(); int c2 = b2.nodeCount(); int answer = c1 - c2; if (answer == 0) { for (int i = 0; i < c1; i++) { Node n1 = b1.node(i); Node n2 = b2.node(i); answer = compare(n1, n2); if (answer != 0) { break; } } } return answer; } public int compare(String o1, String o2) { if (o1 == o2) { return 0; } else if (o1 == null) { // null is less return -1; } else if (o2 == null) { return 1; } return o1.compareTo(o2); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/util/IndexedDocumentFactory.java0000644000175000017500000000657310242120012023622 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.util; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.QName; /** *

* IndexedDocumentFactory is a factory of XML objects which * create indexed Element implementations to allow quicker lookup via name of * Element and Attributes though at the expense of more memory used to create * the name indexes. *

* * @author James Strachan * @version $Revision: 1.9 $ */ public class IndexedDocumentFactory extends DocumentFactory { /** The Singleton instance */ protected static transient IndexedDocumentFactory singleton = new IndexedDocumentFactory(); /** *

* Access to the singleton instance of this factory. *

* * @return the default singleon instance */ public static DocumentFactory getInstance() { return singleton; } // DocumentFactory methods // ------------------------------------------------------------------------- public Element createElement(QName qname) { return new IndexedElement(qname); } public Element createElement(QName qname, int attributeCount) { return new IndexedElement(qname, attributeCount); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/util/UserDataAttribute.java0000644000175000017500000000612310242120013022577 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.util; import org.dom4j.QName; import org.dom4j.tree.DefaultAttribute; /** *

* UserDataAttribute support the adornment of a user data object * on an Element or Attribute instance such that the methods {@link#getData} * {@link #setData(Object)}will get and set the values of a user data object. * This can be useful for developers wishing to create XML trees and adorn the * trees with user defined objects. *

* * @author James Strachan * @version $Revision: 1.8 $ */ public class UserDataAttribute extends DefaultAttribute { /** The user data object */ private Object data; public UserDataAttribute(QName qname) { super(qname); } public UserDataAttribute(QName qname, String text) { super(qname, text); } public Object getData() { return data; } public void setData(Object data) { this.data = data; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/util/UserDataElement.java0000644000175000017500000001050710242120001022223 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.util; import org.dom4j.Element; import org.dom4j.QName; import org.dom4j.tree.DefaultElement; /** *

* UserDataElement support the adornment of a user data object on * an Element or Attribute instance such that the methods {@link#getData} * {@link #setData(Object)}will get and set the values of a user data object. * This can be useful for developers wishing to create XML trees and adorn the * trees with user defined objects. *

* * @author James Strachan * @version $Revision: 1.12 $ */ public class UserDataElement extends DefaultElement { /** The user data object */ private Object data; public UserDataElement(String name) { super(name); } public UserDataElement(QName qname) { super(qname); } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public String toString() { return super.toString() + " userData: " + data; } public Object clone() { UserDataElement answer = (UserDataElement) super.clone(); if (answer != this) { answer.data = getCopyOfUserData(); } return answer; } // Implementation methods // ------------------------------------------------------------------------- /** * If a deep copy of user data is required whenever the clone() or * createCopy() methods are called on this element then this method should * return a clone of the user data * * @return DOCUMENT ME! */ protected Object getCopyOfUserData() { return data; } protected Element createElement(String name) { Element answer = getDocumentFactory().createElement(name); answer.setData(getCopyOfUserData()); return answer; } protected Element createElement(QName qName) { Element answer = getDocumentFactory().createElement(qName); answer.setData(getCopyOfUserData()); return answer; } // protected DocumentFactory getDocumentFactory() { // return DOCUMENT_FACTORY; // } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/util/NonLazyDocumentFactory.java0000644000175000017500000000643510242120013023632 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.util; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.QName; /** *

* NonLazyDocumentFactory is a factory of XML objects which avoid * using the lazy creation pattern. This results in a slower creation of a * Document and uses more memory but it means that the same Document instance * can be shared across threads provided it is not modified. *

* * @author James Strachan * @version $Revision: 1.9 $ */ public class NonLazyDocumentFactory extends DocumentFactory { /** The Singleton instance */ protected static transient NonLazyDocumentFactory singleton = new NonLazyDocumentFactory(); /** *

* Access to the singleton instance of this factory. *

* * @return the default singleon instance */ public static DocumentFactory getInstance() { return singleton; } // DocumentFactory methods // ------------------------------------------------------------------------- public Element createElement(QName qname) { return new NonLazyElement(qname); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/util/UserDataDocumentFactory.java0000644000175000017500000000707510242120023023752 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.util; import org.dom4j.Attribute; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.QName; /** *

* UserDataDocumentFactory is a factory of XML objects which * support the adornment of a user data object on an Element or Attribute * instance such that the methods getData() and * setData() will get and set the values of a user data object. * This can be useful for developers wishing to create XML trees and adorn the * trees with user defined objects. *

* * @author James Strachan * @version $Revision: 1.11 $ */ public class UserDataDocumentFactory extends DocumentFactory { /** The Singleton instance */ protected static transient UserDataDocumentFactory singleton = new UserDataDocumentFactory(); /** *

* Access to the singleton instance of this factory. *

* * @return the default singleon instance */ public static DocumentFactory getInstance() { return singleton; } // DocumentFactory methods // ------------------------------------------------------------------------- public Element createElement(QName qname) { return new UserDataElement(qname); } public Attribute createAttribute(Element owner, QName qname, String value) { return new UserDataAttribute(qname, value); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/util/IndexedElement.java0000644000175000017500000002332410242120007022102 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.util; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.dom4j.Attribute; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.QName; import org.dom4j.tree.BackedList; import org.dom4j.tree.DefaultElement; /** *

* IndexedElement is an implementation of {@link Element}which * maintains an index of the attributes and elements it contains to optimise * lookups via name. *

* * @author James Strachan * @version $Revision: 1.10 $ */ public class IndexedElement extends DefaultElement { /** Lazily constructed index for elements */ private Map elementIndex; /** Lazily constructed index for attributes */ private Map attributeIndex; public IndexedElement(String name) { super(name); } public IndexedElement(QName qname) { super(qname); } public IndexedElement(QName qname, int attributeCount) { super(qname, attributeCount); } public Attribute attribute(String name) { return (Attribute) attributeIndex().get(name); } public Attribute attribute(QName qName) { return (Attribute) attributeIndex().get(qName); } public Element element(String name) { return asElement(elementIndex().get(name)); } public Element element(QName qName) { return asElement(elementIndex().get(qName)); } public List elements(String name) { return asElementList(elementIndex().get(name)); } public List elements(QName qName) { return asElementList(elementIndex().get(qName)); } // Implementation methods // ------------------------------------------------------------------------- protected Element asElement(Object object) { if (object instanceof Element) { return (Element) object; } else if (object != null) { List list = (List) object; if (list.size() >= 1) { return (Element) list.get(0); } } return null; } protected List asElementList(Object object) { if (object instanceof Element) { return createSingleResultList(object); } else if (object != null) { List list = (List) object; BackedList answer = createResultList(); for (int i = 0, size = list.size(); i < size; i++) { answer.addLocal(list.get(i)); } return answer; } return createEmptyList(); } /** * DOCUMENT ME! * * @param object * DOCUMENT ME! * * @return DOCUMENT ME! * * @deprecated WILL BE REMOVED IN dom4j-1.6 !! */ protected Iterator asElementIterator(Object object) { return asElementList(object).iterator(); } // #### could we override the add(Element) remove(Element methods? protected void addNode(Node node) { super.addNode(node); if ((elementIndex != null) && node instanceof Element) { addToElementIndex((Element) node); } else if ((attributeIndex != null) && node instanceof Attribute) { addToAttributeIndex((Attribute) node); } } protected boolean removeNode(Node node) { if (super.removeNode(node)) { if ((elementIndex != null) && node instanceof Element) { removeFromElementIndex((Element) node); } else if ((attributeIndex != null) && node instanceof Attribute) { removeFromAttributeIndex((Attribute) node); } return true; } return false; } protected Map attributeIndex() { if (attributeIndex == null) { attributeIndex = createAttributeIndex(); for (Iterator iter = attributeIterator(); iter.hasNext();) { addToAttributeIndex((Attribute) iter.next()); } } return attributeIndex; } protected Map elementIndex() { if (elementIndex == null) { elementIndex = createElementIndex(); for (Iterator iter = elementIterator(); iter.hasNext();) { addToElementIndex((Element) iter.next()); } } return elementIndex; } /** * A Factory Method to create the index for attributes * * @return DOCUMENT ME! */ protected Map createAttributeIndex() { Map answer = createIndex(); return answer; } /** * A Factory Method to create the index for elements * * @return DOCUMENT ME! */ protected Map createElementIndex() { Map answer = createIndex(); return answer; } protected void addToElementIndex(Element element) { QName qName = element.getQName(); String name = qName.getName(); addToElementIndex(qName, element); addToElementIndex(name, element); } protected void addToElementIndex(Object key, Element value) { Object oldValue = elementIndex.get(key); if (oldValue == null) { elementIndex.put(key, value); } else { if (oldValue instanceof List) { List list = (List) oldValue; list.add(value); } else { List list = createList(); list.add(oldValue); list.add(value); elementIndex.put(key, list); } } } protected void removeFromElementIndex(Element element) { QName qName = element.getQName(); String name = qName.getName(); removeFromElementIndex(qName, element); removeFromElementIndex(name, element); } protected void removeFromElementIndex(Object key, Element value) { Object oldValue = elementIndex.get(key); if (oldValue instanceof List) { List list = (List) oldValue; list.remove(value); } else { elementIndex.remove(key); } } protected void addToAttributeIndex(Attribute attribute) { QName qName = attribute.getQName(); String name = qName.getName(); addToAttributeIndex(qName, attribute); addToAttributeIndex(name, attribute); } protected void addToAttributeIndex(Object key, Attribute value) { Object oldValue = attributeIndex.get(key); if (oldValue != null) { attributeIndex.put(key, value); } } protected void removeFromAttributeIndex(Attribute attribute) { QName qName = attribute.getQName(); String name = qName.getName(); removeFromAttributeIndex(qName, attribute); removeFromAttributeIndex(name, attribute); } protected void removeFromAttributeIndex(Object key, Attribute value) { Object oldValue = attributeIndex.get(key); if ((oldValue != null) && oldValue.equals(value)) { attributeIndex.remove(key); } } /** * Factory method to return a new map implementation for indices * * @return DOCUMENT ME! */ protected Map createIndex() { return new HashMap(); } /** * Factory method to return a list implementation for indices * * @return DOCUMENT ME! */ protected List createList() { return new ArrayList(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/util/SimpleSingleton.java0000644000175000017500000000706010242117776022346 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.util; /** *

* SimpleSingleton is an implementation of the SingletonStrategy * interface used to provide common factory access for the same object instance. * This implementation will create a new instance from the class specified and * will not create a new one unless it is reset. *

* * @author David Lucas * @version $Revision: 1.3 $ */ public class SimpleSingleton implements SingletonStrategy { private String singletonClassName = null; private Object singletonInstance = null; public SimpleSingleton() { } public Object instance() { return singletonInstance; } public void reset() { if (singletonClassName != null) { Class clazz = null; try { clazz = Thread.currentThread().getContextClassLoader().loadClass( singletonClassName); singletonInstance = clazz.newInstance(); } catch (Exception ignore) { try { clazz = Class.forName(singletonClassName); singletonInstance = clazz.newInstance(); } catch (Exception ignore2) { } } } } public void setSingletonClassName(String singletonClassName) { this.singletonClassName = singletonClassName; reset(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/util/AttributeHelper.java0000644000175000017500000000642110242120007022312 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.util; import org.dom4j.Attribute; import org.dom4j.Element; import org.dom4j.QName; /** *

* AttributeHelper a number of helper methods for working with * attribute values. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public class AttributeHelper { protected AttributeHelper() { } public static boolean booleanValue(Element element, String attributeName) { return booleanValue(element.attribute(attributeName)); } public static boolean booleanValue(Element element, QName attributeQName) { return booleanValue(element.attribute(attributeQName)); } protected static boolean booleanValue(Attribute attribute) { if (attribute == null) { return false; } Object value = attribute.getData(); if (value == null) { return false; } else if (value instanceof Boolean) { Boolean b = (Boolean) value; return b.booleanValue(); } else { return "true".equalsIgnoreCase(value.toString()); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/util/NonLazyElement.java0000644000175000017500000000632510242120011022111 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.util; import org.dom4j.Namespace; import org.dom4j.QName; import org.dom4j.tree.BaseElement; /** *

* NonLazyElement is the default DOM4J default implementation of * an XML element. *

* * @author James Strachan * @version $Revision: 1.8 $ */ public class NonLazyElement extends BaseElement { public NonLazyElement(String name) { super(name); this.attributes = createAttributeList(); this.content = createContentList(); } public NonLazyElement(QName qname) { super(qname); this.attributes = createAttributeList(); this.content = createContentList(); } public NonLazyElement(String name, Namespace namespace) { super(name, namespace); this.attributes = createAttributeList(); this.content = createContentList(); } public NonLazyElement(QName qname, int attributeCount) { super(qname); this.attributes = createAttributeList(attributeCount); this.content = createContentList(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/util/ProxyDocumentFactory.java0000644000175000017500000001564110242120011023356 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.util; import java.util.Map; import org.dom4j.Attribute; import org.dom4j.CDATA; import org.dom4j.Comment; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.DocumentType; import org.dom4j.Element; import org.dom4j.Entity; import org.dom4j.Namespace; import org.dom4j.NodeFilter; import org.dom4j.ProcessingInstruction; import org.dom4j.QName; import org.dom4j.Text; import org.dom4j.XPath; import org.dom4j.rule.Pattern; import org.jaxen.VariableContext; /** *

* ProxyDocumentFactory implements a proxy to a DocumentFactory * which is useful for implementation inheritence, allowing the pipelining of * various factory implementations. For example an EncodingDocumentFactory which * takes care of encoding strings outside of allowable XML ranges could be used * with a DatatypeDocumentFactory which is XML Schema Data Type aware. *

* * @author James Strachan * @version $Revision: 1.13 $ */ public abstract class ProxyDocumentFactory { private DocumentFactory proxy; public ProxyDocumentFactory() { // use default factory this.proxy = DocumentFactory.getInstance(); } public ProxyDocumentFactory(DocumentFactory proxy) { this.proxy = proxy; } // Factory methods // ------------------------------------------------------------------------- public Document createDocument() { return proxy.createDocument(); } public Document createDocument(Element rootElement) { return proxy.createDocument(rootElement); } public DocumentType createDocType(String name, String publicId, String systemId) { return proxy.createDocType(name, publicId, systemId); } public Element createElement(QName qname) { return proxy.createElement(qname); } public Element createElement(String name) { return proxy.createElement(name); } public Attribute createAttribute(Element owner, QName qname, String value) { return proxy.createAttribute(owner, qname, value); } public Attribute createAttribute(Element owner, String name, String value) { return proxy.createAttribute(owner, name, value); } public CDATA createCDATA(String text) { return proxy.createCDATA(text); } public Comment createComment(String text) { return proxy.createComment(text); } public Text createText(String text) { return proxy.createText(text); } public Entity createEntity(String name, String text) { return proxy.createEntity(name, text); } public Namespace createNamespace(String prefix, String uri) { return proxy.createNamespace(prefix, uri); } public ProcessingInstruction createProcessingInstruction(String target, String data) { return proxy.createProcessingInstruction(target, data); } public ProcessingInstruction createProcessingInstruction(String target, Map data) { return proxy.createProcessingInstruction(target, data); } public QName createQName(String localName, Namespace namespace) { return proxy.createQName(localName, namespace); } public QName createQName(String localName) { return proxy.createQName(localName); } public QName createQName(String name, String prefix, String uri) { return proxy.createQName(name, prefix, uri); } public QName createQName(String qualifiedName, String uri) { return proxy.createQName(qualifiedName, uri); } public XPath createXPath(String xpathExpression) { return proxy.createXPath(xpathExpression); } public XPath createXPath(String xpathExpression, VariableContext variableContext) { return proxy.createXPath(xpathExpression, variableContext); } public NodeFilter createXPathFilter(String xpathFilterExpression, VariableContext variableContext) { return proxy.createXPathFilter(xpathFilterExpression, variableContext); } public NodeFilter createXPathFilter(String xpathFilterExpression) { return proxy.createXPathFilter(xpathFilterExpression); } public Pattern createPattern(String xpathPattern) { return proxy.createPattern(xpathPattern); } // Implementation methods // ------------------------------------------------------------------------- protected DocumentFactory getProxy() { return proxy; } protected void setProxy(DocumentFactory proxy) { if (proxy == null) { // use default factory proxy = DocumentFactory.getInstance(); } this.proxy = proxy; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/util/PerThreadSingleton.java0000644000175000017500000001014210242120023022741 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.util; import java.lang.ref.WeakReference; /** *

* PerThreadSingleton is an implementation of the * SingletonStrategy used to provide common factory access to a single object * instance based on an implementation strategy for one object instance per * thread. This is useful in replace of the ThreadLocal usage. *

* * @author David Lucas * @version $Revision: 1.3 $ */ public class PerThreadSingleton implements SingletonStrategy { private String singletonClassName = null; private ThreadLocal perThreadCache = new ThreadLocal(); public PerThreadSingleton() { } public void reset() { perThreadCache = new ThreadLocal(); } public Object instance() { Object singletonInstancePerThread = null; // use weak reference to prevent cyclic reference during GC WeakReference ref = (WeakReference) perThreadCache.get(); // singletonInstancePerThread=perThreadCache.get(); // if (singletonInstancePerThread==null) { if (ref == null || ref.get() == null) { Class clazz = null; try { clazz = Thread.currentThread().getContextClassLoader().loadClass( singletonClassName); singletonInstancePerThread = clazz.newInstance(); } catch (Exception ignore) { try { clazz = Class.forName(singletonClassName); singletonInstancePerThread = clazz.newInstance(); } catch (Exception ignore2) { } } perThreadCache.set(new WeakReference(singletonInstancePerThread)); } else { singletonInstancePerThread = ref.get(); } return singletonInstancePerThread; } public void setSingletonClassName(String singletonClassName) { this.singletonClassName = singletonClassName; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/util/package.html0000644000175000017500000000017510242120005020623 0ustar ebourgebourg

A collection of utility classes for the dom4j API.

dom4j-1.6.1/src/java/org/dom4j/util/XMLErrorHandler.java0000644000175000017500000001326010242120013022153 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.util; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.QName; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; /** * XMLErrorHandler is a SAX {@link ErrorHandler}which turns the * SAX parsing errors into XML so that the output can be formatted using XSLT or * the errors can be included in a SOAP message. * * @author James Strachan * @version $Revision: 1.7 $ */ public class XMLErrorHandler implements ErrorHandler { protected static final QName ERROR_QNAME = QName.get("error"); protected static final QName FATALERROR_QNAME = QName.get("fatalError"); protected static final QName WARNING_QNAME = QName.get("warning"); /** Stores the errors that occur during a SAX parse */ private Element errors; /** QName used for error elements */ private QName errorQName = ERROR_QNAME; /** QName used for fatalerror elements */ private QName fatalErrorQName = FATALERROR_QNAME; /** QName used for warning elements */ private QName warningQName = WARNING_QNAME; public XMLErrorHandler() { this.errors = DocumentHelper.createElement("errors"); } public XMLErrorHandler(Element errors) { this.errors = errors; } public void error(SAXParseException e) { Element element = errors.addElement(errorQName); addException(element, e); } public void fatalError(SAXParseException e) { Element element = errors.addElement(fatalErrorQName); addException(element, e); } public void warning(SAXParseException e) { Element element = errors.addElement(warningQName); addException(element, e); } // Properties // ------------------------------------------------------------------------- public Element getErrors() { return errors; } public void setErrors(Element errors) { this.errors = errors; } // Allow the QNames used to create subelements to be changed public QName getErrorQName() { return errorQName; } public void setErrorQName(QName errorQName) { this.errorQName = errorQName; } public QName getFatalErrorQName() { return fatalErrorQName; } public void setFatalErrorQName(QName fatalErrorQName) { this.fatalErrorQName = fatalErrorQName; } public QName getWarningQName() { return warningQName; } public void setWarningQName(QName warningQName) { this.warningQName = warningQName; } // Implementation methods // ------------------------------------------------------------------------- /** * Adds the given parse exception information to the given element instance * * @param element * DOCUMENT ME! * @param e * DOCUMENT ME! */ protected void addException(Element element, SAXParseException e) { element.addAttribute("column", Integer.toString(e.getColumnNumber())); element.addAttribute("line", Integer.toString(e.getLineNumber())); String publicID = e.getPublicId(); if ((publicID != null) && (publicID.length() > 0)) { element.addAttribute("publicID", publicID); } String systemID = e.getSystemId(); if ((systemID != null) && (systemID.length() > 0)) { element.addAttribute("systemID", systemID); } element.addText(e.getMessage()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/ElementHandler.java0000644000175000017500000000612310242120006021117 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; /** *

* ElementHandler interface defines a handler of * Element objects. It is used primarily in event based * processing models such as for processing large XML documents as they are * being parsed rather than waiting until the whole document is parsed. *

* * @author James Strachan * @version $Revision: 1.8 $ */ public interface ElementHandler { /** * Called by an event based processor when an elements openning tag is * encountered. * * @param elementPath * is the current ElementPath to process */ void onStart(ElementPath elementPath); /** * Called by an event based processor when an elements closing tag is * encountered. * * @param elementPath * is the current ElementPath to process */ void onEnd(ElementPath elementPath); } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/Document.java0000644000175000017500000001431710242120000020004 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import java.util.Map; import org.xml.sax.EntityResolver; /** *

* Document defines an XML Document. *

* * @author James Strachan * @version $Revision: 1.14 $ */ public interface Document extends Branch { /** * Returns the root {@link Element}for this document. * * @return the root element for this document */ Element getRootElement(); /** * Sets the root element for this document * * @param rootElement * the new root element for this document */ void setRootElement(Element rootElement); /** * Adds a new Comment node with the given text to this * branch. * * @param comment * is the text for the Comment node. * * @return this Document instance. */ Document addComment(String comment); /** * Adds a processing instruction for the given target * * @param target * is the target of the processing instruction * @param text * is the textual data (key/value pairs) of the processing * instruction * * @return this Document instance. */ Document addProcessingInstruction(String target, String text); /** * Adds a processing instruction for the given target * * @param target * is the target of the processing instruction * @param data * is a Map of the key / value pairs of the processing * instruction * * @return this Document instance. */ Document addProcessingInstruction(String target, Map data); /** * Adds a DOCTYPE declaration to this document * * @param name * is the name of the root element * @param publicId * is the PUBLIC URI * @param systemId * is the SYSTEM URI * * @return this Document instance. */ Document addDocType(String name, String publicId, String systemId); /** * DOCUMENT ME! * * @return the DocumentType property */ DocumentType getDocType(); /** * Sets the DocumentType property * * @param docType * DOCUMENT ME! */ void setDocType(DocumentType docType); /** * DOCUMENT ME! * * @return the EntityResolver used to find resolve URIs such as for DTDs, or * XML Schema documents */ EntityResolver getEntityResolver(); /** * Sets the EntityResolver used to find resolve URIs such as for DTDs, or * XML Schema documents * * @param entityResolver * DOCUMENT ME! */ void setEntityResolver(EntityResolver entityResolver); /** * Return the encoding of this document, as part of the XML declaration This * is null when unspecified or when it is not known (such as * when the Document was created in memory) or when the implementation does * not support this operation. * *

* The way this encoding is retrieved also depends on the way the XML source * is parsed. For instance, if the SAXReader is used and if the underlying * XMLReader implementation support the * org.xml.sax.ext.Locator2 interface, the result returned by * this method is specified by the getEncoding() method of * that interface. *

* * @return The encoding of this document, as stated in the XML declaration, * or null if unknown. * * @since 1.5 */ String getXMLEncoding(); /** * Sets the encoding of this document as it will appear in the XML * declaration part of the document. * * @param encoding the encoding of the document * * @since 1.6 */ void setXMLEncoding(String encoding); } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/NodeFilter.java0000644000175000017500000000537510242120012020270 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; /** *

* NodeFilter defines the behavior for a filter or predicate * which acts on a DOM4J Node. Instances can be generated from an {@link * DocumentFactory}. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public interface NodeFilter { /** *

* matches returns true if the given node matches the filter * condition. *

* * @param node * DOCUMENT ME! * * @return true if this filter matches the given node */ boolean matches(Node node); } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/DocumentType.java0000644000175000017500000000757710242117777020713 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import java.util.List; /** *

* DocumentType defines an XML DOCTYPE declaration. *

* * @author James Strachan * @version $Revision: 1.10 $ */ public interface DocumentType extends Node { /** * This method is the equivalent to the {@link #getName}method. It is added * for clarity. * * @return the root element name for the document type. */ String getElementName(); /** * This method is the equivalent to the {@link #setName}method. It is added * for clarity. * * @param elementName * DOCUMENT ME! */ void setElementName(String elementName); String getPublicID(); void setPublicID(String publicID); String getSystemID(); void setSystemID(String systemID); /** * Returns a list of internal DTD declaration objects, defined in the * {@link org.dom4j.dtd}package * * @return DOCUMENT ME! */ List getInternalDeclarations(); /** * Sets the list of internal DTD declaration objects, defined in the * {@link org.dom4j.dtd}package * * @param declarations * DOCUMENT ME! */ void setInternalDeclarations(List declarations); /** * Returns a list of internal DTD declaration objects, defined in the * {@link org.dom4j.dtd}package * * @return DOCUMENT ME! */ List getExternalDeclarations(); /** * Sets the list of internal DTD declaration objects, defined in the * {@link org.dom4j.dtd}package * * @param declarations * DOCUMENT ME! */ void setExternalDeclarations(List declarations); } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/Text.java0000644000175000017500000000454310242120017017162 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; /** *

* Text defines an XML Text node. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public interface Text extends CharacterData { } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/Comment.java0000644000175000017500000000456710242120022017642 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; /** *

* Comment defines the behavior of an XML comment. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public interface Comment extends CharacterData { } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/dtd/0000755000175000017500000000000012133227266016157 5ustar ebourgebourgdom4j-1.6.1/src/java/org/dom4j/dtd/ExternalEntityDecl.java0000644000175000017500000001147510242120007022561 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dtd; /** *

* ExternalEntityDecl represents an external entity declaration * in a DTD. *

* * @author James Strachan * @version $Revision: 1.9 $ */ public class ExternalEntityDecl { /** Holds value of property name. */ private String name; /** Holds value of property publicID. */ private String publicID; /** Holds value of property systemID. */ private String systemID; public ExternalEntityDecl() { } public ExternalEntityDecl(String name, String publicID, String systemID) { this.name = name; this.publicID = publicID; this.systemID = systemID; } /** * Getter for property name. * * @return Value of property name. */ public String getName() { return name; } /** * Setter for property name. * * @param name * New value of property name. */ public void setName(String name) { this.name = name; } /** * Getter for property publicID. * * @return Value of property publicID. */ public String getPublicID() { return publicID; } /** * Setter for property publicID. * * @param publicID * New value of property publicID. */ public void setPublicID(String publicID) { this.publicID = publicID; } /** * Getter for property systemID. * * @return Value of property systemID. */ public String getSystemID() { return systemID; } /** * Setter for property systemID. * * @param systemID * New value of property systemID. */ public void setSystemID(String systemID) { this.systemID = systemID; } public String toString() { StringBuffer buffer = new StringBuffer(""); return buffer.toString(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/dtd/AttributeDecl.java0000644000175000017500000001364410242120012021541 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dtd; /** *

* AttributeDecl represents an attribute declaration in a DTD. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public class AttributeDecl { /** Holds value of property elementName. */ private String elementName; /** Holds value of property attributeName. */ private String attributeName; /** Holds value of property type. */ private String type; /** Holds value of property value. */ private String value; /** Holds value of property valueDefault. */ private String valueDefault; public AttributeDecl() { } public AttributeDecl(String elementName, String attributeName, String type, String valueDefault, String value) { this.elementName = elementName; this.attributeName = attributeName; this.type = type; this.value = value; this.valueDefault = valueDefault; } /** * Getter for property elementName. * * @return Value of property elementName. */ public String getElementName() { return elementName; } /** * Setter for property elementName. * * @param elementName * New value of property elementName. */ public void setElementName(String elementName) { this.elementName = elementName; } /** * Getter for property attributeName. * * @return Value of property attributeName. */ public String getAttributeName() { return attributeName; } /** * Setter for property attributeName. * * @param attributeName * New value of property attributeName. */ public void setAttributeName(String attributeName) { this.attributeName = attributeName; } /** * Getter for property type. * * @return Value of property type. */ public String getType() { return type; } /** * Setter for property type. * * @param type * New value of property type. */ public void setType(String type) { this.type = type; } /** * Getter for property value. * * @return Value of property value. */ public String getValue() { return value; } /** * Setter for property value. * * @param value * New value of property value. */ public void setValue(String value) { this.value = value; } /** * Getter for property valueDefault. * * @return Value of property valueDefault. */ public String getValueDefault() { return valueDefault; } /** * Setter for property valueDefault. * * @param valueDefault * New value of property valueDefault. */ public void setValueDefault(String valueDefault) { this.valueDefault = valueDefault; } public String toString() { StringBuffer buffer = new StringBuffer(""); return buffer.toString(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/dtd/InternalEntityDecl.java0000644000175000017500000001161610242117776022573 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dtd; /** *

* InternalEntityDecl represents an internal entity declaration * in a DTD. *

* * @author James Strachan * @version $Revision: 1.9 $ */ public class InternalEntityDecl { /** Holds value of property name. */ private String name; /** Holds value of property value. */ private String value; public InternalEntityDecl() { } public InternalEntityDecl(String name, String value) { this.name = name; this.value = value; } /** * Getter for property name. * * @return Value of property name. */ public String getName() { return name; } /** * Setter for property name. * * @param name * New value of property name. */ public void setName(String name) { this.name = name; } /** * Getter for property value. * * @return Value of property value. */ public String getValue() { return value; } /** * Setter for property value. * * @param value * New value of property value. */ public void setValue(String value) { this.value = value; } public String toString() { StringBuffer buffer = new StringBuffer(""); return buffer.toString(); } private String escapeEntityValue(String text) { StringBuffer result = new StringBuffer(); for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); switch (c) { case '<': result.append("&#60;"); break; case '>': result.append(">"); break; case '&': result.append("&#38;"); break; case '\'': result.append("'"); break; case '\"': result.append("""); break; default: if (c < 32) { result.append("&#" + (int) c + ";"); } else { result.append(c); } break; } } return result.toString(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/dtd/package.html0000644000175000017500000000026110242120014020415 0ustar ebourgebourg

Classes to represent the DTD declarations. They are used inside the {@link org.dom4j.DocumentType} interface.

dom4j-1.6.1/src/java/org/dom4j/dtd/ElementDecl.java0000644000175000017500000000674110242120011021166 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dtd; /** *

* AttributeDecl represents an element declaration in a DTD. *

* * @author James Strachan * @version $Revision: 1.6 $ */ public class ElementDecl { /** Holds value of property name. */ private String name; /** Holds value of property model. */ private String model; public ElementDecl() { } public ElementDecl(String name, String model) { this.name = name; this.model = model; } /** * Getter for property name. * * @return Value of property name. */ public String getName() { return name; } /** * Setter for property name. * * @param name * New value of property name. */ public void setName(String name) { this.name = name; } /** * Getter for property model. * * @return Value of property model. */ public String getModel() { return model; } /** * Setter for property model. * * @param model * New value of property model. */ public void setModel(String model) { this.model = model; } public String toString() { return ""; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/IllegalAddException.java0000644000175000017500000000571310242120006022075 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; /** *

* IllegalAddException is thrown when a node is added incorrectly * to an {@link Element} *

* * @version $Revision: 1.6 $ */ public class IllegalAddException extends IllegalArgumentException { public IllegalAddException(String reason) { super(reason); } public IllegalAddException(Element parent, Node node, String reason) { super("The node \"" + node.toString() + "\" could not be added to the element \"" + parent.getQualifiedName() + "\" because: " + reason); } public IllegalAddException(Branch parent, Node node, String reason) { super("The node \"" + node.toString() + "\" could not be added to the branch \"" + parent.getName() + "\" because: " + reason); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/DocumentFactory.java0000644000175000017500000003534610242120011021343 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.List; import java.util.Map; import org.dom4j.rule.Pattern; import org.dom4j.tree.AbstractDocument; import org.dom4j.tree.DefaultAttribute; import org.dom4j.tree.DefaultCDATA; import org.dom4j.tree.DefaultComment; import org.dom4j.tree.DefaultDocument; import org.dom4j.tree.DefaultDocumentType; import org.dom4j.tree.DefaultElement; import org.dom4j.tree.DefaultEntity; import org.dom4j.tree.DefaultProcessingInstruction; import org.dom4j.tree.DefaultText; import org.dom4j.tree.QNameCache; import org.dom4j.util.SimpleSingleton; import org.dom4j.util.SingletonStrategy; import org.dom4j.xpath.DefaultXPath; import org.dom4j.xpath.XPathPattern; import org.jaxen.VariableContext; /** *

* DocumentFactory is a collection of factory methods to allow * easy custom building of DOM4J trees. The default tree that is built uses a * doubly linked tree. *

* *

* The tree built allows full XPath expressions from anywhere on the tree. *

* * @author James Strachan */ public class DocumentFactory implements Serializable { private static SingletonStrategy singleton = null; protected transient QNameCache cache; /** Default namespace prefix -> URI mappings for XPath expressions to use */ private Map xpathNamespaceURIs; private static SingletonStrategy createSingleton() { SingletonStrategy result = null; String documentFactoryClassName; try { documentFactoryClassName = System.getProperty("org.dom4j.factory", "org.dom4j.DocumentFactory"); } catch (Exception e) { documentFactoryClassName = "org.dom4j.DocumentFactory"; } try { String singletonClass = System.getProperty( "org.dom4j.DocumentFactory.singleton.strategy", "org.dom4j.util.SimpleSingleton"); Class clazz = Class.forName(singletonClass); result = (SingletonStrategy) clazz.newInstance(); } catch (Exception e) { result = new SimpleSingleton(); } result.setSingletonClassName(documentFactoryClassName); return result; } public DocumentFactory() { init(); } /** *

* Access to singleton implementation of DocumentFactory which is used if no * DocumentFactory is specified when building using the standard builders. *

* * @return the default singleon instance */ public static synchronized DocumentFactory getInstance() { if (singleton == null) { singleton = createSingleton(); } return (DocumentFactory) singleton.instance(); } // Factory methods public Document createDocument() { DefaultDocument answer = new DefaultDocument(); answer.setDocumentFactory(this); return answer; } /** * DOCUMENT ME! * * @param encoding * DOCUMENT ME! * * @return DOCUMENT ME! * * @since 1.5 */ public Document createDocument(String encoding) { // to keep the DocumentFactory backwards compatible, we have to do this // in this not so nice way, since subclasses only need to extend the // createDocument() method. Document answer = createDocument(); if (answer instanceof AbstractDocument) { ((AbstractDocument) answer).setXMLEncoding(encoding); } return answer; } public Document createDocument(Element rootElement) { Document answer = createDocument(); answer.setRootElement(rootElement); return answer; } public DocumentType createDocType(String name, String publicId, String systemId) { return new DefaultDocumentType(name, publicId, systemId); } public Element createElement(QName qname) { return new DefaultElement(qname); } public Element createElement(String name) { return createElement(createQName(name)); } public Element createElement(String qualifiedName, String namespaceURI) { return createElement(createQName(qualifiedName, namespaceURI)); } public Attribute createAttribute(Element owner, QName qname, String value) { return new DefaultAttribute(qname, value); } public Attribute createAttribute(Element owner, String name, String value) { return createAttribute(owner, createQName(name), value); } public CDATA createCDATA(String text) { return new DefaultCDATA(text); } public Comment createComment(String text) { return new DefaultComment(text); } public Text createText(String text) { if (text == null) { String msg = "Adding text to an XML document must not be null"; throw new IllegalArgumentException(msg); } return new DefaultText(text); } public Entity createEntity(String name, String text) { return new DefaultEntity(name, text); } public Namespace createNamespace(String prefix, String uri) { return Namespace.get(prefix, uri); } public ProcessingInstruction createProcessingInstruction(String target, String data) { return new DefaultProcessingInstruction(target, data); } public ProcessingInstruction createProcessingInstruction(String target, Map data) { return new DefaultProcessingInstruction(target, data); } public QName createQName(String localName, Namespace namespace) { return cache.get(localName, namespace); } public QName createQName(String localName) { return cache.get(localName); } public QName createQName(String name, String prefix, String uri) { return cache.get(name, Namespace.get(prefix, uri)); } public QName createQName(String qualifiedName, String uri) { return cache.get(qualifiedName, uri); } /** *

* createXPath parses an XPath expression and creates a new * XPath XPath instance. *

* * @param xpathExpression * is the XPath expression to create * * @return a new XPath instance * * @throws InvalidXPathException * if the XPath expression is invalid */ public XPath createXPath(String xpathExpression) throws InvalidXPathException { DefaultXPath xpath = new DefaultXPath(xpathExpression); if (xpathNamespaceURIs != null) { xpath.setNamespaceURIs(xpathNamespaceURIs); } return xpath; } /** *

* createXPath parses an XPath expression and creates a new * XPath XPath instance. *

* * @param xpathExpression * is the XPath expression to create * @param variableContext * is the variable context to use when evaluating the XPath * * @return a new XPath instance */ public XPath createXPath(String xpathExpression, VariableContext variableContext) { XPath xpath = createXPath(xpathExpression); xpath.setVariableContext(variableContext); return xpath; } /** *

* createXPathFilter parses a NodeFilter from the given XPath * filter expression. XPath filter expressions occur within XPath * expressions such as self::node()[ filterExpression ] *

* * @param xpathFilterExpression * is the XPath filter expression to create * @param variableContext * is the variable context to use when evaluating the XPath * * @return a new NodeFilter instance */ public NodeFilter createXPathFilter(String xpathFilterExpression, VariableContext variableContext) { XPath answer = createXPath(xpathFilterExpression); // DefaultXPath answer = new DefaultXPath( xpathFilterExpression ); answer.setVariableContext(variableContext); return answer; } /** *

* createXPathFilter parses a NodeFilter from the given XPath * filter expression. XPath filter expressions occur within XPath * expressions such as self::node()[ filterExpression ] *

* * @param xpathFilterExpression * is the XPath filter expression to create * * @return a new NodeFilter instance */ public NodeFilter createXPathFilter(String xpathFilterExpression) { return createXPath(xpathFilterExpression); // return new DefaultXPath( xpathFilterExpression ); } /** *

* createPattern parses the given XPath expression to create * an XSLT style {@link Pattern}instance which can then be used in an XSLT * processing model. *

* * @param xpathPattern * is the XPath pattern expression to create * * @return a new Pattern instance */ public Pattern createPattern(String xpathPattern) { return new XPathPattern(xpathPattern); } // Properties // ------------------------------------------------------------------------- /** * Returns a list of all the QName instances currently used by this document * factory * * @return DOCUMENT ME! */ public List getQNames() { return cache.getQNames(); } /** * DOCUMENT ME! * * @return the Map of namespace URIs that will be used by by XPath * expressions to resolve namespace prefixes into namespace URIs. * The map is keyed by namespace prefix and the value is the * namespace URI. This value could well be null to indicate no * namespace URIs are being mapped. */ public Map getXPathNamespaceURIs() { return xpathNamespaceURIs; } /** * Sets the namespace URIs to be used by XPath expressions created by this * factory or by nodes associated with this factory. The keys are namespace * prefixes and the values are namespace URIs. * * @param namespaceURIs * DOCUMENT ME! */ public void setXPathNamespaceURIs(Map namespaceURIs) { this.xpathNamespaceURIs = namespaceURIs; } // Implementation methods // ------------------------------------------------------------------------- /** *

* createSingleton creates the singleton instance from the * given class name. *

* * @param className * is the name of the DocumentFactory class to use * * @return a new singleton instance. */ protected static DocumentFactory createSingleton(String className) { // let's try and class load an implementation? try { // I'll use the current class loader // that loaded me to avoid problems in J2EE and web apps Class theClass = Class.forName(className, true, DocumentFactory.class.getClassLoader()); return (DocumentFactory) theClass.newInstance(); } catch (Throwable e) { System.out.println("WARNING: Cannot load DocumentFactory: " + className); return new DocumentFactory(); } } /** * DOCUMENT ME! * * @param qname * DOCUMENT ME! * * @return the cached QName instance if there is one or adds the given qname * to the cache if not */ protected QName intern(QName qname) { return cache.intern(qname); } /** * Factory method to create the QNameCache. This method should be overloaded * if you wish to use your own derivation of QName. * * @return DOCUMENT ME! */ protected QNameCache createQNameCache() { return new QNameCache(this); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); init(); } protected void init() { cache = createQNameCache(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */dom4j-1.6.1/src/java/org/dom4j/datatype/0000755000175000017500000000000012133227266017217 5ustar ebourgebourgdom4j-1.6.1/src/java/org/dom4j/datatype/DatatypeElement.java0000644000175000017500000001536710242120010023135 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.datatype; import com.sun.msv.datatype.DatabindableDatatype; import com.sun.msv.datatype.SerializationContext; import com.sun.msv.datatype.xsd.XSDatatype; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.Node; import org.dom4j.QName; import org.dom4j.tree.DefaultElement; import org.relaxng.datatype.DatatypeException; import org.relaxng.datatype.ValidationContext; /** *

* DatatypeElement represents an Element which supports the XML Schema Data Types * specification. *

* * @author James Strachan * @version $Revision: 1.9 $ */ public class DatatypeElement extends DefaultElement implements SerializationContext, ValidationContext { /** The XSDatatype of the Attribute */ private XSDatatype datatype; /** The data (Object) value of the Attribute */ private Object data; public DatatypeElement(QName qname, XSDatatype datatype) { super(qname); this.datatype = datatype; } public DatatypeElement(QName qname, int attributeCount, XSDatatype type) { super(qname, attributeCount); this.datatype = type; } public String toString() { return getClass().getName() + hashCode() + " [Element: <" + getQualifiedName() + " attributes: " + attributeList() + " data: " + getData() + " />]"; } /** * Returns the MSV XSDatatype for this node * * @return DOCUMENT ME! */ public XSDatatype getXSDatatype() { return datatype; } // SerializationContext interface // ------------------------------------------------------------------------- public String getNamespacePrefix(String uri) { Namespace namespace = getNamespaceForURI(uri); return (namespace != null) ? namespace.getPrefix() : null; } // ValidationContext interface // ------------------------------------------------------------------------- public String getBaseUri() { // XXXX: could we use a Document for this? return null; } public boolean isNotation(String notationName) { // XXXX: no way to do this yet in dom4j so assume false return false; } public boolean isUnparsedEntity(String entityName) { // XXXX: no way to do this yet in dom4j so assume valid return true; } public String resolveNamespacePrefix(String prefix) { Namespace namespace = getNamespaceForPrefix(prefix); if (namespace != null) { return namespace.getURI(); } return null; } // Element interface // ------------------------------------------------------------------------- public Object getData() { if (data == null) { String text = getTextTrim(); if ((text != null) && (text.length() > 0)) { if (datatype instanceof DatabindableDatatype) { DatabindableDatatype bind = (DatabindableDatatype) datatype; data = bind.createJavaObject(text, this); } else { data = datatype.createValue(text, this); } } } return data; } public void setData(Object data) { String s = datatype.convertToLexicalValue(data, this); validate(s); this.data = data; setText(s); } public Element addText(String text) { validate(text); return super.addText(text); } public void setText(String text) { validate(text); super.setText(text); } // Implementation methods // ------------------------------------------------------------------------- /** * Override to force lazy recreation of data object * * @param node * DOCUMENT ME! */ protected void childAdded(Node node) { data = null; super.childAdded(node); } /** * Override to force lazy recreation of data object * * @param node * DOCUMENT ME! */ protected void childRemoved(Node node) { data = null; super.childRemoved(node); } protected void validate(String text) throws IllegalArgumentException { try { datatype.checkValid(text, this); } catch (DatatypeException e) { throw new IllegalArgumentException(e.getMessage()); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/datatype/InvalidSchemaException.java0000644000175000017500000000467410242120016024443 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.datatype; /** *

* InvalidSchemaException is thrown when an invalid XML Schema * document is used *

* * @version $Revision: 1.6 $ */ public class InvalidSchemaException extends IllegalArgumentException { public InvalidSchemaException(String reason) { super(reason); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/datatype/NamedTypeResolver.java0000644000175000017500000001132510242120016023454 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.datatype; import com.sun.msv.datatype.xsd.XSDatatype; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.QName; /** *

* NamedTypeResolver resolves named types for a given QName. *

* * @author Yuxin Ruan * @version $Revision: 1.8 $ */ class NamedTypeResolver { protected Map complexTypeMap = new HashMap(); protected Map simpleTypeMap = new HashMap(); protected Map typedElementMap = new HashMap(); protected Map elementFactoryMap = new HashMap(); protected DocumentFactory documentFactory; NamedTypeResolver(DocumentFactory documentFactory) { this.documentFactory = documentFactory; } void registerComplexType(QName type, DocumentFactory factory) { complexTypeMap.put(type, factory); } void registerSimpleType(QName type, XSDatatype datatype) { simpleTypeMap.put(type, datatype); } void registerTypedElement(Element element, QName type, DocumentFactory parentFactory) { typedElementMap.put(element, type); elementFactoryMap.put(element, parentFactory); } void resolveElementTypes() { Iterator iterator = typedElementMap.keySet().iterator(); while (iterator.hasNext()) { Element element = (Element) iterator.next(); QName elementQName = getQNameOfSchemaElement(element); QName type = (QName) typedElementMap.get(element); if (complexTypeMap.containsKey(type)) { DocumentFactory factory = (DocumentFactory) complexTypeMap .get(type); elementQName.setDocumentFactory(factory); } else if (simpleTypeMap.containsKey(type)) { XSDatatype datatype = (XSDatatype) simpleTypeMap.get(type); DocumentFactory factory = (DocumentFactory) elementFactoryMap .get(element); if (factory instanceof DatatypeElementFactory) { ((DatatypeElementFactory) factory) .setChildElementXSDatatype(elementQName, datatype); } } } } void resolveNamedTypes() { resolveElementTypes(); } private QName getQNameOfSchemaElement(Element element) { String name = element.attributeValue("name"); return getQName(name); } private QName getQName(String name) { return documentFactory.createQName(name); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/datatype/SchemaParser.java0000644000175000017500000005110610242120004022417 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.datatype; import com.sun.msv.datatype.xsd.DatatypeFactory; import com.sun.msv.datatype.xsd.TypeIncubator; import com.sun.msv.datatype.xsd.XSDatatype; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.QName; import org.dom4j.io.SAXReader; import org.dom4j.util.AttributeHelper; import org.relaxng.datatype.DatatypeException; import org.relaxng.datatype.ValidationContext; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; /** *

* SchemaParser reads an XML Schema Document. *

* * @author James Strachan * @author Yuxin Ruan * @version $Revision: 1.19 $ */ public class SchemaParser { private static final Namespace XSD_NAMESPACE = Namespace.get("xsd", "http://www.w3.org/2001/XMLSchema"); // Use QNames for the elements private static final QName XSD_ELEMENT = QName .get("element", XSD_NAMESPACE); private static final QName XSD_ATTRIBUTE = QName.get("attribute", XSD_NAMESPACE); private static final QName XSD_SIMPLETYPE = QName.get("simpleType", XSD_NAMESPACE); private static final QName XSD_COMPLEXTYPE = QName.get("complexType", XSD_NAMESPACE); private static final QName XSD_RESTRICTION = QName.get("restriction", XSD_NAMESPACE); private static final QName XSD_SEQUENCE = QName.get("sequence", XSD_NAMESPACE); private static final QName XSD_CHOICE = QName.get("choice", XSD_NAMESPACE); private static final QName XSD_ALL = QName.get("all", XSD_NAMESPACE); private static final QName XSD_INCLUDE = QName .get("include", XSD_NAMESPACE); /** Document factory used to register Element specific factories */ private DatatypeDocumentFactory documentFactory; /** * Cache of XSDatatype instances loaded or created during * this build */ private Map dataTypeCache = new HashMap(); /** NamedTypeResolver */ private NamedTypeResolver namedTypeResolver; /** target namespace */ private Namespace targetNamespace; public SchemaParser() { this(DatatypeDocumentFactory.singleton); } public SchemaParser(DatatypeDocumentFactory documentFactory) { this.documentFactory = documentFactory; this.namedTypeResolver = new NamedTypeResolver(documentFactory); } /** * Parses the given schema document * * @param schemaDocument * is the document of the XML Schema */ public void build(Document schemaDocument) { this.targetNamespace = null; internalBuild(schemaDocument); } public void build(Document schemaDocument, Namespace namespace) { this.targetNamespace = namespace; internalBuild(schemaDocument); } private synchronized void internalBuild(Document schemaDocument) { Element root = schemaDocument.getRootElement(); if (root != null) { // handle schema includes Iterator includeIter = root.elementIterator(XSD_INCLUDE); while (includeIter.hasNext()) { Element includeElement = (Element) includeIter.next(); String inclSchemaInstanceURI = includeElement .attributeValue("schemaLocation"); EntityResolver resolver = schemaDocument.getEntityResolver(); try { if (resolver == null) { String msg = "No EntityResolver available"; throw new InvalidSchemaException(msg); } InputSource inputSource = resolver.resolveEntity(null, inclSchemaInstanceURI); if (inputSource == null) { String msg = "Could not resolve the schema URI: " + inclSchemaInstanceURI; throw new InvalidSchemaException(msg); } SAXReader reader = new SAXReader(); Document inclSchemaDocument = reader.read(inputSource); build(inclSchemaDocument); } catch (Exception e) { System.out.println("Failed to load schema: " + inclSchemaInstanceURI); System.out.println("Caught: " + e); e.printStackTrace(); throw new InvalidSchemaException("Failed to load schema: " + inclSchemaInstanceURI); } } // handle elements Iterator iter = root.elementIterator(XSD_ELEMENT); while (iter.hasNext()) { onDatatypeElement((Element) iter.next(), documentFactory); } // handle named simple types iter = root.elementIterator(XSD_SIMPLETYPE); while (iter.hasNext()) { onNamedSchemaSimpleType((Element) iter.next()); } // hanlde named complex types iter = root.elementIterator(XSD_COMPLEXTYPE); while (iter.hasNext()) { onNamedSchemaComplexType((Element) iter.next()); } namedTypeResolver.resolveNamedTypes(); } } // Implementation methods // ------------------------------------------------------------------------- /** * processes an XML Schema <element> tag * * @param xsdElement * DOCUMENT ME! * @param parentFactory * DOCUMENT ME! */ private void onDatatypeElement(Element xsdElement, DocumentFactory parentFactory) { String name = xsdElement.attributeValue("name"); String type = xsdElement.attributeValue("type"); QName qname = getQName(name); DatatypeElementFactory factory = getDatatypeElementFactory(qname); if (type != null) { // register type with this element name XSDatatype dataType = getTypeByName(type); if (dataType != null) { factory.setChildElementXSDatatype(qname, dataType); } else { QName typeQName = getQName(type); namedTypeResolver.registerTypedElement(xsdElement, typeQName, parentFactory); } return; } // handle element types derrived from simpleTypes Element xsdSimpleType = xsdElement.element(XSD_SIMPLETYPE); if (xsdSimpleType != null) { XSDatatype dataType = loadXSDatatypeFromSimpleType(xsdSimpleType); if (dataType != null) { factory.setChildElementXSDatatype(qname, dataType); } } Element schemaComplexType = xsdElement.element(XSD_COMPLEXTYPE); if (schemaComplexType != null) { onSchemaComplexType(schemaComplexType, factory); } Iterator iter = xsdElement.elementIterator(XSD_ATTRIBUTE); if (iter.hasNext()) { do { onDatatypeAttribute(xsdElement, factory, (Element) iter .next()); } while (iter.hasNext()); } } /** * processes an named XML Schema <complexTypegt; tag * * @param schemaComplexType * DOCUMENT ME! */ private void onNamedSchemaComplexType(Element schemaComplexType) { Attribute nameAttr = schemaComplexType.attribute("name"); if (nameAttr == null) { return; } String name = nameAttr.getText(); QName qname = getQName(name); DatatypeElementFactory factory = getDatatypeElementFactory(qname); onSchemaComplexType(schemaComplexType, factory); namedTypeResolver.registerComplexType(qname, factory); } /** * processes an XML Schema <complexTypegt; tag * * @param schemaComplexType * DOCUMENT ME! * @param elementFactory * DOCUMENT ME! */ private void onSchemaComplexType(Element schemaComplexType, DatatypeElementFactory elementFactory) { Iterator iter = schemaComplexType.elementIterator(XSD_ATTRIBUTE); while (iter.hasNext()) { Element xsdAttribute = (Element) iter.next(); String name = xsdAttribute.attributeValue("name"); QName qname = getQName(name); XSDatatype dataType = dataTypeForXsdAttribute(xsdAttribute); if (dataType != null) { // register the XSDatatype for the given Attribute // #### should both these be done? // elementFactory.setChildElementXSDatatype( qname, dataType ); elementFactory.setAttributeXSDatatype(qname, dataType); } } // handle sequence definition Element schemaSequence = schemaComplexType.element(XSD_SEQUENCE); if (schemaSequence != null) { onChildElements(schemaSequence, elementFactory); } // handle choice definition Element schemaChoice = schemaComplexType.element(XSD_CHOICE); if (schemaChoice != null) { onChildElements(schemaChoice, elementFactory); } // handle all definition Element schemaAll = schemaComplexType.element(XSD_ALL); if (schemaAll != null) { onChildElements(schemaAll, elementFactory); } } private void onChildElements(Element element, DatatypeElementFactory fact) { Iterator iter = element.elementIterator(XSD_ELEMENT); while (iter.hasNext()) { Element xsdElement = (Element) iter.next(); onDatatypeElement(xsdElement, fact); } } /** * processes an XML Schema <attribute> tag * * @param xsdElement * DOCUMENT ME! * @param elementFactory * DOCUMENT ME! * @param xsdAttribute * DOCUMENT ME! */ private void onDatatypeAttribute(Element xsdElement, DatatypeElementFactory elementFactory, Element xsdAttribute) { String name = xsdAttribute.attributeValue("name"); QName qname = getQName(name); XSDatatype dataType = dataTypeForXsdAttribute(xsdAttribute); if (dataType != null) { // register the XSDatatype for the given Attribute elementFactory.setAttributeXSDatatype(qname, dataType); } else { String type = xsdAttribute.attributeValue("type"); System.out.println("Warning: Couldn't find XSDatatype for type: " + type + " attribute: " + name); } } /** * processes an XML Schema <attribute> tag * * @param xsdAttribute * DOCUMENT ME! * * @return DOCUMENT ME! * * @throws InvalidSchemaException * DOCUMENT ME! */ private XSDatatype dataTypeForXsdAttribute(Element xsdAttribute) { String type = xsdAttribute.attributeValue("type"); XSDatatype dataType = null; if (type != null) { dataType = getTypeByName(type); } else { // must parse the element Element xsdSimpleType = xsdAttribute.element(XSD_SIMPLETYPE); if (xsdSimpleType == null) { String name = xsdAttribute.attributeValue("name"); String msg = "The attribute: " + name + " has no type attribute and does not contain a " + " element"; throw new InvalidSchemaException(msg); } dataType = loadXSDatatypeFromSimpleType(xsdSimpleType); } return dataType; } /** * processes an named XML Schema <simpleTypegt; tag * * @param schemaSimpleType * DOCUMENT ME! */ private void onNamedSchemaSimpleType(Element schemaSimpleType) { Attribute nameAttr = schemaSimpleType.attribute("name"); if (nameAttr == null) { return; } String name = nameAttr.getText(); QName qname = getQName(name); XSDatatype datatype = loadXSDatatypeFromSimpleType(schemaSimpleType); namedTypeResolver.registerSimpleType(qname, datatype); } /** * Loads a XSDatatype object from a <simpleType> attribute schema * element * * @param xsdSimpleType * DOCUMENT ME! * * @return DOCUMENT ME! */ private XSDatatype loadXSDatatypeFromSimpleType(Element xsdSimpleType) { Element xsdRestriction = xsdSimpleType.element(XSD_RESTRICTION); if (xsdRestriction != null) { String base = xsdRestriction.attributeValue("base"); if (base != null) { XSDatatype baseType = getTypeByName(base); if (baseType == null) { onSchemaError("Invalid base type: " + base + " when trying to build restriction: " + xsdRestriction); } else { return deriveSimpleType(baseType, xsdRestriction); } } else { // simpleType and base are mutually exclusive and you // must have one within a tag Element xsdSubType = xsdSimpleType.element(XSD_SIMPLETYPE); if (xsdSubType == null) { String msg = "The simpleType element: " + xsdSimpleType + " must contain a base attribute or simpleType" + " element"; onSchemaError(msg); } else { return loadXSDatatypeFromSimpleType(xsdSubType); } } } else { onSchemaError("No . Could not create XSDatatype for" + " simpleType: " + xsdSimpleType); } return null; } /** * Derives a new type from a base type and a set of restrictions * * @param baseType * DOCUMENT ME! * @param xsdRestriction * DOCUMENT ME! * * @return DOCUMENT ME! */ private XSDatatype deriveSimpleType(XSDatatype baseType, Element xsdRestriction) { TypeIncubator incubator = new TypeIncubator(baseType); ValidationContext context = null; try { for (Iterator iter = xsdRestriction.elementIterator(); iter .hasNext();) { Element element = (Element) iter.next(); String name = element.getName(); String value = element.attributeValue("value"); boolean fixed = AttributeHelper.booleanValue(element, "fixed"); // add facet incubator.addFacet(name, value, fixed, context); } // derive a new type by those facets String newTypeName = null; return incubator.derive("", newTypeName); } catch (DatatypeException e) { onSchemaError("Invalid restriction: " + e.getMessage() + " when trying to build restriction: " + xsdRestriction); return null; } } /** * DOCUMENT ME! * * @param name * The name of the element * * @return the DatatypeElementFactory for the given element * QName, creating one if it does not already exist */ private DatatypeElementFactory getDatatypeElementFactory(QName name) { DatatypeElementFactory factory = documentFactory .getElementFactory(name); if (factory == null) { factory = new DatatypeElementFactory(name); name.setDocumentFactory(factory); } return factory; } private XSDatatype getTypeByName(String type) { XSDatatype dataType = (XSDatatype) dataTypeCache.get(type); if (dataType == null) { // first check to see if it is a built-in type // maybe a prefix is being used int idx = type.indexOf(':'); if (idx >= 0) { String localName = type.substring(idx + 1); try { dataType = DatatypeFactory.getTypeByName(localName); } catch (DatatypeException e) { } } if (dataType == null) { try { dataType = DatatypeFactory.getTypeByName(type); } catch (DatatypeException e) { } } if (dataType == null) { // it's no built-in type, maybe it's a type we defined ourself QName typeQName = getQName(type); dataType = (XSDatatype) namedTypeResolver.simpleTypeMap .get(typeQName); } if (dataType != null) { // store in cache for later dataTypeCache.put(type, dataType); } } return dataType; } private QName getQName(String name) { if (targetNamespace == null) { return documentFactory.createQName(name); } else { return documentFactory.createQName(name, targetNamespace); } } /** * Called when there is a problem with the schema and the builder cannot * handle the XML Schema Data Types correctly * * @param message * DOCUMENT ME! * * @throws InvalidSchemaException * DOCUMENT ME! */ private void onSchemaError(String message) { // Some users may wish to disable exception throwing // and instead use some kind of listener for errors and continue // System.out.println( "WARNING: " + message ); throw new InvalidSchemaException(message); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/datatype/DatatypeElementFactory.java0000644000175000017500000001335310242120012024460 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.datatype; import com.sun.msv.datatype.xsd.XSDatatype; import java.util.HashMap; import java.util.Map; import org.dom4j.Attribute; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.QName; /** *

* DatatypeElementFactory is a factory for a specific Element in * an XML Schema. *

* * @author James Strachan * @author Yuxin Ruan * @version $Revision: 1.9 $ */ public class DatatypeElementFactory extends DocumentFactory { private QName elementQName; /** * Cache of XSDatatype instances per Attribute * QName */ private Map attributeXSDatatypes = new HashMap(); /** * Cache of XSDatatype instances per child Element * QName */ private Map childrenXSDatatypes = new HashMap(); public DatatypeElementFactory(QName elementQName) { this.elementQName = elementQName; } /** * DOCUMENT ME! * * @return the QName this element factory is associated with */ public QName getQName() { return elementQName; } /** * DOCUMENT ME! * * @param attributeQName * DOCUMENT ME! * * @return the XSDatatype associated with the given Attribute * QName */ public XSDatatype getAttributeXSDatatype(QName attributeQName) { return (XSDatatype) attributeXSDatatypes.get(attributeQName); } /** * Registers the given XSDatatype for the given * <attribute> QNames * * @param attributeQName * DOCUMENT ME! * @param type * DOCUMENT ME! */ public void setAttributeXSDatatype(QName attributeQName, XSDatatype type) { attributeXSDatatypes.put(attributeQName, type); } /** * DOCUMENT ME! * * @param qname * DOCUMENT ME! * * @return the XSDatatype associated with the given child * Element QName */ public XSDatatype getChildElementXSDatatype(QName qname) { return (XSDatatype) childrenXSDatatypes.get(qname); } public void setChildElementXSDatatype(QName qname, XSDatatype dataType) { childrenXSDatatypes.put(qname, dataType); } // DocumentFactory methods // ------------------------------------------------------------------------- public Element createElement(QName qname) { // the element may have its own element factory! // use factory from the qname for datatype XSDatatype dataType = getChildElementXSDatatype(qname); if (dataType != null) { return new DatatypeElement(qname, dataType); } DocumentFactory factory = qname.getDocumentFactory(); if (factory instanceof DatatypeElementFactory) { DatatypeElementFactory dtFactory = (DatatypeElementFactory) factory; dataType = dtFactory.getChildElementXSDatatype(qname); if (dataType != null) { return new DatatypeElement(qname, dataType); } } return super.createElement(qname); } public Attribute createAttribute(Element owner, QName qname, String value) { XSDatatype dataType = getAttributeXSDatatype(qname); if (dataType == null) { return super.createAttribute(owner, qname, value); } else { return new DatatypeAttribute(qname, dataType, value); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/datatype/DatatypeAttribute.java0000644000175000017500000001645510242120006023513 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.datatype; import com.sun.msv.datatype.DatabindableDatatype; import com.sun.msv.datatype.SerializationContext; import com.sun.msv.datatype.xsd.XSDatatype; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.QName; import org.dom4j.tree.AbstractAttribute; import org.relaxng.datatype.DatatypeException; import org.relaxng.datatype.ValidationContext; /** *

* DatatypeAttribute represents an Attribute which supports the * XML Schema Data Types * specification. *

* * @author James Strachan * @version $Revision: 1.9 $ */ public class DatatypeAttribute extends AbstractAttribute implements SerializationContext, ValidationContext { /** The parent Element of the Attribute */ private Element parent; /** The QName for this element */ private QName qname; /** The XSDatatype of the Attribute */ private XSDatatype datatype; /** The data (Object) value of the Attribute */ private Object data; /** The text value of the Attribute */ private String text; public DatatypeAttribute(QName qname, XSDatatype datatype) { this.qname = qname; this.datatype = datatype; } public DatatypeAttribute(QName qname, XSDatatype datatype, String text) { this.qname = qname; this.datatype = datatype; this.text = text; this.data = convertToValue(text); } public String toString() { return getClass().getName() + hashCode() + " [Attribute: name " + getQualifiedName() + " value \"" + getValue() + "\" data: " + getData() + "]"; } /** * Returns the MSV XSDatatype for this node * * @return DOCUMENT ME! */ public XSDatatype getXSDatatype() { return datatype; } // SerializationContext interface // ------------------------------------------------------------------------- public String getNamespacePrefix(String uri) { Element parentElement = getParent(); if (parentElement != null) { Namespace namespace = parentElement.getNamespaceForURI(uri); if (namespace != null) { return namespace.getPrefix(); } } return null; } // ValidationContext interface // ------------------------------------------------------------------------- public String getBaseUri() { // XXXX: could we use a Document for this? return null; } public boolean isNotation(String notationName) { // XXXX: no way to do this yet in dom4j so assume false return false; } public boolean isUnparsedEntity(String entityName) { // XXXX: no way to do this yet in dom4j so assume valid return true; } public String resolveNamespacePrefix(String prefix) { // first lets see if this is our attribute's prefix if (prefix.equals(getNamespacePrefix())) { return getNamespaceURI(); } else { Element parentElement = getParent(); if (parentElement != null) { Namespace namespace = parentElement .getNamespaceForPrefix(prefix); if (namespace != null) { return namespace.getURI(); } } } return null; } // Attribute interface // ------------------------------------------------------------------------- public QName getQName() { return qname; } public String getValue() { return text; } public void setValue(String value) { validate(value); this.text = value; this.data = convertToValue(value); } public Object getData() { return data; } public void setData(Object data) { String s = datatype.convertToLexicalValue(data, this); validate(s); this.text = s; this.data = data; } public Element getParent() { return parent; } public void setParent(Element parent) { this.parent = parent; } public boolean supportsParent() { return true; } public boolean isReadOnly() { return false; } // Implementation methods // ------------------------------------------------------------------------- protected void validate(String txt) throws IllegalArgumentException { try { datatype.checkValid(txt, this); } catch (DatatypeException e) { throw new IllegalArgumentException(e.getMessage()); } } protected Object convertToValue(String txt) { if (datatype instanceof DatabindableDatatype) { DatabindableDatatype bindable = (DatabindableDatatype) datatype; return bindable.createJavaObject(txt, this); } else { return datatype.createValue(txt, this); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/datatype/DatatypeDocumentFactory.java0000644000175000017500000002063510242120021024646 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.datatype; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.QName; import org.dom4j.io.SAXReader; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; /** *

* DatatypeDocumentFactory is a factory of XML objects which * support the XML Schema Data Types * specification. *

* * @author James Strachan * @version $Revision: 1.9 $ */ public class DatatypeDocumentFactory extends DocumentFactory { // XXXX: I don't think interning of QNames is necessary private static final boolean DO_INTERN_QNAME = false; /** The Singleton instance */ protected static transient DatatypeDocumentFactory singleton = new DatatypeDocumentFactory(); private static final Namespace XSI_NAMESPACE = Namespace.get("xsi", "http://www.w3.org/2001/XMLSchema-instance"); private static final QName XSI_SCHEMA_LOCATION = QName.get( "schemaLocation", XSI_NAMESPACE); private static final QName XSI_NO_SCHEMA_LOCATION = QName.get( "noNamespaceSchemaLocation", XSI_NAMESPACE); /** The builder of XML Schemas */ private SchemaParser schemaBuilder; /** reader of XML Schemas */ private SAXReader xmlSchemaReader = new SAXReader(); /** If schemas are automatically loaded when parsing instance documents */ private boolean autoLoadSchema = true; public DatatypeDocumentFactory() { schemaBuilder = new SchemaParser(this); } /** *

* Access to the singleton instance of this factory. *

* * @return the default singleon instance */ public static DocumentFactory getInstance() { return singleton; } /** * Loads the given XML Schema document into this factory so schema-aware * Document, Elements and Attributes will be created by this factory. * * @param schemaDocument * is an XML Schema Document instance. */ public void loadSchema(Document schemaDocument) { schemaBuilder.build(schemaDocument); } public void loadSchema(Document schemaDocument, Namespace targetNamespace) { schemaBuilder.build(schemaDocument, targetNamespace); } /** * Registers the given DatatypeElementFactory for the given * <element> schema element * * @param elementQName * DOCUMENT ME! * * @return DOCUMENT ME! */ public DatatypeElementFactory getElementFactory(QName elementQName) { DatatypeElementFactory result = null; if (DO_INTERN_QNAME) { elementQName = intern(elementQName); } DocumentFactory factory = elementQName.getDocumentFactory(); if (factory instanceof DatatypeElementFactory) { result = (DatatypeElementFactory) factory; } return result; } // DocumentFactory methods // ------------------------------------------------------------------------- public Attribute createAttribute(Element owner, QName qname, String value) { if (autoLoadSchema && qname.equals(XSI_NO_SCHEMA_LOCATION)) { Document document = (owner != null) ? owner.getDocument() : null; loadSchema(document, value); } else if (autoLoadSchema && qname.equals(XSI_SCHEMA_LOCATION)) { Document document = (owner != null) ? owner.getDocument() : null; String uri = value.substring(0, value.indexOf(' ')); Namespace namespace = owner.getNamespaceForURI(uri); loadSchema(document, value.substring(value.indexOf(' ') + 1), namespace); } return super.createAttribute(owner, qname, value); } // Implementation methods // ------------------------------------------------------------------------- protected void loadSchema(Document document, String schemaInstanceURI) { try { EntityResolver resolver = document.getEntityResolver(); if (resolver == null) { String msg = "No EntityResolver available for resolving URI: "; throw new InvalidSchemaException(msg + schemaInstanceURI); } InputSource inputSource = resolver.resolveEntity(null, schemaInstanceURI); if (resolver == null) { throw new InvalidSchemaException("Could not resolve the URI: " + schemaInstanceURI); } Document schemaDocument = xmlSchemaReader.read(inputSource); loadSchema(schemaDocument); } catch (Exception e) { System.out.println("Failed to load schema: " + schemaInstanceURI); System.out.println("Caught: " + e); e.printStackTrace(); throw new InvalidSchemaException("Failed to load schema: " + schemaInstanceURI); } } protected void loadSchema(Document document, String schemaInstanceURI, Namespace namespace) { try { EntityResolver resolver = document.getEntityResolver(); if (resolver == null) { String msg = "No EntityResolver available for resolving URI: "; throw new InvalidSchemaException(msg + schemaInstanceURI); } InputSource inputSource = resolver.resolveEntity(null, schemaInstanceURI); if (resolver == null) { throw new InvalidSchemaException("Could not resolve the URI: " + schemaInstanceURI); } Document schemaDocument = xmlSchemaReader.read(inputSource); loadSchema(schemaDocument, namespace); } catch (Exception e) { System.out.println("Failed to load schema: " + schemaInstanceURI); System.out.println("Caught: " + e); e.printStackTrace(); throw new InvalidSchemaException("Failed to load schema: " + schemaInstanceURI); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/datatype/package.html0000644000175000017500000000033310242120014021455 0ustar ebourgebourg

An implementation of the dom4j API which supports the XML Schema Data Types specification.

dom4j-1.6.1/src/java/org/dom4j/DocumentHelper.java0000644000175000017500000003340310242120001021142 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import java.io.StringReader; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.dom4j.io.SAXReader; import org.dom4j.rule.Pattern; import org.jaxen.VariableContext; import org.xml.sax.InputSource; /** *

* DocumentHelper is a collection of helper methods for using * DOM4J. *

* * @author James Strachan * @version $Revision: 1.26 $ */ public final class DocumentHelper { private DocumentHelper() { } private static DocumentFactory getDocumentFactory() { return DocumentFactory.getInstance(); } // Static helper methods public static Document createDocument() { return getDocumentFactory().createDocument(); } public static Document createDocument(Element rootElement) { return getDocumentFactory().createDocument(rootElement); } public static Element createElement(QName qname) { return getDocumentFactory().createElement(qname); } public static Element createElement(String name) { return getDocumentFactory().createElement(name); } public static Attribute createAttribute(Element owner, QName qname, String value) { return getDocumentFactory().createAttribute(owner, qname, value); } public static Attribute createAttribute(Element owner, String name, String value) { return getDocumentFactory().createAttribute(owner, name, value); } public static CDATA createCDATA(String text) { return DocumentFactory.getInstance().createCDATA(text); } public static Comment createComment(String text) { return DocumentFactory.getInstance().createComment(text); } public static Text createText(String text) { return DocumentFactory.getInstance().createText(text); } public static Entity createEntity(String name, String text) { return DocumentFactory.getInstance().createEntity(name, text); } public static Namespace createNamespace(String prefix, String uri) { return DocumentFactory.getInstance().createNamespace(prefix, uri); } public static ProcessingInstruction createProcessingInstruction(String pi, String d) { return getDocumentFactory().createProcessingInstruction(pi, d); } public static ProcessingInstruction createProcessingInstruction(String pi, Map data) { return getDocumentFactory().createProcessingInstruction(pi, data); } public static QName createQName(String localName, Namespace namespace) { return getDocumentFactory().createQName(localName, namespace); } public static QName createQName(String localName) { return getDocumentFactory().createQName(localName); } /** *

* createXPath parses an XPath expression and creates a new * XPath XPath instance using the singleton {@link * DocumentFactory}. *

* * @param xpathExpression * is the XPath expression to create * * @return a new XPath instance * * @throws InvalidXPathException * if the XPath expression is invalid */ public static XPath createXPath(String xpathExpression) throws InvalidXPathException { return getDocumentFactory().createXPath(xpathExpression); } /** *

* createXPath parses an XPath expression and creates a new * XPath XPath instance using the singleton {@link * DocumentFactory}. *

* * @param xpathExpression * is the XPath expression to create * @param context * is the variable context to use when evaluating the XPath * * @return a new XPath instance * * @throws InvalidXPathException * if the XPath expression is invalid */ public static XPath createXPath(String xpathExpression, VariableContext context) throws InvalidXPathException { return getDocumentFactory().createXPath(xpathExpression, context); } /** *

* createXPathFilter parses a NodeFilter from the given XPath * filter expression using the singleton {@link DocumentFactory}. XPath * filter expressions occur within XPath expressions such as * self::node()[ filterExpression ] *

* * @param xpathFilterExpression * is the XPath filter expression to create * * @return a new NodeFilter instance */ public static NodeFilter createXPathFilter(String xpathFilterExpression) { return getDocumentFactory().createXPathFilter(xpathFilterExpression); } /** *

* createPattern parses the given XPath expression to create * an XSLT style {@link Pattern}instance which can then be used in an XSLT * processing model. *

* * @param xpathPattern * is the XPath pattern expression to create * * @return a new Pattern instance */ public static Pattern createPattern(String xpathPattern) { return getDocumentFactory().createPattern(xpathPattern); } /** *

* selectNodes performs the given XPath expression on the * {@link List}of {@link Node}instances appending all the results together * into a single list. *

* * @param xpathFilterExpression * is the XPath filter expression to evaluate * @param nodes * is the list of nodes on which to evalute the XPath * * @return the results of all the XPath evaluations as a single list */ public static List selectNodes(String xpathFilterExpression, List nodes) { XPath xpath = createXPath(xpathFilterExpression); return xpath.selectNodes(nodes); } /** *

* selectNodes performs the given XPath expression on the * {@link List}of {@link Node}instances appending all the results together * into a single list. *

* * @param xpathFilterExpression * is the XPath filter expression to evaluate * @param node * is the Node on which to evalute the XPath * * @return the results of all the XPath evaluations as a single list */ public static List selectNodes(String xpathFilterExpression, Node node) { XPath xpath = createXPath(xpathFilterExpression); return xpath.selectNodes(node); } /** *

* sort sorts the given List of Nodes using an XPath * expression as a {@link java.util.Comparator}. *

* * @param list * is the list of Nodes to sort * @param xpathExpression * is the XPath expression used for comparison */ public static void sort(List list, String xpathExpression) { XPath xpath = createXPath(xpathExpression); xpath.sort(list); } /** *

* sort sorts the given List of Nodes using an XPath * expression as a {@link java.util.Comparator}and optionally removing * duplicates. *

* * @param list * is the list of Nodes to sort * @param expression * is the XPath expression used for comparison * @param distinct * if true then duplicate values (using the sortXPath for * comparisions) will be removed from the List */ public static void sort(List list, String expression, boolean distinct) { XPath xpath = createXPath(expression); xpath.sort(list, distinct); } /** *

* parseText parses the given text as an XML document and * returns the newly created Document. *

* * @param text * the XML text to be parsed * * @return a newly parsed Document * * @throws DocumentException * if the document could not be parsed */ public static Document parseText(String text) throws DocumentException { Document result = null; SAXReader reader = new SAXReader(); String encoding = getEncoding(text); InputSource source = new InputSource(new StringReader(text)); source.setEncoding(encoding); result = reader.read(source); // if the XML parser doesn't provide a way to retrieve the encoding, // specify it manually if (result.getXMLEncoding() == null) { result.setXMLEncoding(encoding); } return result; } private static String getEncoding(String text) { String result = null; String xml = text.trim(); if (xml.startsWith(""); String sub = xml.substring(0, end); StringTokenizer tokens = new StringTokenizer(sub, " =\"\'"); while (tokens.hasMoreTokens()) { String token = tokens.nextToken(); if ("encoding".equals(token)) { if (tokens.hasMoreTokens()) { result = tokens.nextToken(); } break; } } } return result; } /** *

* makeElement *

* a helper method which navigates from the given Document or Element node * to some Element using the path expression, creating any necessary * elements along the way. For example the path a/b/c would * get the first child <a> element, which would be created if it did * not exist, then the next child <b> and so on until finally a * <c> element is returned. * * @param source * is the Element or Document to start navigating from * @param path * is a simple path expression, seperated by '/' which denotes * the path from the source to the resulting element such as * a/b/c * * @return the first Element on the given path which either already existed * on the path or were created by this method. */ public static Element makeElement(Branch source, String path) { StringTokenizer tokens = new StringTokenizer(path, "/"); Element parent; if (source instanceof Document) { Document document = (Document) source; parent = document.getRootElement(); // lets throw a NoSuchElementException // if we are given an empty path String name = tokens.nextToken(); if (parent == null) { parent = document.addElement(name); } } else { parent = (Element) source; } Element element = null; while (tokens.hasMoreTokens()) { String name = tokens.nextToken(); if (name.indexOf(':') > 0) { element = parent.element(parent.getQName(name)); } else { element = parent.element(name); } if (element == null) { element = parent.addElement(name); } parent = element; } return element; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/DocumentException.java0000644000175000017500000001021010242120023021654 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import java.io.PrintStream; import java.io.PrintWriter; /** *

* DocumentException is a nested Exception which may be thrown * during the processing of a DOM4J document. *

* * @author James Strachan * @version $Revision: 1.7 $ */ public class DocumentException extends Exception { /** A wrapped Throwable */ private Throwable nestedException; public DocumentException() { super("Error occurred in DOM4J application."); } public DocumentException(String message) { super(message); } public DocumentException(Throwable nestedException) { super(nestedException.getMessage()); this.nestedException = nestedException; } public DocumentException(String message, Throwable nestedException) { super(message); this.nestedException = nestedException; } public Throwable getNestedException() { return nestedException; } public String getMessage() { if (nestedException != null) { return super.getMessage() + " Nested exception: " + nestedException.getMessage(); } else { return super.getMessage(); } } public void printStackTrace() { super.printStackTrace(); if (nestedException != null) { System.err.print("Nested exception: "); nestedException.printStackTrace(); } } public void printStackTrace(PrintStream out) { super.printStackTrace(out); if (nestedException != null) { out.println("Nested exception: "); nestedException.printStackTrace(out); } } public void printStackTrace(PrintWriter writer) { super.printStackTrace(writer); if (nestedException != null) { writer.println("Nested exception: "); nestedException.printStackTrace(writer); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/package.html0000644000175000017500000000024510242120017017647 0ustar ebourgebourg

Defines the XML Document Object Model in Java interfaces together with some helper classes.

dom4j-1.6.1/src/java/org/dom4j/xpath/0000755000175000017500000000000012133227266016530 5ustar ebourgebourgdom4j-1.6.1/src/java/org/dom4j/xpath/DefaultXPath.java0000644000175000017500000002747210242120007021720 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import java.io.Serializable; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import org.dom4j.InvalidXPathException; import org.dom4j.Node; import org.dom4j.NodeFilter; import org.dom4j.XPathException; import org.jaxen.FunctionContext; import org.jaxen.JaxenException; import org.jaxen.NamespaceContext; import org.jaxen.SimpleNamespaceContext; import org.jaxen.VariableContext; import org.jaxen.XPath; import org.jaxen.dom4j.Dom4jXPath; /** *

* Default implementation of {@link org.dom4j.XPath}which uses the Jaxen project. *

* * @author bob mcwhirter * @author James Strachan */ public class DefaultXPath implements org.dom4j.XPath, NodeFilter, Serializable { private String text; private XPath xpath; private NamespaceContext namespaceContext; /** * Construct an XPath * * @param text * DOCUMENT ME! * * @throws InvalidXPathException * DOCUMENT ME! */ public DefaultXPath(String text) throws InvalidXPathException { this.text = text; this.xpath = parse(text); } public String toString() { return "[XPath: " + xpath + "]"; } // XPath interface /** * Retrieve the textual XPath string used to initialize this Object * * @return The XPath string */ public String getText() { return text; } public FunctionContext getFunctionContext() { return xpath.getFunctionContext(); } public void setFunctionContext(FunctionContext functionContext) { xpath.setFunctionContext(functionContext); } public NamespaceContext getNamespaceContext() { return namespaceContext; } public void setNamespaceURIs(Map map) { setNamespaceContext(new SimpleNamespaceContext(map)); } public void setNamespaceContext(NamespaceContext namespaceContext) { this.namespaceContext = namespaceContext; xpath.setNamespaceContext(namespaceContext); } public VariableContext getVariableContext() { return xpath.getVariableContext(); } public void setVariableContext(VariableContext variableContext) { xpath.setVariableContext(variableContext); } public Object evaluate(Object context) { try { setNSContext(context); List answer = xpath.selectNodes(context); if ((answer != null) && (answer.size() == 1)) { return answer.get(0); } return answer; } catch (JaxenException e) { handleJaxenException(e); return null; } } public Object selectObject(Object context) { return evaluate(context); } public List selectNodes(Object context) { try { setNSContext(context); return xpath.selectNodes(context); } catch (JaxenException e) { handleJaxenException(e); return Collections.EMPTY_LIST; } } public List selectNodes(Object context, org.dom4j.XPath sortXPath) { List answer = selectNodes(context); sortXPath.sort(answer); return answer; } public List selectNodes(Object context, org.dom4j.XPath sortXPath, boolean distinct) { List answer = selectNodes(context); sortXPath.sort(answer, distinct); return answer; } public Node selectSingleNode(Object context) { try { setNSContext(context); Object answer = xpath.selectSingleNode(context); if (answer instanceof Node) { return (Node) answer; } if (answer == null) { return null; } throw new XPathException("The result of the XPath expression is " + "not a Node. It was: " + answer + " of type: " + answer.getClass().getName()); } catch (JaxenException e) { handleJaxenException(e); return null; } } public String valueOf(Object context) { try { setNSContext(context); return xpath.stringValueOf(context); } catch (JaxenException e) { handleJaxenException(e); return ""; } } public Number numberValueOf(Object context) { try { setNSContext(context); return xpath.numberValueOf(context); } catch (JaxenException e) { handleJaxenException(e); return null; } } public boolean booleanValueOf(Object context) { try { setNSContext(context); return xpath.booleanValueOf(context); } catch (JaxenException e) { handleJaxenException(e); return false; } } /** *

* sort sorts the given List of Nodes using this XPath * expression as a {@link Comparator}. *

* * @param list * is the list of Nodes to sort */ public void sort(List list) { sort(list, false); } /** *

* sort sorts the given List of Nodes using this XPath * expression as a {@link Comparator}and optionally removing duplicates. *

* * @param list * is the list of Nodes to sort * @param distinct * if true then duplicate values (using the sortXPath for * comparisions) will be removed from the List */ public void sort(List list, boolean distinct) { if ((list != null) && !list.isEmpty()) { int size = list.size(); HashMap sortValues = new HashMap(size); for (int i = 0; i < size; i++) { Object object = list.get(i); if (object instanceof Node) { Node node = (Node) object; Object expression = getCompareValue(node); sortValues.put(node, expression); } } sort(list, sortValues); if (distinct) { removeDuplicates(list, sortValues); } } } public boolean matches(Node node) { try { setNSContext(node); List answer = xpath.selectNodes(node); if ((answer != null) && (answer.size() > 0)) { Object item = answer.get(0); if (item instanceof Boolean) { return ((Boolean) item).booleanValue(); } return answer.contains(node); } return false; } catch (JaxenException e) { handleJaxenException(e); return false; } } /** * Sorts the list based on the sortValues for each node * * @param list * DOCUMENT ME! * @param sortValues * DOCUMENT ME! */ protected void sort(List list, final Map sortValues) { Collections.sort(list, new Comparator() { public int compare(Object o1, Object o2) { o1 = sortValues.get(o1); o2 = sortValues.get(o2); if (o1 == o2) { return 0; } else if (o1 instanceof Comparable) { Comparable c1 = (Comparable) o1; return c1.compareTo(o2); } else if (o1 == null) { return 1; } else if (o2 == null) { return -1; } else { return o1.equals(o2) ? 0 : (-1); } } }); } // Implementation methods /** * Removes items from the list which have duplicate values * * @param list * DOCUMENT ME! * @param sortValues * DOCUMENT ME! */ protected void removeDuplicates(List list, Map sortValues) { // remove distinct HashSet distinctValues = new HashSet(); for (Iterator iter = list.iterator(); iter.hasNext();) { Object node = iter.next(); Object value = sortValues.get(node); if (distinctValues.contains(value)) { iter.remove(); } else { distinctValues.add(value); } } } /** * DOCUMENT ME! * * @param node * DOCUMENT ME! * * @return the node expression used for sorting comparisons */ protected Object getCompareValue(Node node) { return valueOf(node); } protected static XPath parse(String text) { try { return new Dom4jXPath(text); } catch (JaxenException e) { throw new InvalidXPathException(text, e.getMessage()); } catch (Throwable t) { throw new InvalidXPathException(text, t); } } protected void setNSContext(Object context) { if (namespaceContext == null) { xpath.setNamespaceContext(DefaultNamespaceContext.create(context)); } } protected void handleJaxenException(JaxenException exception) throws XPathException { throw new XPathException(text, exception); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/xpath/DefaultNamespaceContext.java0000644000175000017500000000724310242120011024122 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import java.io.Serializable; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.Node; import org.jaxen.NamespaceContext; /** *

* DefaultNamespaceContext implements a Jaxen NamespaceContext * such that a context node is used to determine the current XPath namespace * prefixes and namespace URIs available. *

* * @author James Strachan */ public class DefaultNamespaceContext implements NamespaceContext, Serializable { private final Element element; public DefaultNamespaceContext(Element element) { this.element = element; } public static DefaultNamespaceContext create(Object node) { Element element = null; if (node instanceof Element) { element = (Element) node; } else if (node instanceof Document) { Document doc = (Document) node; element = doc.getRootElement(); } else if (node instanceof Node) { element = ((Node) node).getParent(); } if (element != null) { return new DefaultNamespaceContext(element); } return null; } public String translateNamespacePrefixToUri(String prefix) { if ((prefix != null) && (prefix.length() > 0)) { Namespace ns = element.getNamespaceForPrefix(prefix); if (ns != null) { return ns.getURI(); } } return null; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/xpath/XPathPattern.java0000644000175000017500000001263110242120022021735 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import java.util.ArrayList; import org.dom4j.InvalidXPathException; import org.dom4j.Node; import org.dom4j.XPathException; import org.jaxen.Context; import org.jaxen.ContextSupport; import org.jaxen.JaxenException; import org.jaxen.SimpleNamespaceContext; import org.jaxen.SimpleVariableContext; import org.jaxen.VariableContext; import org.jaxen.XPathFunctionContext; import org.jaxen.dom4j.DocumentNavigator; import org.jaxen.pattern.Pattern; import org.jaxen.pattern.PatternParser; import org.jaxen.saxpath.SAXPathException; /** *

* XPathPattern is an implementation of Pattern which uses an * XPath xpath. *

* * @author James Strachan * @version $Revision: 1.18.2.1 $ */ public class XPathPattern implements org.dom4j.rule.Pattern { private String text; private Pattern pattern; private Context context; public XPathPattern(Pattern pattern) { this.pattern = pattern; this.text = pattern.getText(); this.context = new Context(getContextSupport()); } public XPathPattern(String text) { this.text = text; this.context = new Context(getContextSupport()); try { this.pattern = PatternParser.parse(text); } catch (SAXPathException e) { throw new InvalidXPathException(text, e.getMessage()); } catch (Throwable t) { throw new InvalidXPathException(text, t); } } public boolean matches(Node node) { try { ArrayList list = new ArrayList(1); list.add(node); context.setNodeSet(list); return pattern.matches(node, context); } catch (JaxenException e) { handleJaxenException(e); return false; } } public String getText() { return text; } public double getPriority() { return pattern.getPriority(); } public org.dom4j.rule.Pattern[] getUnionPatterns() { Pattern[] patterns = pattern.getUnionPatterns(); if (patterns != null) { int size = patterns.length; XPathPattern[] answer = new XPathPattern[size]; for (int i = 0; i < size; i++) { answer[i] = new XPathPattern(patterns[i]); } return answer; } return null; } public short getMatchType() { return pattern.getMatchType(); } public String getMatchesNodeName() { return pattern.getMatchesNodeName(); } public void setVariableContext(VariableContext variableContext) { context.getContextSupport().setVariableContext(variableContext); } public String toString() { return "[XPathPattern: text: " + text + " Pattern: " + pattern + "]"; } protected ContextSupport getContextSupport() { return new ContextSupport(new SimpleNamespaceContext(), XPathFunctionContext.getInstance(), new SimpleVariableContext(), DocumentNavigator.getInstance()); } protected void handleJaxenException(JaxenException exception) throws XPathException { throw new XPathException(text, exception); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/java/org/dom4j/xpath/overview.html0000644000175000017500000000033010242120020021233 0ustar ebourgebourg

This XPath implementation attempts to be a fully-compliant implementation of the W3C XPath specification.

dom4j-1.6.1/src/java/org/dom4j/xpath/package.html0000644000175000017500000000025510242120013020770 0ustar ebourgebourg org.dom4j.xpath :: package.html

Provides the core tools needed to use the XPath library

dom4j-1.6.1/src/samples/0000755000175000017500000000000010242117775014325 5ustar ebourgebourgdom4j-1.6.1/src/samples/org/0000755000175000017500000000000010242117775015114 5ustar ebourgebourgdom4j-1.6.1/src/samples/org/dom4j/0000755000175000017500000000000010242117775016131 5ustar ebourgebourgdom4j-1.6.1/src/samples/org/dom4j/samples/0000755000175000017500000000000012133227266017573 5ustar ebourgebourgdom4j-1.6.1/src/samples/org/dom4j/samples/XPathDemo.java0000644000175000017500000000707510242120017022261 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: XPathDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import java.util.Iterator; import java.util.List; import org.dom4j.Document; /** * A sample program to demonstrate the use of XPath expressions. * * @author James Strachan * @version $Revision: 1.4 $ */ public class XPathDemo extends SAXDemo { protected String xpath = "*"; public static void main(String[] args) { run(new XPathDemo(), args); } public XPathDemo() { } public void run(String[] args) throws Exception { if (args.length < 2) { printUsage(" "); return; } String xmlFile = args[0]; xpath = args[1]; writer = createXMLWriter(); Document document = parse(xmlFile); process(document); } protected void process(Document document) throws Exception { println("Evaluating XPath: " + xpath); List list = document.selectNodes(xpath); println("Found: " + list.size() + " node(s)"); println("Results:"); for (Iterator iter = list.iterator(); iter.hasNext();) { Object object = iter.next(); writer.write(object); writer.println(); } writer.flush(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: XPathDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/bean/0000755000175000017500000000000012133227266020500 5ustar ebourgebourgdom4j-1.6.1/src/samples/org/dom4j/samples/bean/BeanDemo.java0000644000175000017500000001042210242120023022772 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: BeanDemo.java,v 1.4 2005/01/29 14:52:58 maartenc Exp $ */ package org.dom4j.samples.bean; import org.dom4j.samples.SAXDemo; import java.awt.Component; import java.util.Iterator; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.bean.BeanDocumentFactory; import org.dom4j.io.SAXReader; /** * A simple test program to demonstrate using simple binding of JavaBeans to * inside a DOM4J tree * * @author James Strachan * @version $Revision: 1.4 $ */ public class BeanDemo extends SAXDemo { public static void main(String[] args) { run(new BeanDemo(), args); } public BeanDemo() { } public void run(String[] args) throws Exception { if (args.length < 1) { printUsage(""); return; } Document document = parse(args[0]); process(document); } protected Document parse(String url) throws Exception { SAXReader reader = new SAXReader(BeanDocumentFactory.getInstance()); return reader.read(url); } protected void process(Document document) throws Exception { // find all of the windows List windows = document.selectNodes("//window"); for (Iterator iter = windows.iterator(); iter.hasNext();) { Element element = (Element) iter.next(); Object window = element.getData(); if (window instanceof Component) { Component component = (Component) window; component.setVisible(true); } println("found element: " + element); println("found window: " + window); } println(""); println("Now lets find all the fonts..."); List fonts = document.selectNodes("//@font"); for (Iterator iter = fonts.iterator(); iter.hasNext();) { Attribute font = (Attribute) iter.next(); println("found font: " + font.getData()); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: BeanDemo.java,v 1.4 2005/01/29 14:52:58 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/CountDemo.java0000644000175000017500000001041710242120015022315 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: CountDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import org.dom4j.Attribute; import org.dom4j.Comment; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.ProcessingInstruction; import org.dom4j.Text; import org.dom4j.Visitor; import org.dom4j.VisitorSupport; /** * A sample program to count the number of various kinds of DOM4J node types * * @author James Strachan * @version $Revision: 1.4 $ */ public class CountDemo extends SAXDemo { private int numCharacters; private int numComments; private int numElements; private int numAttributes; private int numProcessingInstructions; public static void main(String[] args) { run(new CountDemo(), args); } public CountDemo() { } protected void process(Document document) throws Exception { numCharacters = 0; numComments = 0; numElements = 0; numAttributes = 0; numProcessingInstructions = 0; Visitor visitor = new VisitorSupport() { public void visit(Element node) { ++numElements; } public void visit(Attribute node) { ++numAttributes; } public void visit(Comment node) { ++numComments; } public void visit(ProcessingInstruction node) { ++numProcessingInstructions; } public void visit(Text node) { String text = node.getText(); if (text != null) { numCharacters += text.length(); } } }; println("Document: " + document.getName() + " has the following"); println("Elements\tAttributes\tComments\tPIs\tCharacters"); document.accept(visitor); println(numElements + "\t\t" + numAttributes + "\t\t" + numComments + "\t\t" + numProcessingInstructions + "\t" + numCharacters); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: CountDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/SAXDemo.java0000644000175000017500000000552410242120016021664 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: SAXDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import org.dom4j.Document; import org.dom4j.io.SAXReader; /** * A simple test program to demonstrate using SAX to create a DOM4J tree * * @author James Strachan * @version $Revision: 1.4 $ */ public class SAXDemo extends AbstractDemo { public static void main(String[] args) { run(new SAXDemo(), args); } public SAXDemo() { } protected Document parse(String xmlFile) throws Exception { SAXReader reader = new SAXReader(); return reader.read(xmlFile); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: SAXDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/PullParserDemo.java0000644000175000017500000000561510242120003023317 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: PullParserDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import org.dom4j.Document; import org.dom4j.io.XPPReader; /** * A sample program that demonstrates using the XML Pull Parser to create a * dom4j Document * * @author James Strachan * @version $Revision: 1.4 $ */ public class PullParserDemo extends AbstractDemo { public static void main(String[] args) { run(new PullParserDemo(), args); } public PullParserDemo() { } protected Document parse(String xmlFile) throws Exception { XPPReader reader = new XPPReader(); return reader.read(xmlFile); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: PullParserDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/DatatypeDemo.java0000644000175000017500000000612110242120004022773 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: DatatypeDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import org.dom4j.Document; import org.dom4j.datatype.DatatypeDocumentFactory; import org.dom4j.io.SAXReader; /** * A simple test program to demonstrate using XML Schema Data Types * * @author James Strachan * @version $Revision: 1.4 $ */ public class DatatypeDemo extends AbstractDemo { public static void main(String[] args) { run(new DatatypeDemo(), args); } public DatatypeDemo() { } protected Document parse(String xmlFile) throws Exception { SAXReader reader = new SAXReader(); reader.setDocumentFactory(DatatypeDocumentFactory.getInstance()); return reader.read(xmlFile); } protected void process(Document document) throws Exception { getXMLWriter().write(document); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: DatatypeDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/XPathGrep.java0000644000175000017500000001075110242120007022264 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: XPathGrep.java,v 1.5 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.XPath; /** * A utility program which performs XPath expressions on one or more XML files * and outputs the matches. It is similar to the grep command on * Unix but uses XPath expressions for matching * * @author James Strachan * @version $Revision: 1.5 $ */ public class XPathGrep extends SAXDemo { protected XPath xpath; protected boolean verbose; public static void main(String[] args) { run(new XPathGrep(), args); } public XPathGrep() { } public void run(String[] args) throws Exception { if (args.length < 2) { printUsage("{options} "); return; } for (int i = 0, size = args.length; i < size; i++) { String arg = args[i]; if (arg.startsWith("-")) { readOptions(arg); } else { if (xpath == null) { setXPath(arg); } else { Document document = parse(arg); process(document); } } } } public void setXPath(String xpathExpression) { xpath = DocumentHelper.createXPath(xpathExpression); } protected void process(Document document) throws Exception { // perform XPath if (verbose) { println("About to evalute: " + xpath); println("Results:"); } Object object = xpath.evaluate(document); if (object instanceof List) { List list = (List) object; for (Iterator iter = list.iterator(); iter.hasNext();) { getXMLWriter().write(iter.next()); getXMLWriter().println(); } getXMLWriter().flush(); } else { println((object != null) ? object.toString() : "null"); } } protected void readOptions(String arg) { if (arg.indexOf('v') >= 0) { verbose = true; } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: XPathGrep.java,v 1.5 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/VisitorDemo.java0000644000175000017500000001035510242120020022661 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: VisitorDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import org.dom4j.Attribute; import org.dom4j.CDATA; import org.dom4j.Comment; import org.dom4j.Document; import org.dom4j.DocumentType; import org.dom4j.Element; import org.dom4j.Entity; import org.dom4j.Namespace; import org.dom4j.ProcessingInstruction; import org.dom4j.Text; import org.dom4j.Visitor; import org.dom4j.VisitorSupport; /** * A sample program to demonstrate the use of the Visitor Pattern in DOM4J * * @author James Strachan * @version $Revision: 1.4 $ */ public class VisitorDemo extends SAXDemo { public static void main(String[] args) { run(new VisitorDemo(), args); } public VisitorDemo() { } protected void process(Document document) throws Exception { Visitor visitor = new VisitorSupport() { public void visit(Document document) { println(document.toString()); } public void visit(DocumentType documentType) { println(documentType.toString()); } public void visit(Element node) { println(node.toString()); } public void visit(Attribute node) { println(node.toString()); } public void visit(CDATA node) { println(node.toString()); } public void visit(Comment node) { println(node.toString()); } public void visit(Entity node) { println(node.toString()); } public void visit(Namespace node) { println(node.toString()); } public void visit(ProcessingInstruction node) { println(node.toString()); } public void visit(Text node) { println(node.toString()); } }; document.accept(visitor); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: VisitorDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/swing/0000755000175000017500000000000012133227266020722 5ustar ebourgebourgdom4j-1.6.1/src/samples/org/dom4j/samples/swing/JTableTool.java0000644000175000017500000001066610242120007023555 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: JTableTool.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ package org.dom4j.samples.swing; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import org.dom4j.Document; import org.dom4j.io.SAXReader; import org.dom4j.swing.XMLTableModel; /** * Displays an XML document in a JTable JTable GUI from a dom4j Document. The * definition of the table is given using an XML descriptor document such as in * xml/swing/. * * @author James Strachan * @version $Revision: 1.4 $ */ public class JTableTool { public static void main(String[] args) throws Exception { JTableTool sample = new JTableTool(); sample.run(args); } public void run(String[] args) throws Exception { if (args.length <= 1) { System.out.println("Usage: "); System.out.println(); System.out .println("This program displays a document in a Swing JTable given a table description"); System.out.println(); System.out .println("For example running this program as follows will display the servlets of a web.xml"); System.out .println(" java swing.JTableTool xml/swing/tableForWeb.xml xml/web.xml"); System.out .println("This example will display the periodic table in a JTable"); System.out .println(" java swing.JTableTool xml/swing/tableForAtoms.xml xml/periodic_table.xml"); return; } // parse document SAXReader reader = new SAXReader(); Document definition = reader.read(args[0]); Document document = reader.read(args[1]); // build table model XMLTableModel model = new XMLTableModel(definition, document); // make the widgets JTable table = new JTable(model); JFrame frame = new JFrame("JTableTool: " + document.getName()); frame.setSize(300, 300); frame.setLocation(100, 100); frame.getContentPane().add(new JScrollPane(table)); frame.validate(); frame.setVisible(true); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: JTableTool.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/swing/JTreeDemo.java0000644000175000017500000000653310242120021023366 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: JTreeDemo.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ package org.dom4j.samples.swing; import org.dom4j.samples.SAXDemo; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTree; import org.dom4j.Document; import org.dom4j.swing.DocumentTreeModel; /** * A sample program to build a JTree GUI from a dom4j Document * * @author James Strachan * @author Jakob Jenkov * @version $Revision: 1.4 $ */ public class JTreeDemo extends SAXDemo { public static void main(String[] args) { run(new JTreeDemo(), args); } public JTreeDemo() { } /** Create a Swing GUI containing the document */ protected void process(Document document) throws Exception { DocumentTreeModel treeModel = new DocumentTreeModel(document); JTree tree = new JTree(treeModel); JFrame frame = new JFrame("JTreeDemo: " + document.getName()); frame.setSize(300, 300); frame.setLocation(100, 100); frame.getContentPane().add(new JScrollPane(tree)); frame.validate(); frame.setVisible(true); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: JTreeDemo.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/swing/JTableDemo.java0000644000175000017500000001007010242117776023534 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: JTableDemo.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ package org.dom4j.samples.swing; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import org.dom4j.Document; import org.dom4j.io.SAXReader; import org.dom4j.swing.XMLTableDefinition; import org.dom4j.swing.XMLTableModel; /** * A sample program to build a JTable GUI from a dom4j Document * * @author James Strachan * @version $Revision: 1.4 $ */ public class JTableDemo { public static void main(String[] args) throws Exception { JTableDemo sample = new JTableDemo(); sample.run(args); } public void run(String[] args) throws Exception { if (args.length <= 0) { System.out .println("This program displays a web.xml document in a Swing JTable"); System.out.println("Usage: "); return; } // parse document SAXReader reader = new SAXReader(); Document document = reader.read(args[0]); // build table model XMLTableDefinition definition = new XMLTableDefinition(); definition.setRowExpression("/web-app/servlet"); definition.addStringColumn("Name", "servlet-name"); definition.addStringColumn("Class", "servlet-class"); definition.addStringColumn("Mapping", "../servlet-mapping[servlet-name=$Name]"); XMLTableModel model = new XMLTableModel(definition, document); // make the widgets JTable table = new JTable(model); JFrame frame = new JFrame("JTableDemo: " + document.getName()); frame.setSize(300, 300); frame.setLocation(100, 100); frame.getContentPane().add(new JScrollPane(table)); frame.validate(); frame.setVisible(true); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: JTableDemo.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/jaxp/0000755000175000017500000000000012133227266020535 5ustar ebourgebourgdom4j-1.6.1/src/samples/org/dom4j/samples/jaxp/WriterDemo.java0000644000175000017500000000722110242120024023442 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: WriterDemo.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ package org.dom4j.samples.jaxp; import org.dom4j.samples.SAXDemo; import java.io.StringWriter; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import org.dom4j.Document; import org.dom4j.io.DocumentSource; /** * A sample program which uses JAXP to write a dom4j Document to a Stream. * * @author James Strachan * @version $Revision: 1.4 $ */ public class WriterDemo extends SAXDemo { public static void main(String[] args) { run(new WriterDemo(), args); } public WriterDemo() { } /** Outputs the document using JAXP */ protected void process(Document document) throws Exception { // load the transformer TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); // now lets create the TrAX source and result // objects and do the transformation Source source = new DocumentSource(document); StringWriter buffer = new StringWriter(); StreamResult result = new StreamResult(buffer); transformer.transform(source, result); String text = buffer.toString(); System.out.println("The document is:- "); System.out.println(text); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: WriterDemo.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/jaxp/PrettyPrintDemo.java0000644000175000017500000000760110242120017024476 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: PrettyPrintDemo.java,v 1.4 2005/01/29 14:52:58 maartenc Exp $ */ package org.dom4j.samples.jaxp; import org.dom4j.samples.SAXDemo; import java.io.StringWriter; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import org.dom4j.Document; import org.dom4j.io.DocumentSource; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLResult; /** * A sample program which uses JAXP to write a dom4j Document to a stream using * dom4j's pretty printing output format. * * @author James Strachan * @version $Revision: 1.4 $ */ public class PrettyPrintDemo extends SAXDemo { public static void main(String[] args) { run(new PrettyPrintDemo(), args); } public PrettyPrintDemo() { } /** Outputs the document using JAXP */ protected void process(Document document) throws Exception { // load a default transformer TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); // use dom4j document as the source Source source = new DocumentSource(document); // use pretty print format and a buffer for the result OutputFormat format = OutputFormat.createPrettyPrint(); StringWriter buffer = new StringWriter(); Result result = new XMLResult(buffer, format); // now lets transform transformer.transform(source, result); String text = buffer.toString(); System.out.println("The document is:- "); System.out.println(text); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: PrettyPrintDemo.java,v 1.4 2005/01/29 14:52:58 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/jaxp/RoundTripDemo.java0000644000175000017500000001135210242120013024112 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: RoundTripDemo.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ package org.dom4j.samples.jaxp; import org.dom4j.samples.SAXDemo; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.dom4j.Document; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; import org.dom4j.io.XMLWriter; /** * A program demonstrating a round trip from XML to dom4j to text to dom4j again * using JAXP to convert the XML. * * @author James Strachan * @version $Revision: 1.4 $ */ public class RoundTripDemo extends SAXDemo { public static void main(String[] args) { run(new RoundTripDemo(), args); } public RoundTripDemo() { } protected void outputDocument(Document document, Writer out) { try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); StreamResult result = new StreamResult(out); DocumentSource source = new DocumentSource(document); transformer.transform(source, result); } catch (Exception ex) { ex.printStackTrace(); } } protected Document parseDocument(Reader in) { try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); DocumentResult result = new DocumentResult(); StreamSource source = new StreamSource(in); transformer.transform(source, result); return result.getDocument(); } catch (Exception ex) { ex.printStackTrace(); return null; } } /** Outputs the document to a buffer, parse it back again then output it */ protected void process(Document document) throws Exception { System.out.println("about to output: " + document); StringWriter out = new StringWriter(); outputDocument(document, out); Document doc2 = parseDocument(new StringReader(out.toString())); System.out.println("parsed back again: " + doc2); System.out.println("Writing it out..."); XMLWriter writer = new XMLWriter(System.out); writer.write(doc2); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: RoundTripDemo.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/sax/0000755000175000017500000000000012133227266020366 5ustar ebourgebourgdom4j-1.6.1/src/samples/org/dom4j/samples/sax/FilterDemo.java0000644000175000017500000000571310242120005023247 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: FilterDemo.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ package org.dom4j.samples.sax; import org.dom4j.samples.SAXDemo; import org.dom4j.Document; import org.dom4j.io.SAXReader; /** * A sample program which demonstrates how to use a SAX XMLFilter when parsing * an XML document. * * @author James Strachan * @version $Revision: 1.4 $ */ public class FilterDemo extends SAXDemo { public static void main(String[] args) { run(new FilterDemo(), args); } public FilterDemo() { } protected Document parse(String xmlFile) throws Exception { SAXReader reader = new SAXReader(); reader.setXMLFilter(new TrimXMLFilter()); return reader.read(xmlFile); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: FilterDemo.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/sax/TrimXMLFilter.java0000644000175000017500000000631210242120006023654 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: TrimXMLFilter.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ package org.dom4j.samples.sax; import org.xml.sax.SAXException; import org.xml.sax.helpers.XMLFilterImpl; /** * An example XMLFilter which trims all text content, removing whitespace * * @author James Strachan * @version $Revision: 1.4 $ */ public class TrimXMLFilter extends XMLFilterImpl { public TrimXMLFilter() { } public void characters(char[] ch, int start, int length) throws SAXException { int last = start + length; while (start < last && Character.isWhitespace(ch[start])) { start++; length--; } while (length > 0 && Character.isWhitespace(ch[start + length - 1])) { length--; } if (length > 0) { super.characters(ch, start, length); } } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: TrimXMLFilter.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/jaxb/0000755000175000017500000000000012133227266020517 5ustar ebourgebourgdom4j-1.6.1/src/samples/org/dom4j/samples/jaxb/PurchaseOrderHandler.java0000644000175000017500000000564110242120025025414 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: PurchaseOrderHandler.java,v 1.3 2005/01/29 14:52:58 maartenc Exp $ */ package org.dom4j.samples.jaxb; import java.text.SimpleDateFormat; import javax.xml.bind.Element; import org.dom4j.jaxb.JAXBObjectHandler; import org.dom4j.test.primer.PurchaseOrder; /** * @author Wonne Keysers (Realsoftware.be) */ public class PurchaseOrderHandler implements JAXBObjectHandler { public void handleObject(Element jaxbElement) throws Exception { PurchaseOrder order = (PurchaseOrder) jaxbElement; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); System.out.println("Order - id:" + order.getId() + ", date:" + format.format(order.getOrderDate().getTime())); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: PurchaseOrderHandler.java,v 1.3 2005/01/29 14:52:58 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/jaxb/PurchaseOrderDateModifier.java0000644000175000017500000000562110242120020026364 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: PurchaseOrderDateModifier.java,v 1.2 2005/01/29 14:52:58 maartenc Exp $ */ package org.dom4j.samples.jaxb; import java.util.Calendar; import javax.xml.bind.Element; import org.dom4j.jaxb.JAXBObjectModifier; import org.dom4j.test.primer.PurchaseOrder; /** * @author Wonne Keysers (Realsoftware.be) */ public class PurchaseOrderDateModifier implements JAXBObjectModifier { public Element modifyObject(Element jaxbElement) throws Exception { PurchaseOrder order = (PurchaseOrder) jaxbElement; Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); order.setOrderDate(calendar); return order; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: PurchaseOrderDateModifier.java,v 1.2 2005/01/29 14:52:58 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/jaxb/JAXBDemo.java0000644000175000017500000002253710242120013022701 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: JAXBDemo.java,v 1.3 2005/01/29 14:52:58 maartenc Exp $ */ package org.dom4j.samples.jaxb; import java.io.File; import java.math.BigDecimal; import java.util.Calendar; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.jaxb.JAXBModifier; import org.dom4j.jaxb.JAXBReader; import org.dom4j.jaxb.JAXBWriter; import org.dom4j.test.primer.Items; import org.dom4j.test.primer.ObjectFactory; import org.dom4j.test.primer.PurchaseOrder; import org.dom4j.test.primer.PurchaseOrders; import org.dom4j.test.primer.USAddress; /** * JAXB demo * * @author Wonne Keysers (Realsoftware.be) */ public class JAXBDemo { private File outputDir = new File("build/test/"); public static void main(String[] args) { JAXBDemo demo = new JAXBDemo(); demo.init(); demo.demoRead(); demo.demoReadPrune(); demo.demoWrite(); demo.demoModify(); demo.demoModifyWrite(); } public void init() { outputDir.mkdirs(); } public void demoRead() { try { File inputFile = new File("xml/jaxb/primer.xml"); JAXBReader jaxbReader = new JAXBReader("org.dom4j.test.primer"); System.out .println("Fetched PurchaseOrders using JAXBObjectHandler:"); jaxbReader.addObjectHandler("/purchaseOrders/purchaseOrder", new PurchaseOrderHandler()); Document doc = jaxbReader.read(inputFile); System.out.println("Fetched PurchaseOrders using DOM4J document:"); Iterator orderIt = doc.selectNodes("/purchaseOrders/purchaseOrder") .iterator(); while (orderIt.hasNext()) { Element elem = (Element) orderIt.next(); System.out.println("Order - id:" + elem.attributeValue("id") + ", date:" + elem.attributeValue("orderDate")); } System.out.println("Document:"); System.out.println(doc.asXML()); System.out.println(); } catch (Exception e) { e.printStackTrace(); } } public void demoReadPrune() { try { File inputFile = new File("xml/jaxb/primer.xml"); JAXBReader jaxbReader = new JAXBReader("org.dom4j.test.primer"); System.out .println("Fetched PurchaseOrders using JAXBObjectHandler:"); jaxbReader.setPruneElements(true); jaxbReader.addObjectHandler("/purchaseOrders/purchaseOrder", new PurchaseOrderHandler()); Document doc = jaxbReader.read(inputFile); System.out.println("Pruned document:"); System.out.println(doc.asXML()); System.out.println(); } catch (Exception e) { e.printStackTrace(); } } public void demoWrite() { try { ObjectFactory factory = new ObjectFactory(); PurchaseOrders orders = factory.createPurchaseOrders(); // Order 1 PurchaseOrder order = factory.createPurchaseOrder(); USAddress billTo = factory.createUSAddress(); billTo.setCity("Cambridge"); billTo.setCountry("US"); billTo.setName("Robert Smith"); billTo.setState("MA"); billTo.setStreet("8 Oak Avenue"); billTo.setZip(new BigDecimal(12345)); order.setBillTo(billTo); USAddress shipTo = factory.createUSAddress(); shipTo.setCity("Cambridge"); shipTo.setCountry("US"); shipTo.setName("Alice Smith"); shipTo.setState("MA"); shipTo.setStreet("123 Maple Street"); shipTo.setZip(new BigDecimal(12345)); order.setShipTo(shipTo); Calendar orderDate = Calendar.getInstance(); orderDate.set(2004, 06, 30); order.setOrderDate(orderDate); Items items = factory.createItems(); order.setItems(items); orders.getPurchaseOrder().add(order); // Order 2 PurchaseOrder order2 = factory.createPurchaseOrder(); USAddress billTo2 = factory.createUSAddress(); billTo2.setCity("Cambridge"); billTo2.setCountry("US"); billTo2.setName("Robert Smith"); billTo2.setState("MA"); billTo2.setStreet("8 Oak Avenue"); billTo2.setZip(new BigDecimal(12345)); order2.setBillTo(billTo2); USAddress shipTo2 = factory.createUSAddress(); shipTo2.setCity("Cambridge"); shipTo2.setCountry("US"); shipTo2.setName("Alice Smith"); shipTo2.setState("MA"); shipTo2.setStreet("123 Maple Street"); shipTo2.setZip(new BigDecimal(12345)); order2.setShipTo(shipTo2); Calendar orderDate2 = Calendar.getInstance(); orderDate2.set(2004, 06, 30); order2.setOrderDate(orderDate2); Items items2 = factory.createItems(); order2.setItems(items2); orders.getPurchaseOrder().add(order2); File outputFile = new File(outputDir, "jaxbWrite.xml"); JAXBWriter jaxbWriter = new JAXBWriter("org.dom4j.test.primer", OutputFormat.createPrettyPrint()); jaxbWriter.setOutput(outputFile); jaxbWriter.startDocument(); jaxbWriter.write(orders); jaxbWriter.endDocument(); } catch (Exception e) { e.printStackTrace(); } } public void demoModify() { try { File inputFile = new File("xml/jaxb/primer.xml"); JAXBModifier jaxbReader = new JAXBModifier("org.dom4j.test.primer"); jaxbReader.addObjectModifier("/purchaseOrders/purchaseOrder", new PurchaseOrderDateModifier()); Document doc = jaxbReader.modify(inputFile); System.out.println("Modified document:"); System.out.println(doc.asXML()); System.out.println(); } catch (Exception e) { e.printStackTrace(); } } public void demoModifyWrite() { try { File inputFile = new File("xml/jaxb/primer.xml"); File outputFile = new File(outputDir, "testModifyWrite.xml"); JAXBModifier jaxbModifier = new JAXBModifier( "org.dom4j.test.primer", OutputFormat.createPrettyPrint()); jaxbModifier.setPruneElements(true); jaxbModifier.setOutput(outputFile); jaxbModifier.addObjectModifier("/purchaseOrders/purchaseOrder", new PurchaseOrderDateModifier()); Document doc = jaxbModifier.modify(inputFile); System.out.println("Pruned modified document:"); System.out.println(doc.asXML()); System.out.println(); } catch (Exception e) { e.printStackTrace(); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: JAXBDemo.java,v 1.3 2005/01/29 14:52:58 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/dom/0000755000175000017500000000000012133227266020352 5ustar ebourgebourgdom4j-1.6.1/src/samples/org/dom4j/samples/dom/SAXDOMDemo.java0000644000175000017500000001053710242120010022775 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: SAXDOMDemo.java,v 1.4 2005/01/29 14:52:58 maartenc Exp $ */ package org.dom4j.samples.dom; import org.dom4j.samples.AbstractDemo; import org.dom4j.Document; import org.dom4j.io.DOMReader; import org.dom4j.io.DOMWriter; import org.dom4j.io.SAXContentHandler; import org.dom4j.io.SAXReader; import org.dom4j.io.SAXWriter; /** * This sample program parses an XML document as a DOM4J tree using SAX, it then * creates a W3C DOM tree which is then used as input for creating a new DOM4J * tree which is then output to SAX which is then parsed into another DOM4J tree * which is then output as XML. * * This is clearly not terribly useful but demonstrates how to convert from SAX * <->DOM4J and DOM4J <->DOM and DOM4J <->text * * @author James Strachan * @version $Revision: 1.4 $ */ public class SAXDOMDemo extends AbstractDemo { public static void main(String[] args) { run(new SAXDOMDemo(), args); } public SAXDOMDemo() { } protected Document parse(String url) throws Exception { SAXReader saxReader = new SAXReader(); Document document = saxReader.read(url); println("Parsed to DOM4J tree using SAX: " + document); // now lets make a DOM object DOMWriter domWriter = new DOMWriter(); org.w3c.dom.Document domDocument = domWriter.write(document); println("Converted to DOM tree: " + domDocument); // now lets read it back as a DOM4J object DOMReader domReader = new DOMReader(); document = domReader.read(domDocument); println("Converted to DOM4J tree using DOM: " + document); // now lets write it back as SAX events to // a SAX ContentHandler which should build up a new document SAXContentHandler contentHandler = new SAXContentHandler(); SAXWriter saxWriter = new SAXWriter(contentHandler, null, contentHandler); saxWriter.write(document); document = contentHandler.getDocument(); println("Converted DOM4J to SAX events then back to DOM4J: " + document); return document; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: SAXDOMDemo.java,v 1.4 2005/01/29 14:52:58 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/dom/DOMDemo.java0000644000175000017500000000720310242117775022445 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: DOMDemo.java,v 1.4 2005/01/29 14:52:58 maartenc Exp $ */ package org.dom4j.samples.dom; import org.dom4j.samples.AbstractDemo; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.dom4j.Document; import org.dom4j.io.DOMReader; /** * A simple test program to demonstrate using W3C DOM and JAXP to load a DOM XML * tree then converting it to a DOM4J tree. * * @author James Strachan * @version $Revision: 1.4 $ */ public class DOMDemo extends AbstractDemo { public static void main(String[] args) { run(new DOMDemo(), args); } public DOMDemo() { } protected Document parse(String url) throws Exception { // parse a DOM tree DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); println("Loading document with JAXP builder: " + builder); org.w3c.dom.Document domDocument = builder.parse(url); println("Created W3C DOM document: " + domDocument); // now convert to DOM4J model DOMReader reader = new DOMReader(); Document document = reader.read(domDocument); println("Created DOM4J document: " + document); return document; } protected void process(Document document) throws Exception { writer.write(document); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: DOMDemo.java,v 1.4 2005/01/29 14:52:58 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/dom/NativeDOMDemo.java0000644000175000017500000000734110242120022023572 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: NativeDOMDemo.java,v 1.4 2005/01/29 14:52:58 maartenc Exp $ */ package org.dom4j.samples.dom; import org.dom4j.samples.AbstractDemo; import org.dom4j.Document; import org.dom4j.dom.DOMDocumentFactory; import org.dom4j.io.SAXReader; /** * A simple test program to demonstrate the use of native DOM support. * * @author James Strachan * @version $Revision: 1.4 $ */ public class NativeDOMDemo extends AbstractDemo { public static void main(String[] args) { run(new NativeDOMDemo(), args); } public NativeDOMDemo() { } public void run(String[] args) throws Exception { if (args.length < 1) { printUsage(""); return; } parseDOM(args[0]); } protected void parseDOM(String xmlFile) throws Exception { println("Loading document: " + xmlFile); SAXReader reader = new SAXReader(DOMDocumentFactory.getInstance()); Document document = reader.read(xmlFile); println("Created document: " + document); if (document instanceof org.w3c.dom.Document) { org.w3c.dom.Document domDocument = (org.w3c.dom.Document) document; println("Created W3C DOM document: " + domDocument); processDOM(domDocument); } else { println("FAILED to make a native W3C DOM document!!"); } } protected void processDOM(org.w3c.dom.Document document) throws Exception { } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: NativeDOMDemo.java,v 1.4 2005/01/29 14:52:58 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/dom/RoundTripDemo.java0000644000175000017500000000675610242120003023742 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: RoundTripDemo.java,v 1.4 2005/01/29 14:52:58 maartenc Exp $ */ package org.dom4j.samples.dom; import org.dom4j.samples.SAXDemo; import org.dom4j.Document; import org.dom4j.io.DOMReader; import org.dom4j.io.DOMWriter; import org.dom4j.io.XMLWriter; /** * A simple program demonstrating a round trip from XML to dom4j to DOM to dom4j * again * * @author James Strachan * @version $Revision: 1.4 $ */ public class RoundTripDemo extends SAXDemo { public static void main(String[] args) { run(new RoundTripDemo(), args); } public RoundTripDemo() { } /** Outputs the document to DOM, parse it back again then output it */ protected void process(Document document) throws Exception { System.out.println("about to output: " + document); // output the document to DOM DOMWriter writer = new DOMWriter(); org.w3c.dom.Document domDocument = writer.write(document); // parse back again DOMReader reader = new DOMReader(); Document doc2 = reader.read(domDocument); System.out.println("parsed back again: " + doc2); // now lets output it again XMLWriter xmlWriter = new XMLWriter(System.out); xmlWriter.write(doc2); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: RoundTripDemo.java,v 1.4 2005/01/29 14:52:58 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/dom/XSLTNativeDOMDemo.java0000644000175000017500000001050210242117776024324 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: XSLTNativeDOMDemo.java,v 1.4 2005/01/29 14:52:58 maartenc Exp $ */ package org.dom4j.samples.dom; import org.dom4j.samples.XSLTDemo; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.dom4j.Document; import org.dom4j.dom.DOMDocumentFactory; import org.dom4j.io.DOMWriter; import org.dom4j.io.SAXReader; /** * This sample program peforms XSLT on the native DOM implementation of dom4j. * * @author James Strachan * @version $Revision: 1.4 $ */ public class XSLTNativeDOMDemo extends XSLTDemo { public static void main(String[] args) { run(new XSLTNativeDOMDemo(), args); } public XSLTNativeDOMDemo() { } protected Document parse(String url) throws Exception { SAXReader reader = new SAXReader(DOMDocumentFactory.getInstance()); return reader.read(url); } /** Perform XSLT on the stylesheet */ protected void process(Document document) throws Exception { // load the transformer TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(xsl .toString())); // Since we are using the native DOM implementation // converting the tree to DOM should be really fast... DOMWriter domWriter = new DOMWriter(); long start = System.currentTimeMillis(); org.w3c.dom.Document domDocument = domWriter.write(document); long end = System.currentTimeMillis(); System.out.println("Converting to a W3C Document took: " + (end - start) + " milliseconds"); // now lets create the TrAX source and result // objects and do the transformation Source source = new DOMSource(domDocument); StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: XSLTNativeDOMDemo.java,v 1.4 2005/01/29 14:52:58 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/XPathTool.java0000644000175000017500000001323410242117775022325 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: XPathTool.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; /** * A simple program that parsers a document and allows XPath expressions to be * evaluated on the document. * * @author James Strachan * @version $Revision: 1.4 $ */ public class XPathTool extends SAXDemo { protected Document document; protected XMLWriter xmlWriter; protected boolean verbose; public static void main(String[] args) { run(new XPathTool(), args); } public XPathTool() { } public void run(String[] args) throws Exception { if (args.length < 1) { printUsage("{options} "); return; } for (int i = 0, size = args.length; i < size; i++) { String arg = args[i]; if (arg.startsWith("-")) { readOptions(arg); } else { println("Parsing: " + arg); document = parse(arg); break; } } xmlWriter = new XMLWriter(System.out, new OutputFormat(" ", true)); userLoop(); } protected void userLoop() throws Exception { println("Enter XPath expressions to evaluate or 'quit' to stop"); BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); while (true) { print("XPath> "); String line = reader.readLine(); if (line == null) { break; } line = line.trim(); if (line.equalsIgnoreCase("quit")) { break; } evaluateCommand(line); } println("Bye"); } protected void evaluateCommand(String xpath) throws Exception { println("Results..."); Object results = document.selectObject(xpath); printResult(results); xmlWriter.flush(); } protected void printResult(Object results) throws Exception { if (results instanceof Node) { Node node = (Node) results; if (node instanceof Document) { Document document = (Document) node; println("Document: " + document.getName()); } else if (node instanceof Element) { Element element = (Element) node; xmlWriter.writeOpen(element); xmlWriter.println(); } else { xmlWriter.write(node); xmlWriter.println(); } } else if (results instanceof List) { List list = (List) results; println("List of " + list.size() + " item(s)"); for (Iterator iter = list.iterator(); iter.hasNext();) { printResult(iter.next()); } } else { if (results == null) { println("null"); } else { println(results + " (" + results.getClass().getName() + ")"); } } } protected void readOptions(String arg) { if (arg.indexOf('v') >= 0) { verbose = true; } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: XPathTool.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/rule/0000755000175000017500000000000012133227266020542 5ustar ebourgebourgdom4j-1.6.1/src/samples/org/dom4j/samples/rule/SongFilter.java0000644000175000017500000001221510242117775023464 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: SongFilter.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ package org.dom4j.samples.rule; import java.net.URL; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.dom4j.rule.Action; import org.dom4j.rule.Rule; import org.dom4j.rule.Stylesheet; /** * This class is 1:1 representation of the stlyesheet * SongFilter.xsl in package. * * It demonstrates the usage of dom4j Declarative Rule API * * For more information see the * * @link{ http://www.dom4j.org/cookbook.html cookbook }. * * @author Tobias Rademacher * @version $Revision $Date * */ public class SongFilter { private Document resultDoc; private Element songElement; private Element currentSongElement; private Stylesheet style; /** Creates a new instance of SongFilter */ public SongFilter() { this.songElement = DocumentHelper.createElement("song"); } public Document filtering(org.dom4j.Document doc) throws Exception { Element resultRoot = DocumentHelper.createElement("result"); this.resultDoc = DocumentHelper.createDocument(resultRoot); Rule songElementRule = new Rule(); songElementRule.setPattern(DocumentHelper .createPattern("/Songs/song/mp3/id3")); songElementRule.setAction(new SongElementBuilder()); Rule titleTextNodeFilter = new Rule(); titleTextNodeFilter.setPattern(DocumentHelper .createPattern("/Songs/song/mp3/id3/title")); titleTextNodeFilter.setAction(new NodeTextFilter()); this.style = new Stylesheet(); this.style.addRule(songElementRule); this.style.addRule(titleTextNodeFilter); style.run(doc); return this.resultDoc; } private class SongElementBuilder implements Action { public void run(Node node) throws Exception { currentSongElement = songElement.createCopy(); resultDoc.getRootElement().add(currentSongElement); style.applyTemplates(node); } } private class NodeTextFilter implements Action { public void run(Node node) throws Exception { if (currentSongElement != null) { currentSongElement.setText(node.getText()); } } } public static void main(String[] args) throws Exception { SongFilter filter = new SongFilter(); URL source = filter.getClass().getResource( "/org/dom4j/samples/rule/Songs.xml"); Document result = filter.filtering(new SAXReader().read(source)); XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint()); writer.setOutputStream(System.out); writer.write(result); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: SongFilter.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/rule/Songs.xml0000644000175000017500000000640610242120022022340 0ustar ebourgebourg Simon Lifehouse No Name Face 2000 Alternative Rock 6 Hands Clean Alanis Morrisette Under Rug Swept 2002 Alternative Rock 3 Alive Payable On Deatch Satellit 2002 Metal Crawling In The Dark Hoobastank Hoobastank (Selftitled) 2002 Alternative Rock dom4j-1.6.1/src/samples/org/dom4j/samples/rule/SongFilter.xsl0000644000175000017500000000540510242120010023324 0ustar ebourgebourg dom4j-1.6.1/src/samples/org/dom4j/samples/JTidyDemo.java0000644000175000017500000000675210242120015022257 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: JTidyDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import org.dom4j.Document; import org.dom4j.io.DOMReader; import org.w3c.tidy.Tidy; /** * A program which uses JTidy to parse some HTML and turn it into a dom4j * Document * * @author James Strachan * @version $Revision: 1.4 $ */ public class JTidyDemo extends AbstractDemo { public static void main(String[] args) { run(new JTidyDemo(), args); } public JTidyDemo() { } protected Document parse(String xmlFile) throws Exception { InputStream in = openStream(xmlFile); Tidy tidy = new Tidy(); tidy.setXmlOut(true); org.w3c.dom.Document domDocument = tidy.parseDOM(in, null); DOMReader domReader = new DOMReader(); return domReader.read(domDocument); } protected InputStream openStream(String xmlFile) throws Exception { File file = new File(xmlFile); if (file.exists()) { return new BufferedInputStream(new FileInputStream(file)); } return new URL(xmlFile).openStream(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: JTidyDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/AbstractDemo.java0000644000175000017500000001204210242120021022761 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: AbstractDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; /** * An abstract base class for the demo programs. * * @author James Strachan * @version $Revision: 1.4 $ */ public abstract class AbstractDemo { /** The format of XML / HTML that is output by the demo program */ protected OutputFormat format = new OutputFormat(); /** The writer of XML */ protected XMLWriter writer; public AbstractDemo() { } protected static void run(AbstractDemo demo, String[] args) { try { demo.run(args); } catch (DocumentException e) { System.out.println("Exception occurred: " + e); Throwable nestedException = e.getNestedException(); if (nestedException != null) { System.out.println("NestedException: " + nestedException); nestedException.printStackTrace(); } else { e.printStackTrace(); } } catch (Throwable t) { System.out.println("Exception occurred: " + t); t.printStackTrace(); } } public void run(String[] args) throws Exception { if (args.length < 1) { printUsage("no XML document URL specified"); return; } int idx = format.parseOptions(args, 0); if (idx >= args.length) { printUsage("no XML document URL specified"); return; } else { writer = createXMLWriter(); Document document = parse(args[idx]); process(document); } } protected Document parse(String xmlFile) throws Exception { throw new RuntimeException( "parse(String xmlFile) not implemented in this demo"); } protected void process(Document document) throws Exception { getXMLWriter().write(document); getXMLWriter().flush(); } protected void print(String text) { System.out.print(text); } protected void println(String text) { System.out.println(text); } protected void printUsage(String text) { println("Usage: java " + getClass().getName() + " " + text); } protected XMLWriter getXMLWriter() throws Exception { if (writer == null) { writer = createXMLWriter(); } return writer; } /** * A Factory Method to create an XMLWriter instance allowing * derived classes to change this behaviour */ protected XMLWriter createXMLWriter() throws Exception { return new XMLWriter(System.out, format); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: AbstractDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/applets/0000755000175000017500000000000012133227266021243 5ustar ebourgebourgdom4j-1.6.1/src/samples/org/dom4j/samples/applets/SimpleAppletDemo.html0000644000175000017500000000043110242120016025313 0ustar ebourgebourg dom4j-1.6.1/src/samples/org/dom4j/samples/applets/SimpleAppletDemo.java0000644000175000017500000001054310242120012025271 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: SimpleAppletDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples.applets; import java.applet.Applet; import java.awt.Graphics; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; /** * This class demonstrate the use of dom4j in Applets. Note that applets are not * allowed to read files from client disk, if unsigned. * * @author Tobias Rademacher * @version $Revision: 1.4 $ */ public class SimpleAppletDemo extends Applet { private static String DEMO_XML = "\n" + "\n" + "\n" + "snoop\n" + "SnoopServlet\n" + "\n" + ""; private Document demoDocument; private StringBuffer buffer; /** * Called after init. Demonstrates the simplicity of parsing in applets. */ public void start() { try { demoDocument = DocumentHelper.parseText(DEMO_XML); new XMLWriter(OutputFormat.createPrettyPrint()).write(demoDocument); } catch (DocumentException documentEx) { documentEx.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } demoXPath(); repaint(); } /** * Demonstrates the use of XPath in Applets */ private void demoXPath() { this.buffer = new StringBuffer("The name of the servlet is :"); this.buffer.append(demoDocument .valueOf("/web-app/servlet[1]/servlet-name")); this.buffer.append(" and the class is "); this.buffer.append(demoDocument .valueOf("/web-app/servlet[1]/servlet-class")); } /** * Invoked by repaint() and paints a xpath */ public void paint(Graphics g) { g.drawRect(0, 0, getSize().width - 1, getSize().height - 1); g.drawString(this.buffer.toString(), 5, 15); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: SimpleAppletDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/XSLTDemo.java0000644000175000017500000001025410242120003022013 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: XSLTDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import org.dom4j.Document; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; /** * A sample program to demonstrate using XSLT to transform a dom4j Document. * * @author James Strachan * @version $Revision: 1.4 $ */ public class XSLTDemo extends SAXDemo { protected String xsl; public static void main(String[] args) { run(new XSLTDemo(), args); } public XSLTDemo() { } public void run(String[] args) throws Exception { if (args.length < 2) { printUsage(); return; } int idx = format.parseOptions(args, 0); if (args.length - idx < 2) { printUsage(); return; } else { writer = createXMLWriter(); Document document = parse(args[idx++]); xsl = args[idx++]; process(document); } } protected void printUsage() { printUsage(" "); } /** Perform XSLT on the stylesheet */ protected void process(Document document) throws Exception { // load the transformer TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(xsl)); // now lets create the TrAX source and result // objects and do the transformation Source source = new DocumentSource(document); DocumentResult result = new DocumentResult(); transformer.transform(source, result); // output the transformed document Document transformedDoc = result.getDocument(); writer.write(transformedDoc); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: XSLTDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/LinkChecker.java0000644000175000017500000000631410242120014022602 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: LinkChecker.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import java.util.Iterator; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; /** * A sample program to demonstrate the use of XPath in DOM4J to find all the * hypertext links in a source file. * * @author James Strachan * @version $Revision: 1.4 $ */ public class LinkChecker extends SAXDemo { public static void main(String[] args) { run(new LinkChecker(), args); } public LinkChecker() { } protected void process(Document document) throws Exception { List list = document.selectNodes("//*[local-name()='a']/@href"); System.out.println("Found: " + list.size() + " links(s)"); for (Iterator iter = list.iterator(); iter.hasNext();) { Attribute attribute = (Attribute) iter.next(); System.out.println("href = " + attribute.getValue()); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: LinkChecker.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/LargeDocumentDemo.java0000644000175000017500000001057510242120017023765 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: LargeDocumentDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.ElementHandler; import org.dom4j.ElementPath; import org.dom4j.io.SAXReader; /** * This sample parses a big document using the pruning option of the * {@link SAXReader}. * * @author James Strachan * @version $Revision: 1.4 $ */ public class LargeDocumentDemo extends SAXDemo implements ElementHandler { protected String pruningPath; public static void main(String[] args) { run(new LargeDocumentDemo(), args); } public LargeDocumentDemo() { } public void run(String[] args) throws Exception { if (args.length < 2) { printUsage(" "); return; } String xmlFile = args[0]; pruningPath = args[1]; Document document = parse(xmlFile); process(document); } // ElementHandler interface public void onStart(ElementPath path) { Element element = path.getCurrent(); println("onStart: of parsing element: " + element); } public void onEnd(ElementPath path) { Element element = path.getCurrent(); println("onEnd: of parsing element: " + element + " with: " + element.content().size() + " content node(s)"); // now prune the current element to reduce memory element.detach(); } protected Document parse(String url) throws Exception { SAXReader reader = new SAXReader(); println("Parsing document: " + url); println("Using Pruning Path: " + pruningPath); // enable pruning to call me back as each Element is complete reader.addHandler(pruningPath, this); println("##### starting parse"); Document document = reader.read(url); println("##### finished parse"); // the document will be complete but have the prunePath elements pruned println("Now lets dump what is left of the document after pruning..."); return document; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: LargeDocumentDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/XPathValueOf.java0000644000175000017500000000753110242120022022727 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: XPathValueOf.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.XPath; /** * A utility program which performs XPath expressions on one or more XML files * and outputs the valueOf the XPath expression. It is similar to the * grep command on Unix but uses XPath valueOf for matching * * @author James Strachan * @version $Revision: 1.4 $ */ public class XPathValueOf extends SAXDemo { protected XPath xpath; public static void main(String[] args) { run(new XPathValueOf(), args); } public XPathValueOf() { } public void run(String[] args) throws Exception { if (args.length < 2) { printUsage("{options} "); return; } for (int i = 0, size = args.length; i < size; i++) { String arg = args[i]; if (arg.startsWith("-")) { readOptions(arg); } else { if (xpath == null) { setXPath(arg); } else { Document document = parse(arg); process(document); } } } } public void setXPath(String xpathExpression) { xpath = DocumentHelper.createXPath(xpathExpression); } protected void process(Document document) throws Exception { String value = xpath.valueOf(document); println(value); } protected void readOptions(String arg) { } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: XPathValueOf.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/HTMLWriterDemo.java0000644000175000017500000000600610242120010023160 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: HTMLWriterDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import org.dom4j.io.HTMLWriter; import org.dom4j.io.XMLWriter; /** * A demonstration of the use of HTMLWriter to display XHTML * documents to HTML aware browsers. * * @author James Strachan * @version $Revision: 1.4 $ */ public class HTMLWriterDemo extends SAXDemo { public static void main(String[] args) { run(new HTMLWriterDemo(), args); } public HTMLWriterDemo() { } /** * A Factory Method to create an XMLWriter instance allowing * derived classes to change this behaviour */ protected XMLWriter createXMLWriter() throws Exception { return new HTMLWriter(System.out); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: HTMLWriterDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/RoundTripDemo.java0000644000175000017500000000707310242120006023157 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: RoundTripDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import java.io.StringReader; import java.io.StringWriter; import org.dom4j.Document; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; /** * A simple program demonstrating a round trip from XML to dom4j to text to * dom4j again * * @author James Strachan * @version $Revision: 1.4 $ */ public class RoundTripDemo extends SAXDemo { public static void main(String[] args) { run(new RoundTripDemo(), args); } public RoundTripDemo() { } /** Outputs the document to a buffer, parse it back again then output it */ protected void process(Document document) throws Exception { System.out.println("about to output: " + document); // output the document to a buffer StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out); writer.write(document); writer.close(); // parse back again StringReader in = new StringReader(out.toString()); SAXReader reader = new SAXReader(); Document doc2 = reader.read(in); System.out.println("parsed back again: " + doc2); // now lets output it again writer.setOutputStream(System.out); writer.write(doc2); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: RoundTripDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/VisitorDemo2.java0000644000175000017500000001042210242120015022742 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: VisitorDemo2.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.io.SAXReader; /** * This demo uses the Visitor Pattern in DOM4J to display the effect of changing * the {@link DocumentFactory}used when reading a DOM4J object model from a * {@link SAXReader}. * * @author James Strachan * @version $Revision: 1.4 $ */ public class VisitorDemo2 extends VisitorDemo { /** The DocumentFactory class name to use */ protected String documentFactoryClassName; public static void main(String[] args) { run(new VisitorDemo2(), args); } public VisitorDemo2() { } public void run(String[] args) throws Exception { if (args.length < 1) { printUsage(" []"); return; } String xmlFile = args[0]; documentFactoryClassName = (args.length > 1) ? args[1] : null; Document document = parse(xmlFile); process(document); } protected SAXReader createSAXReader() throws Exception { println("Using SAX parser: " + System.getProperty("org.xml.sax.driver", "default")); SAXReader answer = new SAXReader(); if (documentFactoryClassName != null) { try { Class theClass = Class.forName(documentFactoryClassName); DocumentFactory factory = (DocumentFactory) theClass .newInstance(); if (factory != null) { println("DocumentFactory: " + factory); answer.setDocumentFactory(factory); } } catch (Exception e) { println("ERROR: Failed to create an instance of DocumentFactory: " + documentFactoryClassName); println("Exception: " + e); e.printStackTrace(); } } return answer; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: VisitorDemo2.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/CreateXMLDemo.java0000644000175000017500000001037410242120015023013 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: CreateXMLDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import java.io.FileWriter; import java.util.Enumeration; import java.util.Properties; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; /** * A sample program to demonstrate creating some XML output using DOM4J. This * sample generates an XML document representing the state of the current JVM * displaying the current system properties. * * @author James Strachan * @version $Revision: 1.4 $ */ public class CreateXMLDemo extends AbstractDemo { public static void main(String[] args) { run(new CreateXMLDemo(), args); } public CreateXMLDemo() { } public void run(String[] args) throws Exception { Document document = createDocument(); OutputFormat format = new OutputFormat(" ", true); if (args.length < 1) { XMLWriter writer = new XMLWriter(System.out, format); writer.write(document); } else { String fileName = args[0]; println("Writing file: " + fileName); FileWriter out = new FileWriter(args[0]); XMLWriter writer = new XMLWriter(out, format); writer.write(document); out.close(); } } protected Document createDocument() throws Exception { Document document = DocumentHelper.createDocument(); Element root = document.addElement("system"); Properties properties = System.getProperties(); for (Enumeration elements = properties.propertyNames(); elements .hasMoreElements();) { String name = (String) elements.nextElement(); String value = properties.getProperty(name); Element element = root.addElement("property"); element.addAttribute("name", name); element.addText(value); } return document; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: CreateXMLDemo.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/validate/0000755000175000017500000000000012133227266021364 5ustar ebourgebourgdom4j-1.6.1/src/samples/org/dom4j/samples/validate/JARVDemo.java0000644000175000017500000001245410242120025023564 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: JARVDemo.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ package org.dom4j.samples.validate; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; import org.dom4j.io.SAXWriter; import org.iso_relax.verifier.Schema; import org.iso_relax.verifier.Verifier; import org.iso_relax.verifier.VerifierFactory; import org.iso_relax.verifier.VerifierHandler; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; /** * A sample program which validates an already existing dom4j Document using the * JARV API using Sun's MSV library implementation. * * @author James Strachan * @version $Revision: 1.4 $ */ public class JARVDemo { public static void main(String[] args) { new JARVDemo().run(args); } public void run(String[] args) { try { if (args.length < 2) { System.out.println("usage: "); System.out .println("Which validates the given XML document against the given schema document"); System.out .println("The schema can be XML Schema, RelaxNG, Relax or TREX"); return; } String xmlFile = args[0]; String schema = args[1]; SAXReader reader = new SAXReader(); Document document = reader.read(xmlFile); process(document, schema); } catch (DocumentException e) { System.out.println("Exception occurred: " + e); Throwable nestedException = e.getNestedException(); if (nestedException != null) { System.out.println("NestedException: " + nestedException); nestedException.printStackTrace(); } else { e.printStackTrace(); } } catch (Throwable t) { System.out.println("Exception occurred: " + t); t.printStackTrace(); } } /** Validate document using MSV */ protected void process(Document document, String schemaURI) throws Exception { System.out.println("Loaded schema document: " + schemaURI); // use autodetection of schemas VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl(); Schema schema = factory.compileSchema(schemaURI); Verifier verifier = schema.newVerifier(); verifier.setErrorHandler(new ErrorHandler() { public void error(SAXParseException e) { System.out.println("ERROR: " + e); } public void fatalError(SAXParseException e) { System.out.println("FATAL: " + e); } public void warning(SAXParseException e) { System.out.println("WARNING: " + e); } }); System.out.println("Validating XML document"); VerifierHandler handler = verifier.getVerifierHandler(); SAXWriter writer = new SAXWriter(handler); writer.write(document); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: JARVDemo.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/validate/SAXValidatorDemo.java0000644000175000017500000001270710242120021025320 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: SAXValidatorDemo.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ package org.dom4j.samples.validate; import org.dom4j.samples.AbstractDemo; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentType; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.SAXValidator; import org.dom4j.io.XMLWriter; import org.dom4j.util.XMLErrorHandler; import org.xml.sax.SAXException; /** * A sample program demonstrating the use of validation using SAXValidator * * @author James Strachan * @version $Revision: 1.4 $ */ public class SAXValidatorDemo extends AbstractDemo { public static void main(String[] args) { run(new SAXValidatorDemo(), args); } public SAXValidatorDemo() { } public void run(String[] args) throws Exception { if (args.length < 1) { printUsage(" "); } String fileName = args[0]; boolean validateOnParse = false; if (args.length > 1) { String boolText = args[1]; if (boolText.equalsIgnoreCase("true")) { validateOnParse = true; } } validate(fileName, validateOnParse); } protected void validate(String url, boolean validateOnParse) throws Exception { println("Parsing: " + url + " with validation mode: " + validateOnParse); XMLErrorHandler errorHandler = new XMLErrorHandler(); if (validateOnParse) { // validate as we parse SAXReader reader = new SAXReader(true); reader.setErrorHandler(errorHandler); try { Document document = reader.read(url); println("Document: " + url + " is valid!"); } catch (DocumentException e) { println("Document: " + url + " is not valid"); println("Exception: " + e); } } else { // parse without validating, then do that later SAXReader reader = new SAXReader(); Document document = reader.read(url); println("Document URI: " + document.getName()); // now lets set a doc type if one isn't set DocumentType docType = document.getDocType(); if (docType == null) { println("Adding an NITF doc type"); document.addDocType("nitf", null, "nitf.dtd"); } // now lets validate try { SAXValidator validator = new SAXValidator(); validator.setErrorHandler(errorHandler); validator.validate(document); println("Document: " + url + " is valid!"); } catch (SAXException e) { println("Document: " + url + " is not valid"); println("Exception: " + e); } } // now lets output any errors as XML Element errors = errorHandler.getErrors(); if (errors.hasContent()) { XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint()); writer.write(errors); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: SAXValidatorDemo.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/validate/XercesDemo.java0000644000175000017500000000756410242120023024257 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: XercesDemo.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ package org.dom4j.samples.validate; import org.dom4j.samples.AbstractDemo; import org.dom4j.Document; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.dom4j.util.XMLErrorHandler; /** * Validates a document using Xerces and an XML Schema. * * @author James Strachan * @version $Revision: 1.4 $ */ public class XercesDemo extends AbstractDemo { public static void main(String[] args) { run(new XercesDemo(), args); } public XercesDemo() { } public void run(String[] args) throws Exception { if (args.length < 1) { printUsage("no XML document URL specified"); return; } parse(args[0]); } protected Document parse(String uri) throws Exception { SAXReader reader = new SAXReader(); reader.setValidation(true); // specify the schema to use reader .setProperty( "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "personal.xsd"); // add an error handler which turns any errors into XML XMLErrorHandler errorHandler = new XMLErrorHandler(); reader.setErrorHandler(errorHandler); // now lets parse the document Document document = reader.read(uri); // now lets output the errors as XML XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint()); writer.write(errorHandler.getErrors()); return document; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: XercesDemo.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/validate/JARVDemo2.java0000644000175000017500000001250410242120003023636 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: JARVDemo2.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ package org.dom4j.samples.validate; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; import org.iso_relax.verifier.Schema; import org.iso_relax.verifier.Verifier; import org.iso_relax.verifier.VerifierFactory; import org.iso_relax.verifier.VerifierFilter; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; /** * A sample program which validates an XML document as is it being parsed using * the JARV API with Sun's MSV library implementation. * * @author James Strachan * @version $Revision: 1.4 $ */ public class JARVDemo2 { public static void main(String[] args) { new JARVDemo2().run(args); } public void run(String[] args) { try { if (args.length < 2) { System.out.println("usage: "); System.out .println("Which validates the given XML document against the given schema document"); System.out .println("The schema can be XML Schema, RelaxNG, Relax or TREX"); return; } String xmlFile = args[0]; String schema = args[1]; SAXReader reader = createSAXReader(schema); Document document = reader.read(xmlFile); System.out.println("Parsed document: " + xmlFile + " correctly."); } catch (DocumentException e) { System.out.println("Exception occurred: " + e); Throwable nestedException = e.getNestedException(); if (nestedException != null) { System.out.println("NestedException: " + nestedException); nestedException.printStackTrace(); } else { e.printStackTrace(); } } catch (Throwable t) { System.out.println("Exception occurred: " + t); t.printStackTrace(); } } /** Registers the Verifier with the SAXReader */ protected SAXReader createSAXReader(String schemaURI) throws Exception { System.out.println("Loaded schema document: " + schemaURI); // use autodetection of schemas VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl(); Schema schema = factory.compileSchema(schemaURI); Verifier verifier = schema.newVerifier(); verifier.setErrorHandler(new ErrorHandler() { public void error(SAXParseException e) { System.out.println("ERROR: " + e); } public void fatalError(SAXParseException e) { System.out.println("FATAL: " + e); } public void warning(SAXParseException e) { System.out.println("WARNING: " + e); } }); // now install the verifying filter VerifierFilter filter = verifier.getVerifierFilter(); SAXReader reader = new SAXReader(); reader.setXMLFilter(filter); return reader; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: JARVDemo2.java,v 1.4 2005/01/29 14:53:14 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/performance/0000755000175000017500000000000012133227266022074 5ustar ebourgebourgdom4j-1.6.1/src/samples/org/dom4j/samples/performance/Timer.java0000644000175000017500000001354010242120024024001 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: Timer.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ package org.dom4j.samples.performance; /** * A timer for use in performance monitoring * * @author James Strachan * @version $Revision: 1.4 $ */ public class Timer { /** Whether the performance of each run is printed */ protected static boolean VERBOSE = false; /** Default number of loops */ protected static final int DEFAULT_LOOP_COUNT = 40; /** The number of the first loops to display */ private int displayCount = 4; /** Number of loops to perform */ private int loopCount = DEFAULT_LOOP_COUNT; private Task task; public Timer() { } public Timer(Task task) { this.task = task; } /** * Performs a piece of code a number of times in a loop * * @param loopCount * is the number of loops to perform */ public void run() throws Exception { Task task = getTask(); int size = getLoopCount(); if (size <= 0 || task == null) { return; } long[] times = new long[size]; for (int i = 0; i < size; i++) { long start = System.currentTimeMillis(); task.run(); long end = System.currentTimeMillis(); times[i] = end - start; } printSummary(times); } // Properties // ------------------------------------------------------------------------- public Task getTask() { return task; } public void setTask(Task task) { this.task = task; } public int getLoopCount() { return loopCount; } public void setLoopCount(int loopCount) { this.loopCount = loopCount; } // Implementation methods // ------------------------------------------------------------------------- protected void printSummary(long[] times) { println("Performance summary"); println("Number of runs: " + loopCount); if (VERBOSE || loopCount < displayCount) { displayCount = loopCount; } for (int i = 0; i < displayCount; i++) { println("run: " + i + " took: " + times[i] + " (ms)"); } long minimum = times[0]; for (int i = 1; i < loopCount; i++) { long time = times[i]; if (time < minimum) { minimum = time; } } println("Minimum time of run : " + minimum + " (ms)"); // average ignoring first loop long total = 0; for (int i = 0; i < loopCount; i++) { total += times[i]; } double average = total / loopCount; println("Average time of run : " + average + " (ms)"); if (loopCount == 1) { return; } long total_1 = total - times[0]; average = total_1 / (loopCount - 1); println("Average (excluding first run) : " + average + " (ms)"); if (loopCount == 2) { return; } long total_2 = total_1 - times[1]; average = total_2 / (loopCount - 2); println("Average (excluding first & second run): " + average + " (ms)"); println("Total time of run : " + total + " (ms)"); println("Total (excluding first run) : " + total_1 + " (ms)"); println("Total (excluding first & second run) : " + total_2 + " (ms)"); return; } protected void println(String text) { System.out.println(text); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: Timer.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/performance/ToTextTest.java0000644000175000017500000000713210242117777025035 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: ToTextTest.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ package org.dom4j.samples.performance; import java.io.StringWriter; import org.dom4j.Document; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; /** * Tests the performance of turning a Document into text * * @author James Strachan * @version $Revision: 1.4 $ */ public class ToTextTest extends PerformanceSupport { private int bufferSize = 128 * 1024; private Document document; private XMLWriter xmlWriter; private StringWriter stringWriter; public static void main(String[] args) { run(new ToTextTest(), args); } public ToTextTest() { } protected void setUp() throws Exception { SAXReader reader = new SAXReader(); document = reader.read(xmlFile); stringWriter = new StringWriter(bufferSize); xmlWriter = new XMLWriter(stringWriter); } protected void tearDown() throws Exception { println("Created text representation of: " + stringWriter.getBuffer().length() + " characters"); } protected Task createTask() throws Exception { return new Task() { public void run() throws Exception { stringWriter.getBuffer().setLength(0); xmlWriter.write(document); } }; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: ToTextTest.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/performance/ParseLoop.java0000644000175000017500000000764610242120020024633 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: ParseLoop.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ package org.dom4j.samples.performance; import java.io.BufferedReader; import java.io.FileReader; import java.io.StringReader; import org.dom4j.Document; import org.dom4j.io.SAXReader; /** * A simple parsing program that loops which makes it easier to profile * * @author James Strachan * @version $Revision: 1.4 $ */ public class ParseLoop { private static int bufferSize = 128 * 1024; public static void main(String[] args) throws Exception { if (args.length <= 0) { System.out.println("arguments: []"); return; } String xmlFile = args[0]; int loops = 40; if (args.length > 1) { loops = Integer.parseInt(args[1]); } StringBuffer buffer = new StringBuffer(64 * 1024); BufferedReader reader = new BufferedReader(new FileReader(xmlFile)); while (true) { String text = reader.readLine(); if (text == null) { break; } buffer.append(text); buffer.append("\n"); } long start = System.currentTimeMillis(); parse(buffer.toString(), loops); long elapsed = System.currentTimeMillis() - start; System.out.println("Parsed: " + xmlFile + " " + loops + " times in: " + elapsed + " (ms)"); } protected static void parse(String text, int loops) throws Exception { SAXReader xmlReader = new SAXReader(); for (int i = 0; i < loops; i++) { Document document = xmlReader.read(new StringReader(text)); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: ParseLoop.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/performance/PerformanceSupport.java0000644000175000017500000000710310242120014026554 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: PerformanceSupport.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ package org.dom4j.samples.performance; import org.dom4j.samples.SAXDemo; /** * Base class for all simple performance tests * * @author James Strachan * @version $Revision: 1.4 $ */ public abstract class PerformanceSupport extends SAXDemo { /** Whether the performance of each run is printed */ protected static boolean VERBOSE = false; /** Default number of loops */ protected static final int DEFAULT_LOOP_COUNT = 40; /** The XML file to process */ protected String xmlFile; public PerformanceSupport() { } public void run(String[] args) throws Exception { if (args.length < 1) { printUsage(" []"); return; } xmlFile = args[0]; int loopCount = DEFAULT_LOOP_COUNT; if (args.length > 1) { loopCount = Integer.parseInt(args[1]); } setUp(); Timer timer = new Timer(); timer.setLoopCount(loopCount); timer.setTask(createTask()); timer.run(); tearDown(); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } protected abstract Task createTask() throws Exception; } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: PerformanceSupport.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/performance/PullParseTest.java0000644000175000017500000000741110242120014025467 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: PullParseTest.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ package org.dom4j.samples.performance; import java.io.BufferedReader; import java.io.FileReader; import java.io.StringReader; import org.dom4j.Document; import org.dom4j.io.XPPReader; /** * Tests the performance of parsing a Document with the XML Pull Parser * * @author James Strachan * @version $Revision: 1.4 $ */ public class PullParseTest extends PerformanceSupport { private int bufferSize = 128 * 1024; private Document document; private XPPReader xmlReader; private String text; public static void main(String[] args) { run(new PullParseTest(), args); } public PullParseTest() { } protected void setUp() throws Exception { xmlReader = new XPPReader(); StringBuffer buffer = new StringBuffer(64 * 1024); BufferedReader reader = new BufferedReader(new FileReader(xmlFile)); while (true) { String text = reader.readLine(); if (text == null) { break; } buffer.append(text); buffer.append("\n"); } text = buffer.toString(); } protected void tearDown() throws Exception { println("Created Document: " + document); } protected Task createTask() throws Exception { return new Task() { public void run() throws Exception { document = xmlReader.read(new StringReader(text)); } }; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: PullParseTest.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/performance/Task.java0000644000175000017500000000501510242120020023615 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: Task.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ package org.dom4j.samples.performance; /** * An interface for some task which may throw an exception * * @author James Strachan * @version $Revision: 1.4 $ */ public interface Task { public void run() throws Exception; } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: Task.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/performance/ParseTest.java0000644000175000017500000000734410242120013024636 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: ParseTest.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ package org.dom4j.samples.performance; import java.io.BufferedReader; import java.io.FileReader; import java.io.StringReader; import org.dom4j.Document; import org.dom4j.io.SAXReader; /** * Tests the performance of parsing a Document * * @author James Strachan * @version $Revision: 1.4 $ */ public class ParseTest extends PerformanceSupport { private int bufferSize = 128 * 1024; private Document document; private SAXReader xmlReader; private String text; public static void main(String[] args) { run(new ParseTest(), args); } public ParseTest() { } protected void setUp() throws Exception { xmlReader = new SAXReader(); StringBuffer buffer = new StringBuffer(64 * 1024); BufferedReader reader = new BufferedReader(new FileReader(xmlFile)); while (true) { String text = reader.readLine(); if (text == null) { break; } buffer.append(text); buffer.append("\n"); } text = buffer.toString(); } protected void tearDown() throws Exception { println("Created Document: " + document); } protected Task createTask() throws Exception { return new Task() { public void run() throws Exception { document = xmlReader.read(new StringReader(text)); } }; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: ParseTest.java,v 1.4 2005/01/29 14:53:13 maartenc Exp $ */ dom4j-1.6.1/src/samples/org/dom4j/samples/LargeDocumentDemo2.java0000644000175000017500000001124410242120011024033 0ustar ebourgebourg/* * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. * * $Id: LargeDocumentDemo2.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ package org.dom4j.samples; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.ElementHandler; import org.dom4j.ElementPath; import org.dom4j.io.SAXReader; /** * A test harness to test the content API in DOM4J * * @author James Strachan * @version $Revision: 1.4 $ */ public class LargeDocumentDemo2 extends SAXDemo { public static void main(String[] args) { run(new LargeDocumentDemo2(), args); } public LargeDocumentDemo2() { } public void run(String[] args) throws Exception { if (args.length < 1) { printUsage(""); return; } String xmlFile = args[0]; Document document = parse(xmlFile); process(document); } protected Document parse(String url) throws Exception { SAXReader reader = new SAXReader(); println("Parsing document: " + url); // enable pruning to call me back as each Element is complete reader.addHandler("/PLAY/ACT", new playActHandler()); println("##### starting parse"); Document document = reader.read(url); println("##### finished parse"); // the document will be complete but have the prunePath elements pruned println("Now lets dump what is left of the document after pruning..."); return document; } class playActHandler implements ElementHandler { public void onStart(ElementPath path) { Element element = path.getCurrent(); path.addHandler("SCENE/SPEECH", new actSceneSpeechHandler()); } public void onEnd(ElementPath path) { Element element = path.getCurrent(); println("Found Act: " + element.element("TITLE").getText()); path.removeHandler("SCENE/SPEECH"); element.detach(); } } class actSceneSpeechHandler implements ElementHandler { public void onStart(ElementPath path) { Element element = path.getCurrent(); println("Found Start of Speech"); } public void onEnd(ElementPath path) { Element element = path.getCurrent(); println("Found End of Speech by Speaker: " + element.element("SPEAKER").getText()); element.detach(); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved. * * $Id: LargeDocumentDemo2.java,v 1.4 2005/01/29 14:52:57 maartenc Exp $ */ dom4j-1.6.1/src/doc/0000755000175000017500000000000010242120012013400 5ustar ebourgebourgdom4j-1.6.1/src/doc/style/0000755000175000017500000000000012133227266014564 5ustar ebourgebourgdom4j-1.6.1/src/doc/style/javadoc.css0000644000175000017500000000234410242120012016664 0ustar ebourgebourg/* Apache Javadoc style sheet */ /* Page background color */ body { background-color: #FFFFFF } /* Table colors */ .TableHeadingColor { background: #D0D0D0 } .TableSubHeadingColor { background: #E0E0E0 } .TableRowColor { background: #F9F9F9 } /* Navigation bar fonts and colors */ .NavBarCell1 { background-color:#D0D0D0;} .NavBarCell1Rev { background-color:#A0A0A0;} .NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;} .NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;} .NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#E0E0E0;} .NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#F0F0F0;} /* Font used in left-hand frame lists */ .FrameTitleFont { font-size: normal; font-family: Helvetica, Arial, sans-serif } .FrameHeadingFont { font-size: normal; font-family: Helvetica, Arial, sans-serif } .FrameItemFont { font-size: 10pt; font-family: Helvetica, Arial, sans-serif } /* Link colors styling */ A:link { color: #0000A0 } /* unvisited link */ A:visited { color: #A00000 } /* visited links */ A:active { color: #00A000 } /* active links */ dom4j-1.6.1/src/test/0000755000175000017500000000000010242117775013640 5ustar ebourgebourgdom4j-1.6.1/src/test/org/0000755000175000017500000000000010242117775014427 5ustar ebourgebourgdom4j-1.6.1/src/test/org/dom4j/0000755000175000017500000000000012133227266015442 5ustar ebourgebourgdom4j-1.6.1/src/test/org/dom4j/bean/0000755000175000017500000000000012133227266016347 5ustar ebourgebourgdom4j-1.6.1/src/test/org/dom4j/bean/BeansTest.java0000644000175000017500000000541210242120006021063 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.bean; import junit.textui.TestRunner; import org.dom4j.AbstractTestCase; import org.dom4j.io.SAXReader; /** * DOCUMENT ME! * * @author Maarten Coene */ public class BeansTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(BeansTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testReadXML() throws Exception { SAXReader reader = new SAXReader(BeanDocumentFactory.getInstance()); getDocument("/xml/bean/gui.xml", reader); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/ParseTextTest.java0000644000175000017500000000705610242120025021054 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; /** * Tests the {@link DocumentHelper#parseText(String)}method. * * @author James Strachan * @version $Revision: 1.3 $ */ public class ParseTextTest extends AbstractTestCase { protected String xmlText = "Paris"; public static void main(String[] args) { TestRunner.run(ParseTextTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testDocument() throws Exception { assertTrue("Document is not null", document != null); Element root = document.getRootElement(); assertTrue("Root element is not null", root != null); Element author = root.element("author"); assertTrue("Author element is not null", author != null); String name = author.attributeValue("name"); assertEquals("Name attribute matches", name, "James"); String location = document.valueOf("/root/author/location"); assertEquals("Location element matches", location, "Paris"); } // Implementation methods // ------------------------------------------------------------------------- protected void setUp() throws Exception { super.setUp(); document = DocumentHelper.parseText(xmlText); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/AttributeDetachTest.java0000644000175000017500000000753510242120022022210 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.Iterator; import java.util.List; /** * A test harness to test the detach() method on attributes * * @author James Strachan * @version $Revision: 1.3 $ */ public class AttributeDetachTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(AttributeDetachTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testDetachAttribute() throws Exception { List attributes = document.selectNodes("//@name"); assertTrue("Found more than one attribute: ", attributes.size() > 0); for (Iterator iter = attributes.iterator(); iter.hasNext();) { Attribute attribute = (Attribute) iter.next(); Element element = attribute.getParent(); assertTrue("Attribute: " + attribute + " has parent: " + element, attribute.getParent() == element); QName qname = attribute.getQName(); Attribute attribute2 = element.attribute(qname); String value = attribute.getValue(); String value2 = element.attributeValue(qname); assertEquals("Attribute and Element have same attrbute value", value, value2); attribute.detach(); attribute2 = element.attribute(qname); value2 = element.attributeValue(qname); assertTrue("Element now has no value: " + value2, value2 == null); assertTrue("Element now has no attribute: " + attribute2, attribute2 == null); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/NormalizeTest.java0000644000175000017500000000646310242120014021074 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; /** * A test harness for the normalize() method * * @author James Strachan * @version $Revision: 1.3 $ */ public class NormalizeTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(NormalizeTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testNormalize() throws Exception { String text = document.asXML(); document.normalize(); String normalizedText = document.asXML(); log("Initial: " + text); log("Normalized: " + normalizedText); String value = document.valueOf("/dummy/full"); assertEquals("Should not trim text", " node ", value); } // Implementation methods // ------------------------------------------------------------------------- protected void setUp() throws Exception { super.setUp(); String xml = " node with text " + "another node "; document = DocumentHelper.parseText(xml); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/tree/0000755000175000017500000000000012133227266016401 5ustar ebourgebourgdom4j-1.6.1/src/test/org/dom4j/tree/NamespaceCacheTest.java0000644000175000017500000001210410242120015022701 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import junit.textui.TestRunner; import org.dom4j.AbstractTestCase; import org.dom4j.Namespace; /** * A test harness to test the performance of the NamespaceCache * * @author Brett Finnell */ public class NamespaceCacheTest extends AbstractTestCase { private static final int THREADCOUNT = 50; private static final int ITERATIONCOUNT = 10000; public static void main(String[] args) { TestRunner.run(NamespaceCacheTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testGetSameNamespaceSingleThread() { long start = System.currentTimeMillis(); SameNSTest test = new SameNSTest(); test.run(); long end = System.currentTimeMillis(); System.out.println("Same NS Single took " + (end - start) + " ms"); } public void testGetSameNamespaceMultiThread() throws Exception { long start = System.currentTimeMillis(); runMultiThreadedTest(new SameNSTest()); long end = System.currentTimeMillis(); System.out.println("Different NS Single took " + (end - start) + " ms"); } public void testGetNewNamespaceSingleThread() { long start = System.currentTimeMillis(); DifferentNSTest test = new DifferentNSTest(); test.run(); long end = System.currentTimeMillis(); System.out.println("Same NS Multi took " + (end - start) + " ms"); } public void testGetNewNamespaceMultiThread() throws Exception { long start = System.currentTimeMillis(); runMultiThreadedTest(new DifferentNSTest()); long end = System.currentTimeMillis(); System.out.println("Different NS Multi took " + (end - start) + " ms"); } private void runMultiThreadedTest(Runnable test) throws Exception { // Make the threads Thread[] threads = new Thread[THREADCOUNT]; for (int i = 0; i < THREADCOUNT; i++) { threads[i] = new Thread(new SameNSTest()); } // Start the threads for (int j = 0; j < THREADCOUNT; j++) { threads[j].start(); } // Join with the threads for (int k = 0; k < THREADCOUNT; k++) { threads[k].join(); } } private class SameNSTest implements Runnable { public void run() { NamespaceCache cache = new NamespaceCache(); for (int i = 0; i < ITERATIONCOUNT; i++) { Namespace ns = cache.get("prefix", "uri"); } } } private class DifferentNSTest implements Runnable { public void run() { NamespaceCache cache = new NamespaceCache(); for (int i = 0; i < ITERATIONCOUNT; i++) { Namespace ns = cache.get("prefix", Integer.toString(i)); } } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/tree/CDataTest.java0000644000175000017500000000554310242120000021040 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import junit.textui.TestRunner; import org.dom4j.AbstractTestCase; /** * DOCUMENT ME! * * @author Maarten Coene */ public class CDataTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(CDataTest.class); } public void testNullTest() { DefaultCDATA cdata = new DefaultCDATA(null); assertEquals("CData not correct", "", cdata.asXML()); } public void testNormal() { DefaultCDATA cdata = new DefaultCDATA("sample"); assertEquals("CData not correct", "", cdata.asXML()); } public void testLongCData() throws Exception { getDocument("xml/test/longCDATA.xml"); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/tree/DefaultElementTest.java0000644000175000017500000001506610242120016022772 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import junit.textui.TestRunner; import org.dom4j.AbstractTestCase; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import java.util.List; /** * JUnit tests for DefaultElement. * * @author Maarten Coene */ public class DefaultElementTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(DefaultElementTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testParentAfterSetContent() throws Exception { Document doc = DocumentHelper.parseText("" + "a" + "b" + "x" + "d" + ""); Node x = doc.selectSingleNode("/root/x"); List content = doc.getRootElement().content(); int position = content.indexOf(x); Element c = DocumentHelper.createElement("c"); c.setText("c"); content.add(position, c); assertNotNull(c.getParent()); doc.getRootElement().setContent(content); assertNotNull("Parent is null of setting content", c.getParent()); } public void testGetStringValue() throws Exception { Document doc = getDocument("xml/test/test_text.xml"); Element message = doc.getRootElement(); String text = message.getStringValue(); assertEquals("String value incorrect", "This should work", text.trim()); String xpathText = (String) doc .selectObject("normalize-space(/message)"); assertEquals("xpath value incorrect", "This should work", xpathText); } public void testBug894878() { Element foo = DocumentFactory.getInstance().createElement("foo"); foo.addText("bla").addAttribute("foo", "bar"); assertEquals("bla", foo.asXML()); foo = DocumentFactory.getInstance().createElement("foo"); foo.addAttribute("foo", "bar").addText("bla"); assertEquals("bla", foo.asXML()); } public void testGetNamespacesForURI() throws Exception { String xml = "" + " " + " " + " " + " " + " " + " " + ""; Document doc = DocumentHelper.parseText(xml); Element schema = doc.getRootElement(); List namespaces = schema .getNamespacesForURI("http://www.w3.org/2001/XMLSchema"); assertNotNull(namespaces); assertEquals(2, namespaces.size()); } public void testDeclaredNamespaces() throws Exception { String xml = "" + " " + " " + ""; Document doc = DocumentHelper.parseText(xml); Element a = doc.getRootElement(); List ns = a.declaredNamespaces(); assertEquals(1, ns.size()); assertSame(a.getNamespaceForPrefix("ns1"), ns.get(0)); Element b = a.element("b"); ns = b.declaredNamespaces(); assertEquals(0, ns.size()); Element c = a.element("c"); ns = c.declaredNamespaces(); assertEquals(1, ns.size()); assertSame(c.getNamespaceForPrefix("ns2"), ns.get(0)); } public void testAdditionalNamespaces() throws Exception { String xml = "" + " " + " " + ""; Document doc = DocumentHelper.parseText(xml); Element a = doc.getRootElement(); List ns = a.additionalNamespaces(); assertEquals(1, ns.size()); assertSame(a.getNamespaceForPrefix("ns1"), ns.get(0)); Element b = a.element("b"); ns = b.additionalNamespaces(); assertEquals(0, ns.size()); Element c = a.element("c"); ns = c.additionalNamespaces(); assertEquals(0, ns.size()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/tree/DefaultDocumentTest.java0000644000175000017500000001330710242120022023150 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import junit.textui.TestRunner; import java.io.ByteArrayOutputStream; import org.dom4j.AbstractTestCase; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.IllegalAddException; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; /** * Some tests on DefaultDocument. * * @author Maarten Coene */ public class DefaultDocumentTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(DefaultDocumentTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testDoubleRootElement() { Document document = DocumentFactory.getInstance().createDocument(); document.addElement("root"); Element root = DocumentFactory.getInstance().createElement( "anotherRoot"); try { document.add(root); fail(); } catch (IllegalAddException e) { String msg = e.getMessage(); assertTrue(msg.indexOf(root.toString()) != -1); } } public void testBug799656() throws Exception { Document document = DocumentFactory.getInstance().createDocument(); Element el = document.addElement("root"); el.setText("text with an \u00FC in it"); // u00FC is umlaut System.out.println(document.asXML()); DocumentHelper.parseText(document.asXML()); } public void testAsXMLWithEncoding() throws Exception { DefaultDocument document = new DefaultDocument(); document.addElement("root"); document.setXMLEncoding("ISO-8859-1"); Document doc = DocumentHelper.parseText(""); String xml1 = document.asXML(); String xml2 = doc.asXML(); assertTrue(xml1.indexOf("ISO-8859-1") != -1); assertTrue(xml2.indexOf("ISO-8859-1") != -1); } public void testBug1156909() throws Exception { Document doc = DocumentHelper.parseText(""); assertEquals("XMLEncoding not correct", "ISO-8859-1", doc .getXMLEncoding()); } public void testAsXMLWithEncodingAndContent() throws Exception { DefaultDocument document = new DefaultDocument(); document.setXMLEncoding("UTF-16"); Element root = document.addElement("root"); root.setText("text with an \u00FC in it"); // u00FC is umlaut String xml = document.asXML(); assertTrue(xml.indexOf("UTF-16") != -1); assertTrue(xml.indexOf('\u00FC') != -1); } public void testEncoding() throws Exception { Document document = DocumentFactory.getInstance().createDocument( "koi8-r"); Element el = document.addElement("root"); el.setText("text with an \u00FC in it"); // u00FC is umlaut System.out.println(document.asXML()); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputFormat of = OutputFormat.createPrettyPrint(); of.setEncoding("koi8-r"); XMLWriter writer = new XMLWriter(out, of); writer.write(document); String result = out.toString("koi8-r"); System.out.println(result); Document doc2 = DocumentHelper.parseText(result); // System.out.println(doc2.asXML()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/swing/0000755000175000017500000000000012133227266016571 5ustar ebourgebourgdom4j-1.6.1/src/test/org/dom4j/swing/TableModelTest.java0000644000175000017500000001260310242120011022261 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.swing; import junit.textui.TestRunner; import javax.swing.table.TableModel; import org.dom4j.AbstractTestCase; import org.dom4j.Document; /** * Tests the Swing TableModel using a dom4j document. * * @author James Strachan * @version $Revision: 1.4 $ */ public class TableModelTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(TableModelTest.class); } public void testServletTable() throws Exception { Document document = getDocument("/xml/web.xml"); XMLTableDefinition tableDefinition = new XMLTableDefinition(); tableDefinition.setRowExpression("/web-app/servlet"); tableDefinition.addStringColumn("Name", "servlet-name"); tableDefinition.addStringColumn("Class", "servlet-class"); String mapping = "../servlet-mapping[servlet-name=$Name]/url-pattern"; tableDefinition.addStringColumn("Mapping", mapping); XMLTableModel tableModel = new XMLTableModel(tableDefinition, document); // now lets test the values come out assertEquals("correct row count", tableModel.getRowCount(), 2); assertEquals("correct column count", tableModel.getColumnCount(), 3); assertColumnNameEquals(tableModel, 0, "Name"); assertColumnNameEquals(tableModel, 1, "Class"); assertColumnNameEquals(tableModel, 2, "Mapping"); assertCellEquals(tableModel, 0, 0, "snoop"); assertCellEquals(tableModel, 1, 0, "file"); assertCellEquals(tableModel, 0, 1, "SnoopServlet"); assertCellEquals(tableModel, 1, 1, "ViewFile"); assertCellEquals(tableModel, 0, 2, "/foo/snoop"); assertCellEquals(tableModel, 1, 2, ""); } public void testServletTableViaXMLDescription() throws Exception { Document definition = getDocument("/xml/swing/tableForWeb.xml"); Document document = getDocument("/xml/web.xml"); XMLTableModel tableModel = new XMLTableModel(definition, document); // now lets test the values come out assertEquals("correct row count", tableModel.getRowCount(), 2); assertEquals("correct column count", tableModel.getColumnCount(), 3); assertColumnNameEquals(tableModel, 0, "Name"); assertColumnNameEquals(tableModel, 1, "Class"); assertColumnNameEquals(tableModel, 2, "Mapping"); assertCellEquals(tableModel, 0, 0, "snoop"); assertCellEquals(tableModel, 1, 0, "file"); assertCellEquals(tableModel, 0, 1, "SnoopServlet"); assertCellEquals(tableModel, 1, 1, "ViewFile"); assertCellEquals(tableModel, 0, 2, "/foo/snoop"); assertCellEquals(tableModel, 1, 2, ""); } protected void assertColumnNameEquals(TableModel tableModel, int columnIndex, String name) { assertEquals("Column name correct for index: " + columnIndex, name, tableModel.getColumnName(columnIndex)); } protected void assertCellEquals(TableModel tableModel, int rowIndex, int columnIndex, Object value) { assertEquals("Cell value at row: " + rowIndex + " col: " + columnIndex, value, tableModel.getValueAt(rowIndex, columnIndex)); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/ThreadingTest.java0000644000175000017500000003040210242120021021025 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import com.clarkware.junitperf.LoadTest; import com.clarkware.junitperf.TimedTest; import junit.extensions.RepeatedTest; import junit.framework.Test; import junit.framework.TestSuite; import junit.textui.TestRunner; import java.text.FieldPosition; import java.text.SimpleDateFormat; import java.util.Date; /** * A test harness to test the dom4j package in a threaded environment * * @author David Lucas * @version $Revision: 1.3 $ */ public class ThreadingTest extends AbstractTestCase { private static final ThreadLocal FORMATTER_CACHE = new ThreadLocal(); private static final String SEPERATOR = " - "; private static final FieldPosition FIELD_ZERO = new FieldPosition(0); public ThreadingTest(String name) { super(name); } private static void preformat(StringBuffer strBuf, String context) { long now = System.currentTimeMillis(); Date currentTime = new Date(now); SimpleDateFormat formatter = (SimpleDateFormat) FORMATTER_CACHE.get(); if (formatter == null) { formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS zzz"); FORMATTER_CACHE.set(formatter); } strBuf.append("["); formatter.format(currentTime, strBuf, FIELD_ZERO); strBuf.append(" (").append(now).append(") ]"); strBuf.append(SEPERATOR); strBuf.append(getThreadId()); strBuf.append(SEPERATOR); strBuf.append(context); strBuf.append(SEPERATOR); } private static String getThreadId() { String tid = Thread.currentThread().getName(); return tid; } /** * This test combines many different types of operations on DOM4J in a * threaded environment. If a problem occurs with threading, the tests will * fail. This was used to help isolate an internal threading issue. * Unfortunately it may not always create the condition necessary to break * un-thread-safe code. This is due to the nature of the machine, JVM, and * application and if the conditions are right. Typically the problems of * multithreading occur due to an unprotected HashMap or ArrayList in a * class being used by more than one thread. Also, most developers think * that their class or object instance will only be used by one thread. But * if a factory or singleton caches a class or instance, it can quickly * become an unsafe environment. Hence this test to assist in locating * threading issues. */ public void testCombo() { int loop = 10; try { long begin = System.currentTimeMillis(); String value = null; String expected = null; String xml = null; Document doc = null; Element root = null; Element item = null; Element newItem = null; QName qn = null; Namespace ns = null; long now = 0; xml = "" + " Context" + " This is a TEST" + " xyzcustomer" + ""; for (int i = 0; i < loop; i++) { doc = DocumentHelper.parseText(xml); root = doc.getRootElement(); ns = Namespace.get("t0", "http://www.lse.com/t0"); qn = QName.get("Signon", ns); item = root.element(qn); value = item.asXML(); expected = "" + "xyzcustomer"; assertEquals("test t0:Signon ", expected, value); qn = root.getQName("Test"); newItem = DocumentHelper.createElement(qn); now = System.currentTimeMillis(); newItem.setText(String.valueOf(now)); root.add(newItem); qn = root.getQName("Test2"); newItem = DocumentHelper.createElement(qn); now = System.currentTimeMillis(); newItem.setText(String.valueOf(now)); root.add(newItem); item = root.element(qn); item.detach(); item.setQName(qn); root.add(item); value = item.asXML(); expected = "" + now + ""; assertEquals("test Test2 ", expected, value); qn = root.getQName("Test3"); newItem = DocumentHelper.createElement(qn); now = System.currentTimeMillis(); newItem.setText(String.valueOf(now)); root.add(newItem); item = root.element(qn); item.detach(); item.setQName(qn); root.add(item); value = item.asXML(); expected = "" + now + ""; assertEquals("test Test3 ", expected, value); qn = item.getQName("Test4"); newItem = DocumentHelper.createElement(qn); now = System.currentTimeMillis(); newItem.setText(String.valueOf(now)); root.add(newItem); item = root.element(qn); item.detach(); item.setQName(qn); root.add(item); value = item.asXML(); expected = "" + now + ""; assertEquals("test Test4 ", expected, value); } double duration = System.currentTimeMillis() - begin; double avg = duration / loop; } catch (Exception e) { e.printStackTrace(); assertTrue("Exception in test: " + e.getMessage(), false); } } /** * This test isolates QNameCache in a multithreaded environment. */ public void testQNameCache() { int loop = 100; try { long begin = System.currentTimeMillis(); String value = null; String expected = null; String xml = null; Document doc = null; Element root = null; Element item = null; Element newItem = null; QName qn = null; Namespace ns = null; long now = 0; xml = "" + " Context" + " This is a TEST" + " xyzcustomer" + ""; for (int i = 0; i < loop; i++) { doc = DocumentHelper.parseText(xml); root = doc.getRootElement(); qn = DocumentHelper.createQName("test"); value = fetchValue(qn); expected = ""; assertEquals("test test ", expected, value); // creat it again qn = DocumentHelper.createQName("test"); value = fetchValue(qn); expected = ""; assertEquals("test test again ", expected, value); qn = root.getQName("t0:Signon"); value = fetchValue(qn); expected = ""; assertEquals("test t0:Signon ", expected, value); } double duration = System.currentTimeMillis() - begin; double avg = duration / loop; } catch (Exception e) { e.printStackTrace(); assertTrue("Exception in test: " + e.getMessage(), false); } } /** * This method creates a value that can be expected during a test * * @param qn * * @return */ public String fetchValue(QName qn) { String value = null; StringBuffer sb = new StringBuffer(); sb.append("<"); String prefix = qn.getNamespacePrefix(); if ((prefix != null) && (prefix.length() > 0)) { sb.append(prefix).append(":"); } sb.append(qn.getName()); String uri = qn.getNamespaceURI(); if ((uri != null) && (uri.length() > 0)) { sb.append(" xmlns"); if ((prefix != null) && (prefix.length() > 0)) { sb.append(":").append(prefix); } sb.append("=\"").append(uri).append("\""); } sb.append("/>"); value = sb.toString(); return value; } /** * Assembles and returns a test suite. * * @return The suite */ public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(makeRepeatedLoadTest(5, 10, "testCombo")); suite.addTest(makeRepeatedLoadTest(5, 10, "testQNameCache")); return suite; } /** * JUnit method to exercise test via threads and loops * * @param users * Number of users to simulate (i.e. Threads). * @param iterations * Number of iterations per user ( repeat the test x times). * @param testMethod * method to execute (testXXX). * * @return A Junit test */ protected static Test makeRepeatedLoadTest(int users, int iterations, String testMethod) { long maxElapsedTime = 120000 + (1000 * users * iterations); Test testCase = new ThreadingTest(testMethod); Test repeatedTest = new RepeatedTest(testCase, iterations); Test loadTest = new LoadTest(repeatedTest, users); Test timedTest = new TimedTest(loadTest, maxElapsedTime); return timedTest; } public static void main(String[] args) { TestRunner.run(ThreadingTest.class); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/ValidationTest.java0000644000175000017500000000562010242120015021221 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import org.dom4j.io.SAXReader; /** * A test harness for validation when using SAXReader * * @author James Strachan * @version $Revision: 1.3 $ */ public class ValidationTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(ValidationTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testValidation() throws Exception { try { SAXReader reader = new SAXReader(true); reader.read("test"); fail(); } catch (DocumentException e) { // internal parser is non validating, so OK } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/AbstractTestCase.java0000644000175000017500000002515010242120017021470 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.framework.TestCase; import java.io.File; import org.apache.xalan.processor.TransformerFactoryImpl; import org.apache.xerces.jaxp.SAXParserFactoryImpl; import org.dom4j.io.SAXReader; import org.dom4j.util.NodeComparator; /** * An abstract base class for some DOM4J test cases * * @author James Strachan * @version $Revision: 1.24 $ */ public class AbstractTestCase extends TestCase { protected Document document; protected AbstractTestCase() { super(); } protected AbstractTestCase(String name) { super(name); } protected void log(String text) { System.out.println(text); } protected Document getDocument() { return document; } protected Document getDocument(String path) throws Exception { return getDocument(path, new SAXReader()); } protected Document getDocument(String path, SAXReader reader) throws Exception { return reader.read(getFile(path)); } protected File getFile(String path) { return new File(System.getProperty("user.dir"), path); } public void assertDocumentsEqual(Document doc1, Document doc2) throws Exception { try { assertTrue("Doc1 not null", doc1 != null); assertTrue("Doc2 not null", doc2 != null); doc1.normalize(); doc2.normalize(); assertNodesEqual(doc1, doc2); NodeComparator comparator = new NodeComparator(); assertTrue("Documents are equal", comparator.compare(doc1, doc2) == 0); } catch (Exception e) { log("Failed during comparison of: " + doc1 + " and: " + doc2); throw e; } } public void assertNodesEqual(Document n1, Document n2) { // assertEquals( "Document names", n1.getName(), n2.getName() ); assertNodesEqual(n1.getDocType(), n2.getDocType()); assertNodesEqualContent(n1, n2); } public void assertNodesEqual(Element n1, Element n2) { assertNodesEqual(n1.getQName(), n2.getQName()); int c1 = n1.attributeCount(); int c2 = n2.attributeCount(); assertEquals("Elements have same number of attributes (" + c1 + ", " + c2 + " for: " + n1 + " and " + n2, c1, c2); for (int i = 0; i < c1; i++) { Attribute a1 = n1.attribute(i); Attribute a2 = n2.attribute(a1.getQName()); assertNodesEqual(a1, a2); } assertNodesEqualContent(n1, n2); } public void assertNodesEqual(Attribute n1, Attribute n2) { assertNodesEqual(n1.getQName(), n2.getQName()); assertEquals("Attribute values for: " + n1 + " and " + n2, n1 .getValue(), n2.getValue()); } public void assertNodesEqual(QName n1, QName n2) { assertEquals("URIs equal for: " + n1.getQualifiedName() + " and " + n2.getQualifiedName(), n1.getNamespaceURI(), n2 .getNamespaceURI()); assertEquals("qualified names equal", n1.getQualifiedName(), n2 .getQualifiedName()); } public void assertNodesEqual(CharacterData t1, CharacterData t2) { assertEquals("Text equal for: " + t1 + " and " + t2, t1.getText(), t2 .getText()); } public void assertNodesEqual(DocumentType o1, DocumentType o2) { if (o1 != o2) { if (o1 == null) { assertTrue("Missing DocType: " + o2, false); } else if (o2 == null) { assertTrue("Missing DocType: " + o1, false); } else { assertEquals("DocType name equal", o1.getName(), o2.getName()); assertEquals("DocType publicID equal", o1.getPublicID(), o2 .getPublicID()); assertEquals("DocType systemID equal", o1.getSystemID(), o2 .getSystemID()); } } } public void assertNodesEqual(Entity o1, Entity o2) { assertEquals("Entity names equal", o1.getName(), o2.getName()); assertEquals("Entity values equal", o1.getText(), o2.getText()); } public void assertNodesEqual(ProcessingInstruction n1, ProcessingInstruction n2) { assertEquals("PI targets equal", n1.getTarget(), n2.getTarget()); assertEquals("PI text equal", n1.getText(), n2.getText()); } public void assertNodesEqual(Namespace n1, Namespace n2) { assertEquals("Namespace prefixes not equal", n1.getPrefix(), n2 .getPrefix()); assertEquals("Namespace URIs not equal", n1.getURI(), n2.getURI()); } public void assertNodesEqualContent(Branch b1, Branch b2) { int c1 = b1.nodeCount(); int c2 = b2.nodeCount(); if (c1 != c2) { log("Content of: " + b1); log("is: " + b1.content()); log("Content of: " + b2); log("is: " + b2.content()); } assertEquals("Branches have same number of children (" + c1 + ", " + c2 + " for: " + b1 + " and " + b2, c1, c2); for (int i = 0; i < c1; i++) { Node n1 = b1.node(i); Node n2 = b2.node(i); assertNodesEqual(n1, n2); } } public void assertNodesEqual(Node n1, Node n2) { int nodeType1 = n1.getNodeType(); int nodeType2 = n2.getNodeType(); assertTrue("Nodes are of same type: ", nodeType1 == nodeType2); switch (nodeType1) { case Node.ELEMENT_NODE: assertNodesEqual((Element) n1, (Element) n2); break; case Node.DOCUMENT_NODE: assertNodesEqual((Document) n1, (Document) n2); break; case Node.ATTRIBUTE_NODE: assertNodesEqual((Attribute) n1, (Attribute) n2); break; case Node.TEXT_NODE: assertNodesEqual((Text) n1, (Text) n2); break; case Node.CDATA_SECTION_NODE: assertNodesEqual((CDATA) n1, (CDATA) n2); break; case Node.ENTITY_REFERENCE_NODE: assertNodesEqual((Entity) n1, (Entity) n2); break; case Node.PROCESSING_INSTRUCTION_NODE: assertNodesEqual((ProcessingInstruction) n1, (ProcessingInstruction) n2); break; case Node.COMMENT_NODE: assertNodesEqual((Comment) n1, (Comment) n2); break; case Node.DOCUMENT_TYPE_NODE: assertNodesEqual((DocumentType) n1, (DocumentType) n2); break; case Node.NAMESPACE_NODE: assertNodesEqual((Namespace) n1, (Namespace) n2); break; default: assertTrue("Invalid node types. node1: " + n1 + " and node2: " + n2, false); } } // Implementation methods // ------------------------------------------------------------------------- protected void setUp() throws Exception { System.setProperty("javax.xml.parsers.SAXParserFactory", SAXParserFactoryImpl.class.getName()); System.setProperty("javax.xml.transform.TransformerFactory", TransformerFactoryImpl.class.getName()); document = DocumentHelper.createDocument(); Element root = document.addElement("root"); Element author1 = root.addElement("author").addAttribute("name", "James").addAttribute("location", "UK").addText( "James Strachan"); Element url1 = author1.addElement("url"); url1.addText("http://sourceforge.net/users/jstrachan/"); Element author2 = root.addElement("author").addAttribute("name", "Bob") .addAttribute("location", "Canada").addText("Bob McWhirter"); Element url2 = author2.addElement("url"); url2.addText("http://sourceforge.net/users/werken/"); } /** * DOCUMENT ME! * * @return the root element of the document */ protected Element getRootElement() { Element root = document.getRootElement(); assertTrue("Document has root element", root != null); return root; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/CloneTest.java0000644000175000017500000001515110242120010020162 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.Comparator; import org.dom4j.dom.DOMDocument; import org.dom4j.dom.DOMDocumentFactory; import org.dom4j.util.NodeComparator; /** * A test harness to test the clone() methods on Nodes * * @author James Strachan * @version $Revision: 1.6 $ */ public class CloneTest extends AbstractTestCase { private Comparator comparator = new NodeComparator(); public static void main(String[] args) { TestRunner.run(CloneTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testBug1148333() { DOMDocumentFactory factory = (DOMDocumentFactory) DOMDocumentFactory .getInstance(); DOMDocument doc = (DOMDocument) factory.createDocument(); Element el = doc.addElement("root"); el.addNamespace("pref2", "uri2"); DOMDocument clone = (DOMDocument) doc.cloneNode(true); assertNotSame(doc, clone); assertNodesEqual(doc, clone); } public void testElementWithNamespaceClone() { Element element = DocumentFactory.getInstance() .createElement("element"); element.addNamespace("prefix", "uri"); Element clone = (Element) element.clone(); assertNotSame(element, clone); assertNodesEqual(element, clone); } public void testDocumentClone() throws Exception { document.setName("doc1"); Document doc2 = (Document) document.clone(); assertNotSame(document, doc2); assertNodesEqual(document, doc2); } public void testAddCloneToOtherElement() { DocumentFactory factory = DocumentFactory.getInstance(); Document doc = factory.createDocument(); Element root = doc.addElement("root"); Element parent1 = root.addElement("parent"); Element child1 = parent1.addElement("child"); Element parent2 = (Element) parent1.clone(); root.add(parent2); assertSame("parent not correct", root, parent2.getParent()); assertSame("document not correct", doc, parent2.getDocument()); Element child2 = parent2.element("child"); assertNotSame("child not cloned", child1, child2); assertSame("parent not correct", parent2, child2.getParent()); assertSame("document not correct", doc, child2.getDocument()); } public void testRootElementClone() throws Exception { testElementClone(document.getRootElement()); } public void testAuthorElementClone() throws Exception { testElementClone((Element) document.selectSingleNode("//author")); } public void testRootCompare1() throws Exception { Document doc2 = (Document) document.clone(); Element author = doc2.getRootElement(); author.addAttribute("foo", "bar"); assertTrue("Documents are not equal", comparator .compare(document, doc2) != 0); } public void testRootCompare2() throws Exception { Document doc2 = (Document) document.clone(); Element author = doc2.getRootElement(); author.addText("foo"); assertTrue("Documents are not equal", comparator .compare(document, doc2) != 0); } public void testAuthorCompare1() throws Exception { Document doc2 = (Document) document.clone(); Element author = (Element) doc2.selectSingleNode("//author"); author.addAttribute("name", "James Strachan"); assertTrue("Documents are not equal", comparator .compare(document, doc2) != 0); } public void testAuthorCompare2() throws Exception { Document doc2 = (Document) document.clone(); Element author = (Element) doc2.selectSingleNode("//author"); author.addText("foo"); assertTrue("Documents are not equal", comparator .compare(document, doc2) != 0); } protected void testElementClone(Element element) throws Exception { Element element2 = (Element) element.clone(); assertTrue("Returned a new Element", element2 != element); assertNull("New element has no parent", element2.getParent()); assertNull("New element has no Document", element2.getDocument()); assertTrue("Element fragments are equal", comparator.compare(element, element2) == 0); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/GetQNamesTest.java0000644000175000017500000000723210242120022020752 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.List; import org.dom4j.io.SAXReader; /** * A test harness to test the DocumentFactory.getQNames() method * * @author James Strachan * @version $Revision: 1.4 $ */ public class GetQNamesTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(GetQNamesTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testQNames() throws Exception { DocumentFactory factory = new DocumentFactory(); SAXReader reader = new SAXReader(); reader.setDocumentFactory(factory); getDocument("/xml/test/soap2.xml", reader); List qnames = factory.getQNames(); assertEquals("Number of QNames not correct", 15, qnames.size()); } /** * Test the element rename functionality which was lacking as spotted by Rob * Lebowitz * * @throws Exception * DOCUMENT ME! */ public void testRename() throws Exception { Document doc = DocumentHelper.createDocument(); Element root = doc.addElement("foo"); assertEquals("named correctly", "foo", root.getName()); root.setName("bar"); assertEquals("named correctly", "bar", root.getName()); QName xyz = root.getQName("xyz"); root.setQName(xyz); assertEquals("QNamed correctly", xyz, root.getQName()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/dom/0000755000175000017500000000000012133227266016221 5ustar ebourgebourgdom4j-1.6.1/src/test/org/dom4j/dom/DOMTest.java0000644000175000017500000002051710242120021020324 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dom; import junit.textui.TestRunner; import java.io.StringReader; import org.dom4j.AbstractTestCase; import org.dom4j.io.DOMWriter; import org.dom4j.io.SAXReader; import org.w3c.dom.DOMException; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * A test harness to test the native DOM implementation of dom4j * * @author James Strachan * @version $Revision: 1.4 $ */ public class DOMTest extends AbstractTestCase { /** Elements. */ private long elements; /** Attributes. */ private long attributes; /** Characters. */ private long characters; public static void main(String[] args) { TestRunner.run(DOMTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testCount() throws Exception { DOMWriter domWriter = new DOMWriter(); long start = System.currentTimeMillis(); org.w3c.dom.Document domDocument = domWriter.write(document); long end = System.currentTimeMillis(); System.out.println("Converting to a W3C Document took: " + (end - start) + " milliseconds"); traverse(domDocument); log("elements: " + elements + " attributes: " + attributes + " characters: " + characters); } public void testNamespace() throws Exception { String xml = ""; SAXReader xmlReader = new SAXReader(DOMDocumentFactory.getInstance()); DOMDocument d = (DOMDocument) xmlReader.read(new StringReader(xml)); assertEquals("namespace prefix not correct", "prefix", d .getRootElement().getNamespace().getPrefix()); assertEquals("namespace uri not correct", "myuri", d.getRootElement() .getNamespace().getURI()); System.out.println(d.asXML()); } /** * Tests the bug found by Soumanjoy * * @throws Exception * DOCUMENT ME! */ public void testClassCastBug() throws Exception { DOMDocument oDocument = new DOMDocument("Root"); org.w3c.dom.Element oParent = oDocument.createElement("Parent"); // <-- Fails here when the code is broken. oParent.setAttribute("name", "N01"); oParent.setAttribute("id", "ID01"); oDocument.appendChild(oParent); // <-- Fails here, Error message is // below } public void testReplaceChild() throws Exception { DOMDocument document = new DOMDocument("Root"); org.w3c.dom.Element parent = document.createElement("Parent"); org.w3c.dom.Element first = document.createElement("FirstChild"); org.w3c.dom.Element second = document.createElement("SecondChild"); org.w3c.dom.Element third = document.createElement("ThirdChild"); document.appendChild(parent); parent.appendChild(first); parent.appendChild(second); parent.appendChild(third); org.w3c.dom.Element newFirst = document.createElement("NewFirst"); org.w3c.dom.Element oldFirst = (org.w3c.dom.Element) parent .replaceChild(newFirst, first); /* check the return value of replaceChild */ assertEquals(oldFirst, first); /* make sure the old node has been replaced */ NodeList children = parent.getChildNodes(); Node firstChild = children.item(0); assertEquals(Node.ELEMENT_NODE, firstChild.getNodeType()); assertEquals(newFirst, firstChild); /* try to replace a node that doesn't exist */ org.w3c.dom.Element badNode = document.createElement("No Child"); try { parent.replaceChild(newFirst, badNode); fail("DOMException not thrown"); } catch (DOMException e) { assertEquals(DOMException.NOT_FOUND_ERR, e.code); } } // Implementation methods // ------------------------------------------------------------------------- protected void setUp() throws Exception { super.setUp(); SAXReader reader = new SAXReader(DOMDocumentFactory.getInstance()); document = getDocument("/xml/contents.xml", reader); } /** * Traverses the specified node, recursively. * * @param node * DOCUMENT ME! */ protected void traverse(Node node) { // is there anything to do? if (node == null) { return; } int type = node.getNodeType(); switch (type) { case Node.DOCUMENT_NODE: { elements = 0; attributes = 0; characters = 0; traverse(((org.w3c.dom.Document) node).getDocumentElement()); break; } case Node.ELEMENT_NODE: { elements++; NamedNodeMap attrs = node.getAttributes(); if (attrs != null) { attributes += attrs.getLength(); } NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) { traverse(children.item(i)); } } break; } case Node.ENTITY_REFERENCE_NODE: { NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) { traverse(children.item(i)); } } break; } case Node.CDATA_SECTION_NODE: { characters += node.getNodeValue().length(); break; } case Node.TEXT_NODE: { characters += node.getNodeValue().length(); break; } default: break; } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/AddNodeTest.java0000644000175000017500000001035510242120020020422 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; /** * A test harness to test the addNode() methods on node * * @author Philippe Ombredanne */ public class AddNodeTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(AddNodeTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testDom4jAddNodeClone() { Document maindoc = DocumentHelper.createDocument(); Element docroot = maindoc.addElement("document"); Element header = docroot.addElement("header").addText("Some Text"); Document subdoc = DocumentHelper.createDocument(); Element docroot2 = subdoc.addElement("document"); docroot2.add((Element) maindoc.selectSingleNode("/document/header") .clone()); assertEquals(subdoc.asXML(), maindoc.asXML()); } public void testDom4jAddNodeCreateCopy() { Document maindoc = DocumentHelper.createDocument(); Element docroot = maindoc.addElement("document"); Element header = docroot.addElement("header").addText("Some Text"); Document subdoc = DocumentHelper.createDocument(); Element docroot2 = subdoc.addElement("document"); docroot2.add(((Element) maindoc.selectSingleNode("/document/header")) .createCopy()); assertEquals(subdoc.asXML(), maindoc.asXML()); } public void testDom4jAddNodeBug() { Document maindoc = DocumentHelper.createDocument(); Element docroot = maindoc.addElement("document"); Element header = docroot.addElement("header").addText("Some Text"); Document subdoc = DocumentHelper.createDocument(); Element subroot = subdoc.addElement("document"); try { // add the header node from maindoc without clone... or createCopy subroot.add((Element) maindoc.selectSingleNode("/document/header")); fail(); } catch (IllegalAddException e) { // the header already has a parent, this exception is normal } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/XSLTTest.java0000644000175000017500000001030110242120023017710 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.List; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; /** * Tests that XSLT works correctly * * @author James Strachan * @version $Revision: 1.4 $ */ public class XSLTTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(XSLTTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testTransform() throws Exception { Document transformedDoc = transform("/xml/nitf/ashtml.xsl"); // log( transformedDoc.asXML() ); assertTrue("Transformed Document is not null", transformedDoc != null); List h1List = transformedDoc.selectNodes("/html//h1"); assertTrue("At least one

", h1List.size() > 0); List pList = transformedDoc.selectNodes("//p"); assertTrue("At least one

", pList.size() > 0); } // Implementation methods // ------------------------------------------------------------------------- protected void setUp() throws Exception { super.setUp(); document = getDocument("/xml/nitf/sample.xml"); } protected Document transform(String xsl) throws Exception { assertTrue("Document is not null", document != null); // load the transformer TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource( getFile(xsl))); // now lets create the TrAX source and result // objects and do the transformation Source source = new DocumentSource(document); DocumentResult result = new DocumentResult(); transformer.transform(source, result); return result.getDocument(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/rule/0000755000175000017500000000000012133227266016411 5ustar ebourgebourgdom4j-1.6.1/src/test/org/dom4j/rule/RuleTest.java0000644000175000017500000001233610242120020021003 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.rule; import junit.textui.TestRunner; import java.util.ArrayList; import java.util.Collections; import org.dom4j.AbstractTestCase; import org.dom4j.CDATA; import org.dom4j.Document; import org.dom4j.DocumentFactory; /** * Tests the ordering of Rules * * @author James Strachan * @version $Revision: 1.3 $ */ public class RuleTest extends AbstractTestCase { protected DocumentFactory factory = new DocumentFactory(); public static void main(String[] args) { TestRunner.run(RuleTest.class); } public void testOrder() throws Exception { testGreater("foo", "*"); } protected void testGreater(String expr1, String expr2) throws Exception { System.out.println("parsing: " + expr1 + " and " + expr2); Rule r1 = createRule(expr1); Rule r2 = createRule(expr2); System.out.println("rule1: " + r1 + " rule2: " + r2); int value = r1.compareTo(r2); System.out.println("Comparison: " + value); assertTrue("r1 > r2", value > 0); ArrayList list = new ArrayList(); list.add(r1); list.add(r2); Collections.sort(list); assertTrue("r2 should be first", list.get(0) == r2); assertTrue("r1 should be next", list.get(1) == r1); list = new ArrayList(); list.add(r2); list.add(r1); Collections.sort(list); assertTrue("r2 should be first", list.get(0) == r2); assertTrue("r1 should be next", list.get(1) == r1); /* * TreeSet set = new TreeSet(); set.add( r1 ); set.add( r2 ); * * assertTrue( "r2 should be first", set.first() == r2 ); assertTrue( * "r1 should be next", set.last() == r1 ); * * Object[] array = set.toArray(); * * assertTrue( "r2 should be first", array[0] == r2 ); assertTrue( "r1 * should be next", array[1] == r1 ); * * set = new TreeSet(); set.add( r2 ); set.add( r1 ); * * assertTrue( "r2 should be first", set.first() == r2 ); assertTrue( * "r1 should be next", set.last() == r1 ); * * array = set.toArray(); * * assertTrue( "r2 should be first", array[0] == r2 ); assertTrue( "r1 * should be next", array[1] == r1 ); */ } public void testDocument() { Rule rule = createRule("/"); Document document = factory.createDocument(); document.addElement("foo"); assertTrue("/ matches document", rule.matches(document)); assertTrue("/ does not match root element", !rule.matches(document .getRootElement())); } public void testTextMatchesCDATA() { CDATA cdata = factory.createCDATA("<>&"); Rule rule = createRule("text()"); assertTrue("text() matches CDATA", rule.matches(cdata)); } protected Rule createRule(String expr) { Pattern pattern = factory.createPattern(expr); return new Rule(pattern); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/rule/PriorityTest.java0000644000175000017500000000656310242120025021727 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.rule; import junit.textui.TestRunner; import org.dom4j.AbstractTestCase; import org.dom4j.DocumentFactory; /** * Tests the priority behaviour of Pattern. * * @author James Strachan * @version $Revision: 1.3 $ */ public class PriorityTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(PriorityTest.class); } public void testNameNode() throws Exception { testPriority("foo", 0); } public void testFilter() throws Exception { testPriority("foo[@id='123']", 0.5); } public void testURI() throws Exception { testPriority("foo:*", -0.25); } public void testAnyNode() throws Exception { testPriority("*", -0.5); } protected void testPriority(String expr, double priority) throws Exception { System.out.println("parsing: " + expr); Pattern pattern = DocumentFactory.getInstance().createPattern(expr); double d = pattern.getPriority(); System.out.println("expr: " + expr + " has priority: " + d); System.out.println("pattern: " + pattern); assertEquals("expr: " + expr, new Double(priority), new Double(d)); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/rule/StylesheetTest.java0000644000175000017500000001370110242120022022224 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.rule; import junit.textui.TestRunner; import org.dom4j.AbstractTestCase; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Node; import org.dom4j.xpath.DefaultXPath; /** * A test harness to test the use of the Stylesheet and the XSLT rule engine. * * @author James Strachan * @version $Revision: 1.4 $ */ public class StylesheetTest extends AbstractTestCase { protected String[] templates = { "/", "*", "root", "author", "@name", "root/author", "author[@location='UK']", "root/author[@location='UK']", "root//author[@location='UK']"}; protected String[] templates2 = {"/", "title", "para", "*"}; protected Stylesheet stylesheet; public static void main(String[] args) { TestRunner.run(StylesheetTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testRules() throws Exception { for (int i = 0, size = templates.length; i < size; i++) { addTemplate(templates[i]); } log(""); log("........................................"); log(""); log("Running stylesheet"); stylesheet.run(document); log("Finished"); } public void testLittleDoc() throws Exception { for (int i = 0, size = templates2.length; i < size; i++) { addTemplate(templates2[i]); } Document doc = getDocument("/xml/test/littledoc.xml"); stylesheet = new Stylesheet(); stylesheet.setValueOfAction(new Action() { public void run(Node node) { log("Default ValueOf action on node: " + node); log("........................................"); } }); stylesheet.run(doc); } public void testFireRuleForNode() throws Exception { final StringBuffer b = new StringBuffer(); final Stylesheet s = new Stylesheet(); Pattern pattern = DocumentHelper.createPattern("url"); Action action = new Action() { public void run(Node node) throws Exception { b.append("url"); s.applyTemplates(node); } }; Rule r = new Rule(pattern, action); s.addRule(r); s.applyTemplates(document, new DefaultXPath("root/author/url")); assertEquals("Check url is processed twice", "urlurl", b.toString()); } // Implementation methods // ------------------------------------------------------------------------- protected void setUp() throws Exception { super.setUp(); stylesheet = new Stylesheet(); stylesheet.setValueOfAction(new Action() { public void run(Node node) { log("Default ValueOf action on node: " + node); log("........................................"); } }); } protected void addTemplate(final String match) { log("Adding template match: " + match); Pattern pattern = DocumentHelper.createPattern(match); log("Pattern: " + pattern); log("........................................"); Action action = new Action() { public void run(Node node) throws Exception { log("Matched pattern: " + match); log("Node: " + node.asXML()); log("........................................"); // apply any child templates stylesheet.applyTemplates(node); } }; Rule rule = new Rule(pattern, action); stylesheet.addRule(rule); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/NodeTypeNameTest.java0000644000175000017500000001267010242117775021505 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.Iterator; /** * Tests the getNodeNameType() method * * @author James Strachan * @version $Revision: 1.4 $ */ public class NodeTypeNameTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(NodeTypeNameTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testDocument() throws Exception { testDocument(getDocument()); } public void testCDATA() throws Exception { testDocument("/xml/cdata.xml"); } public void testNamespaces() throws Exception { testDocument("/xml/namespaces.xml"); testDocument("/xml/testNamespaces.xml"); } public void testPI() throws Exception { testDocument("/xml/testPI.xml"); } public void testInline() throws Exception { testDocument("/xml/inline.xml"); } // Implementation methods // ------------------------------------------------------------------------- protected void testDocument(String fileName) throws Exception { Document document = getDocument(fileName); testDocument(document); } protected void testDocument(Document document) throws Exception { assertEquals(document.getNodeTypeName(), "Document"); DocumentType docType = document.getDocType(); if (docType != null) { assertEquals(docType.getNodeTypeName(), "DocumentType"); } testElement(document.getRootElement()); } protected void testElement(Element element) { assertEquals(element.getNodeTypeName(), "Element"); for (Iterator iter = element.attributeIterator(); iter.hasNext();) { Attribute attribute = (Attribute) iter.next(); assertEquals(attribute.getNodeTypeName(), "Attribute"); } for (Iterator iter = element.nodeIterator(); iter.hasNext();) { Node node = (Node) iter.next(); String nodeTypeName = node.getNodeTypeName(); if (node instanceof Attribute) { assertEquals(nodeTypeName, "Attribute"); } else if (node instanceof CDATA) { assertEquals(nodeTypeName, "CDATA"); } else if (node instanceof Comment) { assertEquals(nodeTypeName, "Comment"); } else if (node instanceof Element) { assertEquals(nodeTypeName, "Element"); testElement((Element) node); } else if (node instanceof Entity) { assertEquals(nodeTypeName, "Entity"); } else if (node instanceof Element) { assertEquals(nodeTypeName, "Element"); } else if (node instanceof Namespace) { assertEquals(nodeTypeName, "Namespace"); } else if (node instanceof ProcessingInstruction) { assertEquals(nodeTypeName, "ProcessingInstruction"); } else if (node instanceof Text) { assertEquals(nodeTypeName, "Text"); } else { assertTrue("Invalid node type: " + nodeTypeName + " for node: " + node, false); } } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/GetXMLEncodingTest.java0000644000175000017500000000751510242120024021703 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.io.ByteArrayInputStream; import java.io.StringReader; import org.dom4j.io.SAXReader; import org.xml.sax.InputSource; /** * DOCUMENT ME! * * @author Maarten Coene * @version $Revision: 1.4 $ */ public class GetXMLEncodingTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(GetXMLEncodingTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testXMLEncodingFromString() throws Exception { String xmlEnc = "\n"; SAXReader reader = new SAXReader(); InputSource source = new InputSource(new ByteArrayInputStream(xmlEnc .getBytes("UTF-8"))); Document doc = reader.read(source); assertEquals("UTF-8", doc.getXMLEncoding()); doc = reader.read(new StringReader(xmlEnc)); assertNull(doc.getXMLEncoding()); } public void testXMLEncodingFromURL() throws Exception { Document doc = getDocument("/xml/test/encode.xml"); assertEquals("UTF-8", doc.getXMLEncoding()); doc = getDocument("/xml/russArticle.xml"); assertEquals("koi8-r", doc.getXMLEncoding()); } public void testXMLEncodingFromStringWithHelper() throws Exception { String xmlEnc = "\n"; String xmlNoEnc = ""; Document doc = DocumentHelper.parseText(xmlEnc); assertEquals("UTF-8", doc.getXMLEncoding()); doc = DocumentHelper.parseText(xmlNoEnc); assertNull(doc.getXMLEncoding()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/IteratorTest.java0000644000175000017500000001564410242117776020753 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.Iterator; import java.util.List; /** * A test harness to test the Iterator API in DOM4J * * @author Jonathan Doughty * @version $Revision: 1.4 $ */ public class IteratorTest extends AbstractTestCase { private static final int NUMELE = 10; protected Document iterDocument; public static void main(String[] args) { TestRunner.run(IteratorTest.class); } protected void setUp() throws Exception { super.setUp(); iterDocument = DocumentHelper.createDocument(); Element root = iterDocument.addElement("root"); for (int i = 0; i < NUMELE; i++) { root.addElement("iterator test").addAttribute("instance", Integer.toString(i)); } } // Test case(s) // ------------------------------------------------------------------------- public void testElementCount() throws Exception { Element root = iterDocument.getRootElement(); assertTrue("Has root element", root != null); List elements = root.elements("iterator test"); int elementSize = elements.size(); assertTrue("Root has " + elementSize + " children", (elements != null) && (elementSize == NUMELE)); } public void testPlainIteration() throws Exception { Element root = iterDocument.getRootElement(); List elements = root.elements("iterator test"); Iterator iter = root.elementIterator("iterator test"); int elementSize = elements.size(); int count = 0; for (; iter.hasNext();) { Element e = (Element) iter.next(); assertEquals("instance " + e.attribute("instance").getValue() + " equals " + count, e.attribute("instance").getValue(), Integer.toString(count)); count++; } assertTrue(elementSize + " elements iterated", count == elementSize); } public void testSkipAlternates() throws Exception { Element root = iterDocument.getRootElement(); List elements = root.elements("iterator test"); Iterator iter = root.elementIterator("iterator test"); int elementSize = elements.size(); int count = 0; for (; iter.hasNext();) { Element e = (Element) iter.next(); assertEquals("instance " + e.attribute("instance").getValue() + " equals " + (count * 2), e.attribute("instance") .getValue(), Integer.toString(count * 2)); iter.next(); count++; } assertTrue((elementSize / 2) + " alternate elements iterated", count == (elementSize / 2)); } public void testNoHasNext() throws Exception { Element root = iterDocument.getRootElement(); List elements = root.elements("iterator test"); Iterator iter = root.elementIterator("iterator test"); int elementSize = elements.size(); int count = 0; Element e = null; for (; count < elementSize;) { e = (Element) iter.next(); assertEquals("instance " + e.attribute("instance").getValue() + " equals " + count, e.attribute("instance").getValue(), Integer.toString(count)); System.out.println("instance " + e.attribute("instance").getValue() + " equals " + count); count++; } try { e = (Element) iter.next(); if (e != null) { // Real Iterators wouldn't get here assertTrue("no more elements,value instead is " + e.attribute("instance").getValue(), e == null); } } catch (Exception exp) { assertTrue("Real iterators throw NoSuchElementException", exp instanceof java.util.NoSuchElementException); } } public void testExtraHasNexts() throws Exception { Element root = iterDocument.getRootElement(); List elements = root.elements("iterator test"); Iterator iter = root.elementIterator("iterator test"); int elementSize = elements.size(); int count = 0; for (; iter.hasNext();) { Element e = (Element) iter.next(); assertEquals("instance " + e.attribute("instance").getValue() + " equals " + count, e.attribute("instance").getValue(), Integer.toString(count)); iter.hasNext(); count++; } assertTrue(elementSize + " elements iterated with extra hasNexts", count == elementSize); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/NamespaceTest.java0000644000175000017500000001436110242120024021025 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.dom4j.io.SAXReader; /** * A test harness to test the use of Namespaces. * * @author James Strachan * @version $Revision: 1.4 $ */ public class NamespaceTest extends AbstractTestCase { /** Input XML file to read */ private static final String INPUT_XML_FILE = "/xml/namespaces.xml"; /** Namespace to use in tests */ private static final Namespace XSL_NAMESPACE = Namespace.get("xsl", "http://www.w3.org/1999/XSL/Transform"); private static final QName XSL_TEMPLATE = QName.get("template", XSL_NAMESPACE); public static void main(String[] args) { TestRunner.run(NamespaceTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void debugShowNamespaces() throws Exception { Element root = getRootElement(); for (Iterator iter = root.elementIterator(); iter.hasNext();) { Element element = (Element) iter.next(); log("Found element: " + element); log("Namespace: " + element.getNamespace()); log("Namespace prefix: " + element.getNamespacePrefix()); log("Namespace URI: " + element.getNamespaceURI()); } } public void testGetElement() throws Exception { Element root = getRootElement(); Element firstTemplate = root.element(XSL_TEMPLATE); assertTrue( "Root element contains at least one element", firstTemplate != null); log("Found element: " + firstTemplate); } public void testGetElements() throws Exception { Element root = getRootElement(); List list = root.elements(XSL_TEMPLATE); assertTrue( "Root element contains at least one element", list.size() > 0); log("Found elements: " + list); } public void testElementIterator() throws Exception { Element root = getRootElement(); Iterator iter = root.elementIterator(XSL_TEMPLATE); assertTrue( "Root element contains at least one element", iter.hasNext()); do { Element element = (Element) iter.next(); log("Found element: " + element); } while (iter.hasNext()); } /** * Tests the use of namespace URI Mapping associated with a DocumentFactory * * @throws Exception * DOCUMENT ME! */ public void testNamespaceUriMap() throws Exception { // register namespace prefix->uri mappings with factory Map uris = new HashMap(); uris.put("x", "fooNamespace"); uris.put("y", "barNamespace"); DocumentFactory factory = new DocumentFactory(); factory.setXPathNamespaceURIs(uris); // parse or create a document SAXReader reader = new SAXReader(); reader.setDocumentFactory(factory); Document doc = getDocument("/xml/test/nestedNamespaces.xml", reader); // evaluate XPath using registered namespace prefixes // which do not appear in the document (though the URIs do!) String value = doc.valueOf("/x:pizza/y:cheese/x:pepper"); log("Found value: " + value); assertEquals("XPath used default namesapce URIS", "works", value); } // Implementation methods // ------------------------------------------------------------------------- protected void setUp() throws Exception { super.setUp(); document = getDocument(INPUT_XML_FILE); } /** * DOCUMENT ME! * * @return the root element of the document */ protected Element getRootElement() { Element root = document.getRootElement(); assertTrue("Document has root element", root != null); return root; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/DetachTest.java0000644000175000017500000001000410242120000020301 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; /** * A test harness to test the detach() method on root elements * * @author James Strachan * @version $Revision: 1.3 $ */ public class DetachTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(DetachTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testRoot() throws Exception { document.setName("doc1"); Element root = document.getRootElement(); assertTrue("Has root element", root != null); assertTrue("Root has no parent", root.getParent() == null); root.detach(); assertTrue("Detached root now has no document", root.getDocument() == null); assertTrue("Original doc now has no root element", document .getRootElement() == null); Document doc2 = DocumentHelper.createDocument(); doc2.setName("doc2"); assertTrue("Doc2 has no root element", doc2.getRootElement() == null); doc2.setRootElement(root); assertTrue("Doc2 has now has root element", doc2.getRootElement() == root); assertTrue("Root element now has document", root.getDocument() == doc2); Document doc3 = DocumentHelper.createDocument(); doc3.setName("doc3"); doc3.addElement("foo"); assertTrue("Doc3 has root element", doc3.getRootElement() != null); root = doc2.getRootElement(); root.detach(); doc3.setRootElement(root); assertTrue("Doc3 now has root element", doc3.getRootElement() == root); assertSame("Root element now has a document", root.getDocument(), doc3); assertTrue("Doc2 has no root element", doc2.getRootElement() == null); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/XMLResultTest.java0000644000175000017500000001017610242120024020770 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.io.StringWriter; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import org.dom4j.io.DocumentSource; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLResult; import org.dom4j.io.XMLWriter; /** * Test harness for the XMLResult which acts as a JAXP Result * * @author James Strachan * @version $Revision: 1.3 $ */ public class XMLResultTest extends AbstractTestCase { protected static final boolean VERBOSE = false; public static void main(String[] args) { TestRunner.run(XMLResultTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testWriter() throws Exception { // load a default transformer TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); // use dom4j document as the source Source source = new DocumentSource(document); // use pretty print format and a buffer for the result OutputFormat format = OutputFormat.createCompactFormat(); StringWriter buffer = new StringWriter(); Result result = new XMLResult(buffer, format); // now lets transform transformer.transform(source, result); String text = buffer.toString(); if (VERBOSE) { log("Using JAXP and XMLResult the document is:- "); log(text); } StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, format); writer.write(document); String text2 = out.toString(); if (VERBOSE) { log("Using XMLWriter the text is:-"); log(text2); } assertEquals("The text output should be identical", text2, text); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/IsTextOnlyTest.java0000644000175000017500000000606010242120013021206 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; /** * A test harness to test the parent relationship and use of the {@link * Node#asXPathResult} method. * * @author James Strachan * @version $Revision: 1.3 $ */ public class IsTextOnlyTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(IsTextOnlyTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testDocument() throws Exception { DocumentFactory factory = new DocumentFactory(); Element root = factory.createElement("root"); Element first = root.addElement("child"); first.addText("This is some text"); assertTrue("Root node is not text only: " + root, !root.isTextOnly()); assertTrue("First child is text only: " + first, first.isTextOnly()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/MakeElementTest.java0000644000175000017500000001056710242120021021321 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; /** * A test harness to test the DocumentHelper.makeElement() methodt * * @author James Strachan * @version $Revision: 1.3 $ */ public class MakeElementTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(MakeElementTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testMakeElement() throws Exception { Document doc = DocumentHelper.createDocument(); Element c = DocumentHelper.makeElement(doc, "a/b/c"); assertTrue("Should return a valid element", c != null); Element c2 = DocumentHelper.makeElement(doc, "a/b/c"); assertTrue("Found same element again", c == c2); c.addAttribute("x", "123"); Node found = doc.selectSingleNode("/a/b/c[@x='123']"); assertEquals("Found same node via XPath", c, found); Element b = c.getParent(); Element e = DocumentHelper.makeElement(b, "c/d/e"); assertTrue("Should return a valid element", e != null); Element e2 = DocumentHelper.makeElement(b, "c/d/e"); assertTrue("Found same element again", e == e2); e.addAttribute("y", "456"); found = b.selectSingleNode("c/d/e[@y='456']"); assertEquals("Found same node via XPath", e, found); } public void testMakeQualifiedElement() throws Exception { Document doc = DocumentHelper.createDocument(); Element root = doc.addElement("root"); root.addNamespace("", "defaultURI"); root.addNamespace("foo", "fooURI"); root.addNamespace("bar", "barURI"); Element c = DocumentHelper.makeElement(doc, "root/foo:b/bar:c"); assertTrue("Should return a valid element", c != null); assertEquals("c has a valid namespace", "barURI", c.getNamespaceURI()); Element b = c.getParent(); assertEquals("b has a valid namespace", "fooURI", b.getNamespaceURI()); log("Created: " + c); Element c2 = DocumentHelper.makeElement(doc, "root/foo:b/bar:c"); assertTrue("Found same element again", c == c2); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/io/0000755000175000017500000000000012133227266016051 5ustar ebourgebourgdom4j-1.6.1/src/test/org/dom4j/io/DTDTest.java0000644000175000017500000004706510242120014020161 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import junit.framework.AssertionFailedError; import junit.textui.TestRunner; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.dom4j.AbstractTestCase; import org.dom4j.Document; import org.dom4j.DocumentType; import org.dom4j.dtd.AttributeDecl; import org.dom4j.dtd.ElementDecl; import org.dom4j.dtd.ExternalEntityDecl; import org.dom4j.dtd.InternalEntityDecl; import org.dom4j.tree.DefaultDocumentType; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Tests the DocType functionality. * *

* Incorporated additional test cases for optional processing of the internal * and external DTD subsets. The "external" and "mixed" tests both fail * due to a reported bug. See http://tinyurl.com/4dzyq *

* * @author James Strachan * @version $Revision: 1.4 $ */ public class DTDTest extends AbstractTestCase { /** * Input XML file to read xml/dtd/internal.xml- document * using internal DTD subset, but no external DTD subset. */ private static final String XML_INTERNAL_FILE = "xml/dtd/internal.xml"; /** * Input XML file to read xml/dtd/external.xml- document * using external DTD subset, but no internal DTD subset. The external * entity should be locatable by either PUBLIC or SYSTEM identifier. The * testing harness should use an appropriate EntityResolver to locate the * external entity as a local resource (no internet access). */ private static final String XML_EXTERNAL_FILE = "xml/dtd/external.xml"; /** * Input XML file to read xml/dtd/mixed.xml- document using * both an internal and an external DTD subset. The external entity should * be locatable by either PUBLIC or SYSTEM identifier. The testing harness * should use an appropriate EntityResolver to locate the external entity as * a local resource (no internet access). */ private static final String XML_MIXED = "xml/dtd/mixed.xml"; /** * Input XML file to for {@linkEntityResolver} * xml/dtd/sample.dtd- the external entity providing the * external DTD subset for test cases that need one. The SYSTEM identifier * for this external entity is given by {@link#DTD_SYSTEM_ID}. */ private static final String DTD_FILE = "xml/dtd/sample.dtd"; /** * The PUBLIC identifier, which is -//dom4j//DTD sample, for * the external entity providing DTD for tests. */ protected static final String DTD_PUBLICID = "-//dom4j//DTD sample"; /** * The SYSTEM identifier, which is sample.dtd, for the * external entity providing DTD for tests. */ protected static final String DTD_SYSTEM_ID = "sample.dtd"; public static void main(String[] args) { TestRunner.run(DTDTest.class); } // Test case(s) // ------------------------------------------------------------------------- /** * Test verifies correct identification of the internal DTD subset and * correct non-presence of the external DTD subset. * * @throws Exception * DOCUMENT ME! */ public void testInternalDTDSubset() throws Exception { /* * Setup the expected DocumentType. * * @todo dom4j should expose a DefaultDocumentType constructor that * accepts only the elementName property. This is used when only an * internal DTD subset is being provided via the * syntax, in which case there is neither a SYSTEM nor PUBLIC * identifier. */ DocumentType expected = new DefaultDocumentType(); expected.setElementName("greeting"); expected.setInternalDeclarations(getInternalDeclarations()); /* * Parse the test XML document and compare the expected and actual * DOCTYPEs. */ try { assertSameDocumentType(expected, readDocument( XML_INTERNAL_FILE, true, false).getDocType()); } catch (AssertionFailedError ex) { throw ex; } catch (Throwable t) { fail("Not expecting: " + t); } } /** * Test verifies correct identification of the external DTD subset and * correct non-presence of the internal DTD subset. */ public void testExternalDTDSubset() { /* * Setup the expected DocumentType. */ DocumentType expected = new DefaultDocumentType("another-greeting", null, DTD_SYSTEM_ID); expected.setExternalDeclarations(getExternalDeclarations()); /* * Parse the test XML document and compare the expected and actual * DOCTYPEs. */ try { assertSameDocumentType(expected, readDocument( XML_EXTERNAL_FILE, false, true).getDocType()); } catch (AssertionFailedError ex) { throw ex; } catch (Throwable t) { fail("Not expecting: " + t); } } /** * Test verifies correct identification of the internal and external DTD * subsets. */ public void testMixedDTDSubset() { /* * Setup the expected DocumentType. */ DocumentType expected = new DefaultDocumentType("another-greeting", null, DTD_SYSTEM_ID); expected.setInternalDeclarations(getInternalDeclarations()); expected.setExternalDeclarations(getExternalDeclarations()); /* * Parse the test XML document and compare the expected and actual * DOCTYPEs. */ try { assertSameDocumentType(expected, readDocument(XML_MIXED, true, true).getDocType()); } catch (AssertionFailedError ex) { throw ex; } catch (Throwable t) { fail("Not expecting: " + t); } } // Implementation methods // ------------------------------------------------------------------------- /** * Test helper method returns a {@link List}of DTD declarations that * represents the expected internal DTD subset (for the tests that use an * internal DTD subset). * *

* Note: The declarations returned by this method MUST agree those actually * declared in {@link #XML_INTERNAL_FILE}and {@link * #XML_MIXED}. *

* *

*

* * @return DOCUMENT ME! */ protected List getInternalDeclarations() { List decls = new ArrayList(); decls.add(new ElementDecl("greeting", "(#PCDATA)")); decls.add(new AttributeDecl("greeting", "foo", "ID", "#IMPLIED", null)); decls.add(new InternalEntityDecl("%boolean", "( true | false )")); return decls; } /** * Test helper method returns a {@link List}of DTD declarations that * represents the expected external DTD subset (for the tests that use an * external DTD subset). * * @return DOCUMENT ME! */ protected List getExternalDeclarations() { List decls = new ArrayList(); decls.add(new ElementDecl("another-greeting", "(#PCDATA)")); return decls; } /** * Test helper method compares the expected and actual {@link DocumentType} * objects, including their internal and external DTD subsets. * *

*

* * @param expected * DOCUMENT ME! * @param actual * DOCUMENT ME! */ protected void assertSameDocumentType(DocumentType expected, DocumentType actual) { /* * Nothing expected? */ if (expected == null) { if (actual == null) { return; // Nothing found. } else { fail("Not expecting DOCTYPE."); } } else { /* * Something expected. */ if (actual == null) { fail("Expecting DOCTYPE"); } log("Expected DocumentType:\n" + expected.toString()); log("Actual DocumentType:\n" + actual.toString()); // Check the internal DTD subset. assertSameDTDSubset("Internal", expected.getInternalDeclarations(), actual.getInternalDeclarations()); // Check the external DTD subset. assertSameDTDSubset("External", expected.getExternalDeclarations(), actual.getExternalDeclarations()); } } /** * Test helper method compares an expected set of DTD declarations with an * actual set of DTD declarations. This method should be invoked seperately * for the internal DTD subset and the external DTD subset. The declarations * must occur in their logical ordering. See Lexical Handler for conformance * criteria. * * @param txt * DOCUMENT ME! * @param expected * DOCUMENT ME! * @param actual * DOCUMENT ME! * * @throws AssertionError * DOCUMENT ME! */ protected void assertSameDTDSubset(String txt, List expected, List actual) { /* * Nothing expected? */ if (expected == null) { if (actual == null) { return; // Nothing found. } else { fail("Not expecting " + txt + " DTD subset."); } } else { /* * Something expected. */ if (actual == null) { fail("Expecting " + txt + " DTD subset."); } /* * Correct #of declarations found? */ assertEquals(txt + " DTD subset has correct #of declarations" + ": expected=[" + expected.toString() + "]" + ", actual=[" + actual.toString() + "]", expected.size(), actual.size()); /* * Check order, type, and values of each declaration. Serialization * tests are done separately. */ Iterator itr1 = expected.iterator(); Iterator itr2 = actual.iterator(); while (itr1.hasNext()) { Object obj1 = itr1.next(); Object obj2 = itr2.next(); assertEquals(txt + " DTD subset: Same type of declaration", obj1.getClass().getName(), obj2.getClass().getName()); if (obj1 instanceof AttributeDecl) { assertSameDecl((AttributeDecl) obj1, (AttributeDecl) obj2); } else if (obj1 instanceof ElementDecl) { assertSameDecl((ElementDecl) obj1, (ElementDecl) obj2); } else if (obj1 instanceof InternalEntityDecl) { assertSameDecl((InternalEntityDecl) obj1, (InternalEntityDecl) obj2); } else if (obj1 instanceof ExternalEntityDecl) { assertSameDecl((ExternalEntityDecl) obj1, (ExternalEntityDecl) obj2); } else { throw new AssertionError("Unexpected declaration type: " + obj1.getClass()); } } } } /** * Test helper method compares an expected and an actual {@link * AttributeDecl}. * * @param expected * DOCUMENT ME! * @param actual * DOCUMENT ME! */ public void assertSameDecl(AttributeDecl expected, AttributeDecl actual) { assertEquals("attributeName is correct", expected.getAttributeName(), actual.getAttributeName()); assertEquals("elementName is correct", expected.getElementName(), actual.getElementName()); assertEquals("type is correct", expected.getType(), actual.getType()); assertEquals("value is not correct", expected.getValue(), actual .getValue()); assertEquals("valueDefault is correct", expected.getValueDefault(), actual.getValueDefault()); assertEquals("toString() is correct", expected.toString(), actual .toString()); } /** * Test helper method compares an expected and an actual {@link * ElementDecl}. * * @param expected * DOCUMENT ME! * @param actual * DOCUMENT ME! */ protected void assertSameDecl(ElementDecl expected, ElementDecl actual) { assertEquals("name is correct", expected.getName(), actual.getName()); assertEquals("model is not correct", expected.getModel(), actual .getModel()); assertEquals("toString() is correct", expected.toString(), actual .toString()); } /** * Test helper method compares an expected and an actual {@link * InternalEntityDecl}. * * @param expected * DOCUMENT ME! * @param actual * DOCUMENT ME! */ protected void assertSameDecl(InternalEntityDecl expected, InternalEntityDecl actual) { assertEquals("name is correct", expected.getName(), actual.getName()); assertEquals("value is not correct", expected.getValue(), actual .getValue()); assertEquals("toString() is correct", expected.toString(), actual .toString()); } /** * Test helper method compares an expected and an actual {@link * ExternalEntityDecl}. * * @param expected * DOCUMENT ME! * @param actual * DOCUMENT ME! */ protected void assertSameDecl(ExternalEntityDecl expected, ExternalEntityDecl actual) { assertEquals("name is correct", expected.getName(), actual.getName()); assertEquals("publicID is correct", expected.getPublicID(), actual .getPublicID()); assertEquals("systemID is correct", expected.getSystemID(), actual .getSystemID()); assertEquals("toString() is correct", expected.toString(), actual .toString()); } /** * Helper method reads a local resource and parses it as an XML document. * The internal and external DTD subsets are optionally retained by the * parser and exposed via the {@link DocumentType}object on the returned * {@link Document}. The parser is configured with an {@link * EntityResolver}that knows how to find the local resource identified by * {@link #DTD_FILE}whose SYSTEM identifier is given by {@link * #DTD_SYSTEM_ID}. * * @param resourceName * DOCUMENT ME! * @param includeInternal * DOCUMENT ME! * @param includeExternal * DOCUMENT ME! * * @return DOCUMENT ME! * * @throws Exception * DOCUMENT ME! */ protected Document readDocument(String resourceName, boolean includeInternal, boolean includeExternal) throws Exception { SAXReader reader = new SAXReader(); reader.setIncludeInternalDTDDeclarations(includeInternal); reader.setIncludeExternalDTDDeclarations(includeExternal); reader.setEntityResolver(new MyEntityResolver(DTD_FILE, DTD_PUBLICID, DTD_SYSTEM_ID)); return getDocument(resourceName, reader); } /** * Provides a resolver for the local test DTD resource. */ protected static class MyEntityResolver implements EntityResolver { private String resourceName; private String pubId; private String sysId; public MyEntityResolver(String localResourceName, String publicId, String systemId) { resourceName = localResourceName; sysId = systemId; } public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (pubId != null) { if (pubId.equals(publicId)) { return new InputSource(getInputStream(resourceName)); } } if (sysId.equals(systemId)) { return new InputSource(getInputStream(resourceName)); } else { return null; } } /** * Returns an {@link InputStream}that will read from the indicated * local resource. * * @param localResourceName * DOCUMENT ME! * * @return DOCUMENT ME! * * @throws IOException * DOCUMENT ME! */ protected InputStream getInputStream(String localResourceName) throws IOException { InputStream is = new FileInputStream(localResourceName); return is; } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/io/DocumentSourceTest.java0000644000175000017500000000663110242120003022475 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import junit.textui.TestRunner; import java.io.StringWriter; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import org.dom4j.AbstractTestCase; import org.dom4j.Document; import org.dom4j.DocumentHelper; /** * DOCUMENT ME! * * @author Maarten Coene */ public class DocumentSourceTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(DocumentSourceTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testBug555549() throws Exception { // simulate String xml = "line1" + (char) 13 + (char) 10 + "line2"; Document doc = DocumentHelper.parseText(xml); TransformerFactory tf = TransformerFactory.newInstance(); Transformer txml = tf.newTransformer(); StringWriter writer = new StringWriter(); txml.transform(new DocumentSource(doc), new StreamResult(writer)); System.out.println(writer.toString()); assertTrue(writer.toString().indexOf(" ") == -1); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/io/DOMReaderTest.java0000644000175000017500000000721510242120016021303 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import junit.textui.TestRunner; import java.io.ByteArrayInputStream; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.dom4j.AbstractTestCase; /** * DOCUMENT ME! * * @author Maarten */ public class DOMReaderTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(DOMReaderTest.class); } public void testBug972737() throws Exception { String xml = "" + " " + " " + " " + " " + " " + " " + ""; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(xml .getBytes())); DOMReader reader = new DOMReader(); org.dom4j.Document dom4jDoc = reader.read(doc); List namespaces = dom4jDoc.getRootElement().declaredNamespaces(); assertEquals(2, namespaces.size()); System.out.println(dom4jDoc.asXML()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/io/DOMWriterTest.java0000644000175000017500000001053310242120020021345 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import junit.textui.TestRunner; import java.io.StringWriter; import org.dom4j.AbstractTestCase; import org.w3c.dom.NamedNodeMap; /** * DOCUMENT ME! * * @author Maarten */ public class DOMWriterTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(DOMWriterTest.class); } public void testNamespaceBug() throws Exception { org.dom4j.Document doc = getDocument("/xml/namespaces.xml"); DOMWriter writer = new DOMWriter(org.dom4j.dom.DOMDocument.class); org.w3c.dom.Document result = writer.write(doc); NamedNodeMap atts = result.getDocumentElement().getAttributes(); assertEquals(4, atts.getLength()); XMLWriter wr = new XMLWriter(); wr.setOutputStream(System.out); wr.write((org.dom4j.Document) result); } public void testBug905745() throws Exception { org.dom4j.Document doc = getDocument("/xml/namespaces.xml"); DOMWriter writer = new DOMWriter(); org.w3c.dom.Document result = writer.write(doc); NamedNodeMap atts = result.getDocumentElement().getAttributes(); org.w3c.dom.Node versionAttr = atts.getNamedItem("version"); assertNotNull(versionAttr); assertNotNull(versionAttr.getLocalName()); assertEquals("version", versionAttr.getLocalName()); assertEquals("version", versionAttr.getNodeName()); } public void testBug926752() throws Exception { org.dom4j.Document doc = getDocument("/xml/test/defaultNamespace.xml"); DOMWriter writer = new DOMWriter(org.dom4j.dom.DOMDocument.class); org.w3c.dom.Document result = writer.write(doc); NamedNodeMap atts = result.getDocumentElement().getAttributes(); assertEquals(1, atts.getLength()); OutputFormat format = OutputFormat.createCompactFormat(); format.setSuppressDeclaration(true); XMLWriter wr = new XMLWriter(format); StringWriter strWriter = new StringWriter(); wr.setWriter(strWriter); wr.write((org.dom4j.Document) result); assertEquals("Hello", strWriter.toString()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/io/SAXReaderTest.java0000644000175000017500000001272210242120010021310 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import junit.textui.TestRunner; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.StringReader; import java.io.StringWriter; import java.util.List; import org.dom4j.AbstractTestCase; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; /** * A test harness to test the content API in DOM4J * * @author Maarten Coene */ public class SAXReaderTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(SAXReaderTest.class); } // Test case(s) // ------------------------------------------------------------------------- /** * Test bug reported by Christian Oetterli http://tinyurl.com/6po8v * * @throws Exception * DOCUMENT ME! */ public void testReadFile() throws Exception { File file = getFile("/xml/#.xml"); new SAXReader().read(file); } public void testEncoding() throws Exception { String xml = ""; SAXReader reader = new SAXReader(); reader.setEncoding("ISO-8859-1"); Document doc = reader.read(new StringReader(xml)); assertEquals("encoding incorrect", "ISO-8859-1", doc.getXMLEncoding()); } public void testRussian() throws Exception { Document doc = getDocument("/xml/russArticle.xml"); assertEquals("encoding not correct", "koi8-r", doc.getXMLEncoding()); Element el = doc.getRootElement(); StringWriter writer = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(writer); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("koi8-r"); xmlWriter.write(doc); log(writer.toString()); } public void testRussian2() throws Exception { Document doc = getDocument("/xml/russArticle.xml"); XMLWriter xmlWriter = new XMLWriter(new OutputFormat("", false, "koi8-r")); ByteArrayOutputStream out = new ByteArrayOutputStream(); xmlWriter.setOutputStream(out); xmlWriter.write(doc); xmlWriter.flush(); xmlWriter.close(); log(out.toString()); } public void testBug833765() throws Exception { SAXReader reader = new SAXReader(); reader.setIncludeExternalDTDDeclarations(true); getDocument("/xml/dtd/external.xml", reader); } public void testBug527062() throws Exception { Document doc = getDocument("/xml/test/test.xml"); List l = doc.selectNodes("//broked/junk"); for (int i = 0; i < l.size(); i++) { System.out.println("Found node: " + ((Element) l.get(i)).getStringValue()); } assertEquals("hi there", ((Element) l.get(0)).getStringValue()); assertEquals("hello world", ((Element) l.get(1)).getStringValue()); } public void testEscapedComment() throws Exception { String txt = "<!-- <head> & <body> -->"; Document doc = DocumentHelper.parseText(txt); Element eg = doc.getRootElement(); System.out.println(doc.asXML()); assertEquals("", eg.getText()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/io/DispatchHandlerTest.java0000644000175000017500000000631410242120020022570 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import junit.textui.TestRunner; import org.dom4j.AbstractTestCase; import org.dom4j.ElementHandler; /** * DOCUMENT ME! * * @author Maarten Coene */ public class DispatchHandlerTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(DispatchHandlerTest.class); } public void testBug611445() throws Exception { MyHandler handler = new MyHandler(); SAXReader reader = new SAXReader(); reader.addHandler("/products/product/colour", handler); reader.read(getFile("/xml/test/sample.xml")); assertEquals(3, handler.getCount()); reader.read(getFile("/xml/test/sample.xml")); assertEquals(6, handler.getCount()); } private static class MyHandler implements ElementHandler { private int count = 0; public void onEnd(org.dom4j.ElementPath elementPath) { } public void onStart(org.dom4j.ElementPath elementPath) { count++; } int getCount() { return count; } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/io/XPP3ReaderTest.java0000644000175000017500000000755510242120016021425 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import junit.textui.TestRunner; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.StringWriter; import org.dom4j.AbstractTestCase; import org.dom4j.Document; import org.dom4j.Element; /** * Test class for the XPP3Reader. This is based on the TestSaxReader class. * * @author Pelle Braendgaard * @author Maarten Coene */ public class XPP3ReaderTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(XPP3ReaderTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testRussian() throws Exception { File file = getFile("/xml/russArticle.xml"); XPP3Reader xmlReader = new XPP3Reader(); Document doc = xmlReader.read(file); Element el = doc.getRootElement(); StringWriter writer = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(writer); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("koi8-r"); xmlWriter.write(doc); log(writer.toString()); } public void testRussian2() throws Exception { File file = getFile("/xml/russArticle.xml"); XPP3Reader xmlReader = new XPP3Reader(); Document doc = xmlReader.read(file); XMLWriter xmlWriter = new XMLWriter(new OutputFormat("", false, "koi8-r")); ByteArrayOutputStream out = new ByteArrayOutputStream(); xmlWriter.setOutputStream(out); xmlWriter.write(doc); xmlWriter.flush(); xmlWriter.close(); log(out.toString()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/io/StaxTest.java0000644000175000017500000001025410242117776020500 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import junit.textui.TestRunner; import java.io.File; import java.io.FileReader; import java.io.StringWriter; import javax.xml.stream.XMLInputFactory; import org.dom4j.AbstractTestCase; import org.dom4j.Document; /** * Tests STAX->DOM4J functionality. * * @author Maarten Coene * @author Christian Niles */ public class StaxTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(StaxTest.class); } // Test case(s) // ------------------------------------------------------------------------- /** * Tests that the encoding specified in the XML declaration is exposed in * the Document read via StAX, and also that it gets output when writing. */ public void testEncoding() { /* * only execute if a reference implementation is available */ try { XMLInputFactory.newInstance(); } catch (javax.xml.stream.FactoryConfigurationError e) { // no implementation found, stop the test. return; } try { File file = getFile("/xml/russArticle.xml"); STAXEventReader xmlReader = new STAXEventReader(); Document doc = xmlReader.readDocument(new FileReader(file)); assertEquals("russArticle.xml encoding wasn't correct", "koi8-r", doc.getXMLEncoding()); StringWriter writer = new StringWriter(); STAXEventWriter xmlWriter = new STAXEventWriter(writer); xmlWriter.writeDocument(doc); String output = writer.toString(); String xmlDecl = output.substring(0, output.indexOf("?>") + 2); String expected = ""; assertEquals("Unexpected xml declaration", expected, xmlDecl); System.out.println(output); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/io/WriteUnmergedTextTest.java0000644000175000017500000001541210242120005023163 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import junit.textui.TestRunner; import java.io.StringReader; import java.io.StringWriter; import org.dom4j.AbstractTestCase; import org.dom4j.Document; /** * A simple test harness to check that the XML Writer works * * @author James Strachan * @version $Revision: 1.3 $ */ public class WriteUnmergedTextTest extends AbstractTestCase { protected static final boolean VERBOSE = true; private String inputText = "" + "Test using < " + "& >"; public static void main(String[] args) { TestRunner.run(WriteUnmergedTextTest.class); } // Test case(s) // ------------------------------------------------------------------------- public String readwriteText(OutputFormat outFormat, boolean mergeAdjacentText) throws Exception { StringWriter out = new StringWriter(); StringReader in = new StringReader(inputText); SAXReader reader = new SAXReader(); // reader.setValidation(true); reader.setMergeAdjacentText(mergeAdjacentText); Document document = reader.read(in); XMLWriter writer = (outFormat == null) ? new XMLWriter(out) : new XMLWriter(out, outFormat); writer.write(document); writer.close(); String outText = out.toString(); return outText; } public void testWithoutFormatNonMerged() throws Exception { String outText = readwriteText(null, false); if (VERBOSE) { log("Text output is ["); log(outText); log("]. Done"); } // should contain & and < assertTrue("Output text contains \"&\"", outText .lastIndexOf("&") >= 0); assertTrue("Output text contains \"<\"", outText.lastIndexOf("<") >= 0); } public void testWithCompactFormatNonMerged() throws Exception { String outText = readwriteText(OutputFormat.createCompactFormat(), false); if (VERBOSE) { log("Text output is ["); log(outText); log("]. Done"); } // should contain & and < assertTrue("Output text contains \"&\"", outText .lastIndexOf("&") >= 0); assertTrue("Output text contains \"<\"", outText.lastIndexOf("<") >= 0); } public void testWithPrettyPrintFormatNonMerged() throws Exception { String outText = readwriteText(OutputFormat.createPrettyPrint(), false); if (VERBOSE) { log("Text output is ["); log(outText); log("]. Done"); } // should contain & and < assertTrue("Output text contains \"&\"", outText .lastIndexOf("&") >= 0); assertTrue("Output text contains \"<\"", outText.lastIndexOf("<") >= 0); } public void testWithoutFormatMerged() throws Exception { String outText = readwriteText(null, true); if (VERBOSE) { log("Text output is ["); log(outText); log("]. Done"); } // should contain & and < assertTrue("Output text contains \"&\"", outText .lastIndexOf("&") >= 0); assertTrue("Output text contains \"<\"", outText.lastIndexOf("<") >= 0); } public void testWithCompactFormatMerged() throws Exception { String out = readwriteText(OutputFormat.createCompactFormat(), true); if (VERBOSE) { log("Text output is ["); log(out); log("]. Done"); } // should contain & and < assertTrue("Output text contains \"&\"", out .lastIndexOf("&") >= 0); assertTrue("Output text contains \"<\"", out.lastIndexOf("<") >= 0); } public void testWithPrettyPrintFormatMerged() throws Exception { String outText = readwriteText(OutputFormat.createPrettyPrint(), true); if (VERBOSE) { log("Text output is ["); log(outText); log("]. Done"); } // should contain & and < assertTrue("Output text contains \"&\"", outText .lastIndexOf("&") >= 0); assertTrue("Output text contains \"<\"", outText.lastIndexOf("<") >= 0); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/ProcessingInstructionTest.java0000644000175000017500000000622210242120022023502 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.Map; /** * DOCUMENT ME! * * @author kralik * @author Maarten Coene */ public class ProcessingInstructionTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(ProcessingInstructionTest.class); } public void testParseValues() { String data = " abc='123' def=\"2!=3\" ghi=' 4 = '"; ProcessingInstruction pi = DocumentHelper.createProcessingInstruction( "pi", data); Map values = pi.getValues(); assertEquals(3, values.size()); assertEquals("123", pi.getValue("abc")); assertEquals("2!=3", pi.getValue("def")); assertEquals(" 4 = ", pi.getValue("ghi")); } public void testBug787428() { String data = "xpath=\"/abc/cde[@id='qqq']\""; ProcessingInstruction pi = DocumentHelper.createProcessingInstruction( "merge", data); assertEquals("/abc/cde[@id='qqq']", pi.getValue("xpath")); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/XMLWriterTest.java0000644000175000017500000005164110242120023020767 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.StringReader; import java.io.StringWriter; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.dom4j.tree.BaseElement; import org.dom4j.tree.DefaultDocument; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * A simple test harness to check that the XML Writer works * * @author James Strachan * @version $Revision: 1.7.2.1 $ */ public class XMLWriterTest extends AbstractTestCase { protected static final boolean VERBOSE = false; public static void main(String[] args) { TestRunner.run(XMLWriterTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testBug1180791() throws Exception { String xml = "bar"; SAXReader reader = new SAXReader(); Document doc = reader.read(new StringReader(xml)); // of with newlines OutputFormat format = new OutputFormat(); format.setNewlines(true); //format.setTrimText(true); // first time StringWriter writer = new StringWriter(); XMLWriter xmlwriter = new XMLWriter(writer, format); xmlwriter.write(doc); System.out.println(writer.toString()); // 2nd time doc = reader.read(new StringReader(writer.toString())); writer = new StringWriter(); xmlwriter = new XMLWriter(writer, format); xmlwriter.write(doc); System.out.println(writer.toString()); } public void testBug1119733() throws Exception { Document doc = DocumentHelper .parseText("foo bar"); StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint()); writer.write(doc); writer.close(); String xml = out.toString(); System.out.println(xml); assertEquals("whitespace problem", -1, xml.indexOf("bar")); } public void testBug1119733WithSAXEvents() throws Exception { StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint()); writer.startDocument(); writer.startElement(null, "root", "root", new AttributesImpl()); writer.startElement(null, "code", "code", new AttributesImpl()); writer.characters(new char[] { 'f', 'o', 'o' }, 0, 3); writer.endElement(null, "code", "code"); writer.characters(new char[] { ' ', 'b', 'a', 'r' }, 0, 4); writer.endElement(null, "root", "root"); writer.endDocument(); writer.close(); String xml = out.toString(); System.out.println(xml); assertEquals("whitespace problem", -1, xml.indexOf("bar")); } public void testWriter() throws Exception { Object object = document; StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out); writer.write(object); writer.close(); String text = out.toString(); if (VERBOSE) { log("Text output is ["); log(text); log("]. Done"); } assertTrue("Output text is bigger than 10 characters", text.length() > 10); } public void testEncodingFormats() throws Exception { testEncoding("UTF-8"); testEncoding("UTF-16"); testEncoding("ISO-8859-1"); } public void testWritingEmptyElement() throws Exception { Document doc = DocumentFactory.getInstance().createDocument(); Element grandFather = doc.addElement("grandfather"); Element parent1 = grandFather.addElement("parent"); Element child1 = parent1.addElement("child1"); Element child2 = parent1.addElement("child2"); child2.setText("test"); Element parent2 = grandFather.addElement("parent"); Element child3 = parent2.addElement("child3"); child3.setText("test"); StringWriter buffer = new StringWriter(); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(buffer, format); writer.write(doc); String xml = buffer.toString(); System.out.println(xml); assertTrue("child2 not present", xml.indexOf("test") != -1); } protected void testEncoding(String encoding) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(encoding); XMLWriter writer = new XMLWriter(out, format); writer.write(document); writer.close(); log("Wrote to encoding: " + encoding); } public void testWriterBug() throws Exception { Element project = new BaseElement("project"); Document doc = new DefaultDocument(project); ByteArrayOutputStream out = new ByteArrayOutputStream(); XMLWriter writer = new XMLWriter(out, new OutputFormat("\t", true, "ISO-8859-1")); writer.write(doc); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); SAXReader reader = new SAXReader(); Document doc2 = reader.read(in); assertTrue("Generated document has a root element", doc2 .getRootElement() != null); assertEquals("Generated document has corrent named root element", doc2 .getRootElement().getName(), "project"); } public void testNamespaceBug() throws Exception { Document doc = DocumentHelper.createDocument(); Element root = doc.addElement("root", "ns1"); Element child1 = root.addElement("joe", "ns2"); child1.addElement("zot", "ns1"); StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint()); writer.write(doc); String text = out.toString(); // System.out.println( "Generated:" + text ); Document doc2 = DocumentHelper.parseText(text); root = doc2.getRootElement(); assertEquals("root has incorrect namespace", "ns1", root .getNamespaceURI()); Element joe = (Element) root.elementIterator().next(); assertEquals("joe has correct namespace", "ns2", joe.getNamespaceURI()); Element zot = (Element) joe.elementIterator().next(); assertEquals("zot has correct namespace", "ns1", zot.getNamespaceURI()); } /** * This test harness was supplied by Lari Hotari * * @throws Exception DOCUMENT ME! */ public void testContentHandler() throws Exception { StringWriter out = new StringWriter(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("iso-8859-1"); XMLWriter writer = new XMLWriter(out, format); generateXML(writer); writer.close(); String text = out.toString(); if (VERBOSE) { log("Created XML"); log(text); } // now lets parse the output and test it with XPath Document doc = DocumentHelper.parseText(text); String value = doc.valueOf("/processes[@name='arvojoo']"); assertEquals("Document contains the correct text", "jeejee", value); } /** * This test was provided by Manfred Lotz * * @throws Exception DOCUMENT ME! */ public void testWhitespaceBug() throws Exception { String notes = " This is a multiline\n\rentry"; Document doc = DocumentHelper.parseText(notes); OutputFormat format = new OutputFormat(); format.setEncoding("UTF-8"); format.setIndentSize(4); format.setNewlines(true); format.setTrimText(true); format.setExpandEmptyElements(true); StringWriter buffer = new StringWriter(); XMLWriter writer = new XMLWriter(buffer, format); writer.write(doc); String xml = buffer.toString(); log(xml); Document doc2 = DocumentHelper.parseText(xml); String text = doc2.valueOf("/notes"); String expected = "This is a multiline entry"; assertEquals("valueOf() returns the correct text padding", expected, text); assertEquals("getText() returns the correct text padding", expected, doc2.getRootElement().getText()); } /** * This test was provided by Manfred Lotz * * @throws Exception DOCUMENT ME! */ public void testWhitespaceBug2() throws Exception { Document doc = DocumentHelper.createDocument(); Element root = doc.addElement("root"); Element meaning = root.addElement("meaning"); meaning.addText("to li"); meaning.addText("ve"); OutputFormat format = new OutputFormat(); format.setEncoding("UTF-8"); format.setIndentSize(4); format.setNewlines(true); format.setTrimText(true); format.setExpandEmptyElements(true); StringWriter buffer = new StringWriter(); XMLWriter writer = new XMLWriter(buffer, format); writer.write(doc); String xml = buffer.toString(); log(xml); Document doc2 = DocumentHelper.parseText(xml); String text = doc2.valueOf("/root/meaning"); String expected = "to live"; assertEquals("valueOf() returns the correct text padding", expected, text); assertEquals("getText() returns the correct text padding", expected, doc2.getRootElement().element("meaning").getText()); } public void testPadding() throws Exception { Document doc = DocumentFactory.getInstance().createDocument(); Element root = doc.addElement("root"); root.addText("prefix "); root.addElement("b"); root.addText(" suffix"); OutputFormat format = new OutputFormat("", false); format.setOmitEncoding(true); format.setSuppressDeclaration(true); format.setExpandEmptyElements(true); format.setPadText(true); format.setTrimText(true); StringWriter buffer = new StringWriter(); XMLWriter writer = new XMLWriter(buffer, format); writer.write(doc); String xml = buffer.toString(); System.out.println("xml: " + xml); String expected = "prefix suffix"; assertEquals(expected, xml); } public void testPadding2() throws Exception { Document doc = DocumentFactory.getInstance().createDocument(); Element root = doc.addElement("root"); root.addText("prefix"); root.addElement("b"); root.addText("suffix"); OutputFormat format = new OutputFormat("", false); format.setOmitEncoding(true); format.setSuppressDeclaration(true); format.setExpandEmptyElements(true); format.setPadText(true); format.setTrimText(true); StringWriter buffer = new StringWriter(); XMLWriter writer = new XMLWriter(buffer, format); writer.write(doc); String xml = buffer.toString(); System.out.println("xml: " + xml); String expected = "prefixsuffix"; assertEquals(expected, xml); } /* * This must be tested manually to see if the layout is correct. */ public void testPrettyPrinting() throws Exception { Document doc = DocumentFactory.getInstance().createDocument(); doc.addElement("summary").addAttribute("date", "6/7/8").addElement( "orderline").addText("puffins").addElement("ranjit") .addComment("Ranjit is a happy Puffin"); XMLWriter writer = new XMLWriter(System.out, OutputFormat .createPrettyPrint()); writer.write(doc); doc = DocumentFactory.getInstance().createDocument(); doc.addElement("summary").addAttribute("date", "6/7/8").addElement( "orderline").addText("puffins").addElement("ranjit") .addComment("Ranjit is a happy Puffin").addComment( "another comment").addElement("anotherElement"); writer.write(doc); } public void testAttributeQuotes() throws Exception { Document doc = DocumentFactory.getInstance().createDocument(); doc.addElement("root").addAttribute("test", "text with ' in it"); StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, OutputFormat .createCompactFormat()); writer.write(doc); String expected = "\n" + ""; assertEquals(expected, out.toString()); } public void testBug868408() throws Exception { Document doc = getDocument("/xml/web.xml"); Document doc2 = DocumentHelper.parseText(doc.asXML()); assertEquals(doc.asXML(), doc2.asXML()); } public void testBug923882() throws Exception { Document doc = DocumentFactory.getInstance().createDocument(); Element root = doc.addElement("root"); root.addText("this is "); root.addText(" sim"); root.addText("ple text "); root.addElement("child"); root.addText(" contai"); root.addText("ning spaces and"); root.addText(" multiple textnodes"); OutputFormat format = new OutputFormat(); format.setEncoding("UTF-8"); format.setIndentSize(4); format.setNewlines(true); format.setTrimText(true); format.setExpandEmptyElements(true); StringWriter buffer = new StringWriter(); XMLWriter writer = new XMLWriter(buffer, format); writer.write(doc); String xml = buffer.toString(); log(xml); int start = xml.indexOf("") + 6; String eol = "\n"; // System.getProperty("line.separator"); String expected = "this is simple text" + eol + " containing spaces and multiple textnodes" + eol + ""; System.out.println("Expected:"); System.out.println(expected); System.out.println("Obtained:"); System.out.println(xml.substring(start, end)); assertEquals(expected, xml.substring(start, end)); } public void testEscapeXML() throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); OutputFormat format = new OutputFormat(null, false, "ISO-8859-2"); format.setSuppressDeclaration(true); XMLWriter writer = new XMLWriter(os, format); Document document = DocumentFactory.getInstance().createDocument(); Element root = document.addElement("root"); root.setText("bla &#c bla"); writer.write(document); String result = os.toString(); System.out.println(result); Document doc2 = DocumentHelper.parseText(result); doc2.normalize(); // merges adjacant Text nodes System.out.println(doc2.getRootElement().getText()); assertNodesEqual(document, doc2); } public void testWriteEntities() throws Exception { String xml = "\n" + " " + " " + " " + " " + " " + " " + " " + " " + " " + " ]>\n" + ""; SAXReader reader = new SAXReader("org.apache.xerces.parsers.SAXParser"); reader.setIncludeInternalDTDDeclarations(true); Document doc = reader.read(new StringReader(xml)); StringWriter wr = new StringWriter(); XMLWriter writer = new XMLWriter(wr); writer.write(doc); String xml2 = wr.toString(); System.out.println(xml2); Document doc2 = DocumentHelper.parseText(xml2); assertNodesEqual(doc, doc2); } public void testEscapeChars() throws Exception { Document document = DocumentFactory.getInstance().createDocument(); Element root = document.addElement("root"); root.setText("blahblah " + '\u008f'); XMLWriter writer = new XMLWriter(); StringWriter strWriter = new StringWriter(); writer.setWriter(strWriter); writer.setMaximumAllowedCharacter(127); writer.write(document); String xml = strWriter.toString(); } public void testEscapeText() throws SAXException { StringWriter writer = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(writer); xmlWriter.setEscapeText(false); String txt = ""; xmlWriter.startDocument(); xmlWriter.characters(txt.toCharArray(), 0, txt.length()); xmlWriter.endDocument(); String output = writer.toString(); System.out.println(output); assertTrue(output.indexOf("") != -1); } public void testNullCData() { Element e = DocumentHelper.createElement("test"); e.add(DocumentHelper.createElement("another").addCDATA(null)); Document doc = DocumentHelper.createDocument(e); assertEquals(-1, e.asXML().indexOf("null")); assertEquals(-1, doc.asXML().indexOf("null")); System.out.println(e.asXML()); System.out.println(doc.asXML()); } protected void generateXML(ContentHandler handler) throws SAXException { handler.startDocument(); AttributesImpl attrs = new AttributesImpl(); attrs.clear(); attrs.addAttribute("", "", "name", "CDATA", "arvojoo"); handler.startElement("", "", "processes", attrs); String text = "jeejee"; char[] textch = text.toCharArray(); handler.characters(textch, 0, textch.length); handler.endElement("", "", "processes"); handler.endDocument(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/XPathBugTest.java0000644000175000017500000001407310242120023020612 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.List; /** * A test harness to test XPath expression evaluation in DOM4J * * @author James Strachan * @version $Revision: 1.4 $ */ public class XPathBugTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(XPathBugTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testXPaths() throws Exception { Document document = getDocument("/xml/rabo1ae.xml"); Element root = (Element) document .selectSingleNode("/m:Msg/m:Contents/m:Content"); assertTrue("root is not null", root != null); Namespace ns = root.getNamespaceForPrefix("ab"); assertTrue("Found namespace", ns != null); System.out.println("Found: " + ns.getURI()); Element element = (Element) root .selectSingleNode("ab:RaboPayLoad[@id='1234123']"); assertTrue("element is not null", element != null); String value = element.valueOf("ab:AccountingEntry/ab:RateType"); assertEquals("RateType is correct", "CRRNT", value); } /** * A bug found by Rob Lebowitz * * @throws Exception * DOCUMENT ME! */ public void testRobLebowitz() throws Exception { String text = "
    " + "
      " + "
    • " + "
        " + "
      • " + "
      " + "
    • " + "
    " + "
"; Document document = DocumentHelper.parseText(text); List lists = document.selectNodes("//ul | //ol"); int count = 0; for (int i = 0; i < lists.size(); i++) { Element list = (Element) lists.get(i); List nodes = list.selectNodes("ancestor::ul"); if ((nodes != null) && (nodes.size() > 0)) { continue; } nodes = list.selectNodes("ancestor::ol"); if ((nodes != null) && (nodes.size() > 0)) { continue; } } } /** * A bug found by Stefan which results in IndexOutOfBoundsException for * empty results * * @throws Exception * DOCUMENT ME! */ public void testStefan() throws Exception { String text = "hello"; Document document = DocumentHelper.parseText(text); XPath xpath = DocumentHelper.createXPath("/x"); Object value = xpath.evaluate(document); } /** * Test found by Mike Skells * * @throws Exception * DOCUMENT ME! */ public void testMikeSkells() throws Exception { Document top = DocumentFactory.getInstance().createDocument(); Element root = top.addElement("root"); root.addElement("child1").addElement("child11"); root.addElement("child2").addElement("child21"); System.out.println(top.asXML()); XPath test1 = top.createXPath("/root/child1/child11"); XPath test2 = top.createXPath("/root/child2/child21"); Node position1 = test1.selectSingleNode(root); Node position2 = test2.selectSingleNode(root); System.out.println("test1= " + test1); System.out.println("test2= " + test2); System.out.println("Position1 Xpath = " + position1.getUniquePath()); System.out.println("Position2 Xpath = " + position2.getUniquePath()); System.out.println("test2.matches(position1) : " + test2.matches(position1)); assertTrue("test1.matches(position1)", test1.matches(position1)); assertTrue("test2.matches(position2)", test2.matches(position2)); assertTrue("test2.matches(position1) should be false", !test2 .matches(position1)); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/SerializeTest.java0000644000175000017500000001337010242120010021052 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Map; import org.dom4j.io.SAXReader; /** * Tests that a dom4j document is Serializable * * @author James Strachan * @version $Revision: 1.4 $ */ public class SerializeTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(SerializeTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testSerializePeriodicTable() throws Exception { testSerialize("/xml/periodic_table.xml"); } public void testSerializeMuchAdo() throws Exception { testSerialize("/xml/much_ado.xml"); } public void testSerializeTestSchema() throws Exception { testSerialize("/xml/test/schema/personal.xsd"); } public void testSerializeXPath() throws Exception { Map uris = new HashMap(); uris.put("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/"); uris.put("m", "urn:xmethodsBabelFish"); DocumentFactory factory = new DocumentFactory(); factory.setXPathNamespaceURIs(uris); // now parse a document using my factory SAXReader reader = new SAXReader(); reader.setDocumentFactory(factory); Document doc = getDocument("/xml/soap.xml", reader); // now lets use the prefixes String expr = "/SOAP-ENV:Envelope/SOAP-ENV:Body/m:BabelFish"; Node element = doc.selectSingleNode(expr); assertTrue("Found valid element", element != null); XPath xpath = factory .createXPath("/SOAP-ENV:Envelope/SOAP-ENV:Body/m:BabelFish"); element = xpath.selectSingleNode(doc); assertTrue("Found valid element", element != null); // now serialize ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bytesOut); out.writeObject(xpath); out.close(); byte[] data = bytesOut.toByteArray(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream( data)); XPath xpath2 = (XPath) in.readObject(); in.close(); element = xpath2.selectSingleNode(doc); assertTrue("Found valid element", element != null); } // Implementation methods // ------------------------------------------------------------------------- protected void testSerialize(String xmlFile) throws Exception { Document document = getDocument(xmlFile); String text = document.asXML(); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bytesOut); out.writeObject(document); out.close(); byte[] data = bytesOut.toByteArray(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream( data)); Document doc2 = (Document) in.readObject(); in.close(); String text2 = doc2.asXML(); assertEquals("Documents text are equal", text, text2); assertTrue("Read back document after serialization", (doc2 != null) && doc2 instanceof Document); assertDocumentsEqual(document, (Document) doc2); // now lets try add something to the document... doc2.getRootElement().addElement("new"); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/HTMLWriterTest.java0000644000175000017500000001515710242120014021075 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.io.StringWriter; import org.dom4j.io.HTMLWriter; import org.dom4j.io.OutputFormat; /** * Test harness for the HTMLWriter * * @author James Strachan * @version $Revision: 1.4 $ */ public class HTMLWriterTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(HTMLWriterTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testWriter() throws Exception { String xml = " "; Document document = DocumentHelper.parseText(xml); StringWriter buffer = new StringWriter(); HTMLWriter writer = new HTMLWriter(buffer); writer.write(document); String output = buffer.toString(); String expects = "\n\n First test\n\n"; System.out.println("expects: " + expects); System.out.println("output: " + output); assertEquals("Output is correct", expects, output); } public void testBug923882() throws Exception { Document doc = DocumentFactory.getInstance().createDocument(); Element root = doc.addElement("root"); root.addText("this is "); root.addText(" sim"); root.addText("ple text "); root.addElement("child"); root.addText(" contai"); root.addText("ning spaces and"); root.addText(" multiple textnodes"); OutputFormat format = new OutputFormat(); format.setEncoding("UTF-8"); format.setIndentSize(4); format.setNewlines(true); format.setTrimText(true); format.setExpandEmptyElements(true); StringWriter buffer = new StringWriter(); HTMLWriter writer = new HTMLWriter(buffer, format); writer.write(doc); String xml = buffer.toString(); log(xml); int start = xml.indexOf("") + 6; String eol = "\n"; // System.getProperty("line.separator"); String expected = "this is simple text" + eol + " containing spaces and multiple textnodes" + eol + ""; System.out.println("Expected:"); System.out.println(expected); System.out.println("Obtained:"); System.out.println(xml.substring(start, end)); assertEquals(expected, xml.substring(start, end)); } public void testBug923882asWriter() throws Exception { // use an the HTMLWriter sax-methods. // StringWriter buffer = new StringWriter(); HTMLWriter writer = new HTMLWriter(buffer, OutputFormat .createPrettyPrint()); writer.characters("wor".toCharArray(), 0, 3); writer.characters("d-being-cut".toCharArray(), 0, 11); String expected = "word-being-cut"; assertEquals(expected, buffer.toString()); buffer = new StringWriter(); writer = new HTMLWriter(buffer, OutputFormat.createPrettyPrint()); writer.characters(" wor".toCharArray(), 0, 7); writer.characters("d being ".toCharArray(), 0, 11); writer.characters(" cut".toCharArray(), 0, 5); expected = "word being cut"; assertEquals(expected, buffer.toString()); } public void testBug923882asWriterWithEmptyCharArray() throws Exception { // use an the HTMLWriter sax-methods. // StringWriter buffer = new StringWriter(); HTMLWriter writer = new HTMLWriter(buffer, OutputFormat .createPrettyPrint()); writer.characters("wor".toCharArray(), 0, 3); writer.characters(new char[0], 0, 0); writer.characters("d-being-cut".toCharArray(), 0, 11); String expected = "word-being-cut"; assertEquals(expected, buffer.toString()); } public void testBug619415() throws Exception { Document doc = getDocument("/xml/test/dosLineFeeds.xml"); StringWriter wr = new StringWriter(); HTMLWriter writer = new HTMLWriter(wr, new OutputFormat("", false)); writer.write(doc); String result = wr.toString(); System.out.println(result); assertTrue(result.indexOf("Mary had a little lamb.") > -1); assertTrue(result.indexOf("Hello, this is a test.") > -1); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/SetTextTest.java0000644000175000017500000000711310242120012020523 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; /** * Tests the setText method * * @author Maarten Coene */ public class SetTextTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(SetTextTest.class); } /* * The structure of the test document is: [root] [author name="James" * location="UK"] James Strachem * [url]http://sourceforge.net/users/jstrachan/[/url] [/author] [author * name="Bob" location="Canada"] Bob McWhirter * [url]http://sourceforge.net/users/werken/[/url] [/author] [/root] */ public void testSetText1() throws Exception { String newURL = "newURL"; Node urlNode = document.selectSingleNode("//root/author[1]/url"); urlNode.setText(newURL); assertEquals(newURL, urlNode.getText()); assertTrue(urlNode instanceof Element); Element urlElement = (Element) urlNode; assertEquals(0, urlElement.elements().size()); } public void testSetText2() throws Exception { String newName = "Strachem James"; Node authorNode = document.selectSingleNode("//root/author[1]"); authorNode.setText(newName); assertEquals(newName, authorNode.getText()); assertTrue(authorNode instanceof Element); Element urlElement = (Element) authorNode; assertEquals(1, urlElement.elements().size()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/CopyTest.java0000644000175000017500000001101710242120011020032 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.List; /** * A test harness to test the copy() methods on Element * * @author James Strachan * @version $Revision: 1.3 $ */ public class CopyTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(CopyTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testRoot() throws Exception { document.setName("doc1"); Element root = document.getRootElement(); List authors = root.elements("author"); assertTrue("Should be at least 2 authors", authors.size() == 2); Element author1 = (Element) authors.get(0); Element author2 = (Element) authors.get(1); testCopy(root); testCopy(author1); testCopy(author2); } protected void testCopy(Element element) throws Exception { assertTrue("Not null", element != null); int attributeCount = element.attributeCount(); int nodeCount = element.nodeCount(); Element copy = element.createCopy(); assertEquals("Node size not equal after copy", element.nodeCount(), nodeCount); assertTrue("Same attribute size after copy", element.attributeCount() == attributeCount); assertTrue("Copy has same node size", copy.nodeCount() == nodeCount); assertTrue("Copy has same attribute size", copy.attributeCount() == attributeCount); for (int i = 0; i < attributeCount; i++) { Attribute attr1 = element.attribute(i); Attribute attr2 = copy.attribute(i); assertTrue("Attribute: " + i + " name is equal", attr1.getName() .equals(attr2.getName())); assertTrue("Attribute: " + i + " value is equal", attr1.getValue() .equals(attr2.getValue())); } for (int i = 0; i < nodeCount; i++) { Node node1 = element.node(i); Node node2 = copy.node(i); assertTrue("Node: " + i + " type is equal", node1.getNodeType() == node2.getNodeType()); assertTrue("Node: " + i + " value is equal", node1.getText() .equals(node2.getText())); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/DocTypeTest.java0000644000175000017500000000722210242120022020474 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.List; import org.dom4j.dtd.ElementDecl; import org.dom4j.io.SAXReader; /** * Tests the DocType functionality * * @author James Strachan * @version $Revision: 1.4 $ */ public class DocTypeTest extends AbstractTestCase { /** Input XML file to read */ protected static final String INPUT_XML_FILE = "/xml/dtd/internal.xml"; public static void main(String[] args) { TestRunner.run(DocTypeTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testDocType() throws Exception { SAXReader reader = new SAXReader(); reader.setIncludeInternalDTDDeclarations(true); Document document = getDocument(INPUT_XML_FILE, reader); DocumentType docType = document.getDocType(); assertTrue("Has DOCTYPE", docType != null); List declarations = docType.getInternalDeclarations(); assertTrue("DOCTYPE has declarations", (declarations != null) && !declarations.isEmpty()); ElementDecl decl = (ElementDecl) declarations.get(0); assertEquals("name is correct", "greeting", decl.getName()); assertEquals("model is correct", "(#PCDATA)", decl.getModel()); String expected = ""; assertEquals("toString() is correct", expected, decl.toString()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/MergeTextTest.java0000644000175000017500000000776010242120005021041 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.Iterator; import org.dom4j.io.SAXReader; /** * A test harness for SAXReader option setMergeAdjacentText(true) * * @author Steen Lehmann * @version $Revision: 1.4 $ */ public class MergeTextTest extends AbstractTestCase { /** Input XML file to read */ private static final String INPUT_XML_FILE = "/xml/test/mergetext.xml"; public static void main(String[] args) { TestRunner.run(MergeTextTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testNoAdjacentText() throws Exception { // After reading using SAXReader with mergeAdjacentText true, // no two Text objects should be adjacent to each other in the // document. SAXReader reader = new SAXReader(); reader.setMergeAdjacentText(true); Document document = getDocument(INPUT_XML_FILE, reader); checkNoAdjacent(document.getRootElement()); log("No adjacent Text nodes in " + document.asXML()); } // Implementation methods // ------------------------------------------------------------------------- private void checkNoAdjacent(Element parent) { // Check that no two Text nodes are adjacent in the parent's content Node prev = null; Iterator iter = parent.nodeIterator(); while (iter.hasNext()) { Node n = (Node) iter.next(); if (n instanceof Text && ((prev != null) && prev instanceof Text)) { fail("Node: " + n + " is text and so is its " + "preceding sibling: " + prev); } else if (n instanceof Element) { checkNoAdjacent((Element) n); } prev = n; } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/XPathTest.java0000644000175000017500000001412110242120022020145 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.List; import org.dom4j.tree.DefaultElement; import org.dom4j.xpath.DefaultXPath; /** * A test harness to test XPath expression evaluation in DOM4J * * @author James Strachan * @version $Revision: 1.4 $ */ public class XPathTest extends AbstractTestCase { protected static String[] paths = { ".", "*", "/", "/.", "/*", "/node()", "/child::node()", "/self::node()", "root", "/root", "/root/author", "text()", "//author", "//author/text()", "//@location", "//attribute::*", "//namespace::*", "normalize-space(/root)", "//author[@location]", "//author[@location='UK']", "root|author", "//*[.='James Strachan']", "//root/author[1]", "normalize-space(/root/author)", "normalize-space(' a b c d ')", "//root|//author[1]|//author[2]", "//root/author[2]", "//root/author[3]"}; public static void main(String[] args) { TestRunner.run(XPathTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testBug1116471() throws Exception { String xml = "Water T & D-46816"; String expected = "Water T & D-46816"; Document doc = DocumentHelper.parseText(xml); String result = (String) doc.selectObject("string(a/b[1])"); assertEquals("xpath result not correct", expected, result); Node node = doc.selectSingleNode("a/b"); String result2 = node.getStringValue(); assertEquals("xpath result not correct", expected, result2); } public void testXPaths() throws Exception { int size = paths.length; for (int i = 0; i < size; i++) { testXPath(paths[i]); } } public void testCreateXPathBug() throws Exception { Element element = new DefaultElement("foo"); XPath xpath = element.createXPath("//bar"); assertTrue(("created a valid XPath: " + xpath) != null); } public void testBug857704() throws Exception { Document doc = DocumentHelper .parseText(""); doc.selectNodes("//*[preceding-sibling::*]"); // shouldn't throw NPE } public void testBooleanValueOf() throws Exception { Document doc = DocumentHelper.parseText("blah"); XPath path = new DefaultXPath("//root"); assertTrue(path.booleanValueOf(doc)); path = new DefaultXPath("//root2"); assertFalse(path.booleanValueOf(doc)); } // Implementation methods // ------------------------------------------------------------------------- protected void testXPath(String xpathExpression) { log("Searched path: " + xpathExpression); XPath xpath = DocumentHelper.createXPath(xpathExpression); List list = xpath.selectNodes(document); if (list == null) { log("null"); } else { log("["); for (int i = 0, size = list.size(); i < size; i++) { Object object = list.get(i); String text = "null"; if (object instanceof Node) { Node node = (Node) object; text = node.asXML(); } else if (object != null) { text = object.toString(); } log(" " + text); } log("]"); } log("..........................................."); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/NamespacesTest.java0000644000175000017500000003375210242120007021216 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.io.StringReader; import java.util.Iterator; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.dom4j.io.DOMReader; import org.xml.sax.InputSource; /** * Test the use of namespaces * * @author James Strachan * @version $Revision: 1.4 $ */ public class NamespacesTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(NamespacesTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testNamespaces() throws Exception { testNamespaces(document); testNamespaces(saxRoundTrip(document)); testNamespaces(domRoundTrip(document)); } public void testNamespaces(Document document) throws Exception { Document doc2 = (Document) document.clone(); Element root = doc2.getRootElement(); assertNamespace(root.getNamespace(), "", "http://www.w3.org/2001/XMLSchema"); assertEquals("xmlns=\"http://www.w3.org/2001/XMLSchema\"", root .getNamespace().asXML()); assertEquals("namespace::*[name()='']", root.getNamespace().getPath()); assertEquals("namespace::*[name()='']", root.getNamespace() .getUniquePath()); List additionalNS = root.additionalNamespaces(); assertTrue("at least one additional namespace", (additionalNS != null) && (additionalNS.size() > 0)); Namespace ns = (Namespace) additionalNS.get(0); assertNamespace(ns, "t", "http://www.w3.org/namespace/"); assertEquals("xmlns:t=\"http://www.w3.org/namespace/\"", ns.asXML()); assertEquals("namespace::t", ns.getPath()); assertEquals("namespace::t", ns.getUniquePath()); Node node = root.node(0); assertTrue("First node is a namespace", node instanceof Namespace); // now lets try change the namespace root.remove(ns); root.addNamespace("t", "myNewURI"); additionalNS = root.additionalNamespaces(); assertTrue("at least one additional namespace", (additionalNS != null) && (additionalNS.size() > 0)); ns = (Namespace) additionalNS.get(0); assertNamespace(ns, "t", "myNewURI"); // lets test the list is backed additionalNS.remove(0); additionalNS.add(Namespace.get("t", "myNewURI-2")); additionalNS = root.additionalNamespaces(); assertTrue("at least one additional namespace", (additionalNS != null) && (additionalNS.size() > 0)); ns = (Namespace) additionalNS.get(0); assertNamespace(ns, "t", "myNewURI-2"); additionalNS.clear(); root.addNamespace("t", "myNewURI"); additionalNS = root.additionalNamespaces(); assertTrue("at least one additional namespace", (additionalNS != null) && (additionalNS.size() > 0)); ns = (Namespace) additionalNS.get(0); assertNamespace(ns, "t", "myNewURI"); log("Namespaces: " + additionalNS); log("XML is now"); log(root.asXML()); } public void testNamespaceForPrefix() throws Exception { testNamespaceForPrefix(document); testNamespaceForPrefix(saxRoundTrip(document)); testNamespaceForPrefix(domRoundTrip(document)); } public void testNamespaceForPrefix(Document document) throws Exception { Element root = document.getRootElement(); Namespace ns = root.getNamespaceForPrefix("t"); assertNamespace(ns, "t", "http://www.w3.org/namespace/"); Element element = (Element) root.elements().get(0); Namespace ns2 = element.getNamespaceForPrefix("t"); assertNamespace(ns2, "t", "http://www.w3.org/namespace/"); assertTrue("Same namespace instance returned", ns == ns2); log("found: " + ns.asXML()); } public void testNamespaceForDefaultPrefix() throws Exception { Document document = getDocument("/xml/test/defaultNamespace.xml"); testNamespaceForDefaultPrefix(document); testNamespaceForDefaultPrefix(saxRoundTrip(document)); testNamespaceForDefaultPrefix(domRoundTrip(document)); } public void testNamespaceForDefaultPrefix(Document document) throws Exception { List list = document.selectNodes("//*"); for (Iterator iter = list.iterator(); iter.hasNext();) { Element element = (Element) iter.next(); Namespace ns = element.getNamespaceForPrefix(""); assertNamespace(ns, "", "dummyNamespace"); ns = element.getNamespaceForPrefix(null); assertNamespace(ns, "", "dummyNamespace"); log("found: " + ns.asXML()); } } public void testAttributeDefaultPrefix() throws Exception { Document document = getDocument("/xml/test/soap3.xml"); testAttributeDefaultPrefix(document); testAttributeDefaultPrefix(saxRoundTrip(document)); testAttributeDefaultPrefix(domRoundTrip(document)); } public void testAttributeDefaultPrefix(Document document) throws Exception { List list = document.selectNodes("//@*[local-name()='actor']"); assertTrue("Matched at least one 'actor' attribute", list.size() > 0); for (Iterator iter = list.iterator(); iter.hasNext();) { Attribute attribute = (Attribute) iter.next(); log("found: " + attribute.asXML()); Element element = attribute.getParent(); assertTrue("Attribute has a parent", element != null); Namespace ns = element.getNamespaceForPrefix(""); String uri = "http://schemas.xmlsoap.org/soap/envelope/"; assertNamespace(ns, "", uri); Namespace ns2 = attribute.getNamespace(); // Note that namespaces do not inherit the default namespace! assertNamespace(ns2, "", ""); } } public void testNamespaceForURI() throws Exception { testNamespaceForURI(document); testNamespaceForURI(saxRoundTrip(document)); testNamespaceForURI(domRoundTrip(document)); } public void testNamespaceForURI(Document document) throws Exception { Element root = document.getRootElement(); Namespace ns = root.getNamespaceForURI("http://www.w3.org/namespace/"); assertNamespace(ns, "t", "http://www.w3.org/namespace/"); Element element = (Element) root.elements().get(0); Namespace ns2 = element .getNamespaceForURI("http://www.w3.org/namespace/"); assertNamespace(ns2, "t", "http://www.w3.org/namespace/"); assertTrue("Same namespace instance returned", ns == ns2); log("found: " + ns.asXML()); } public void testRedeclareNamespaces() throws Exception { Document document = getDocument("/xml/test/soap2.xml"); testRedeclareNamespaces(document); testRedeclareNamespaces(saxRoundTrip(document)); testRedeclareNamespaces(domRoundTrip(document)); } public void testRedeclareNamespaces(Document document) throws Exception { String uri = "http://schemas.xmlsoap.org/soap/envelope/"; assertNamespaces(document.selectNodes("//*[local-name()='Envelope']"), "SOAP-ENV", uri); assertNamespaces(document.selectNodes("//*[local-name()='Body']"), "SOAP-ENV", uri); assertNamespaces(document.selectNodes("//*[local-name()='bar']"), "a", "barURI"); assertNamespaces(document.selectNodes("//*[local-name()='newBar']"), "a", "newBarURI"); assertNamespaces(document.selectNodes("//*[local-name()='foo']"), "", "fooURI"); assertNamespaces(document.selectNodes("//*[local-name()='newFoo']"), "", "newFooURI"); } public void testDefaultNamespaceIssue() throws Exception { Document document = getDocument("/xml/test/defaultNamespaceIssue.xsd"); testDefaultNamespaceIssue(document); testDefaultNamespaceIssue(saxRoundTrip(document)); testDefaultNamespaceIssue(domRoundTrip(document)); } public void testDefaultNamespaceIssue(Document document) throws Exception { // When writing documents using a default namespace with XMLWriter // a redeclaration of the default namespace to "" was dropped in the // output. Test that // // is in no namespace. String expr = "/xsd:schema/xsd:element/xsd:annotation/xsd:documentation/text"; assertNotNull("default namespace redeclaration", (Element) document .selectSingleNode(expr)); // The test document has a default namespace declaration on the root // element ("schema"), but the element itself is not in the default // namespace. Test that declaredNamespaces on the root element also // returns the default namespace declaration. Iterator iter = document.getRootElement().declaredNamespaces() .iterator(); while (iter.hasNext()) { Namespace ns = (Namespace) iter.next(); if ("urn:wapforum:devicesheet".equals(ns.getURI()) && "".equals(ns.getPrefix())) { return; } } fail("Default namespace declaration not present on root element"); } public void testDefaultNamespace() throws Exception { Document doc = DocumentHelper.createDocument(); Element processDef = doc.addElement("process-definition", "http://jbpm.org/statedefinition-2.0-beta3"); Element startState = processDef.addElement("start-state"); startState.addAttribute("name", "start"); Element transition = startState.addElement("transition"); transition.addAttribute("to", "first"); assertEquals("http://jbpm.org/statedefinition-2.0-beta3", startState .getNamespace().getURI()); assertEquals("", startState.getNamespace().getPrefix()); System.out.println(doc.asXML()); } // Implementation methods // ------------------------------------------------------------------------- protected void setUp() throws Exception { super.setUp(); document = getDocument("/xml/test/test_schema.xml"); } protected Document saxRoundTrip(Document document) throws Exception { return DocumentHelper.parseText(document.asXML()); } protected Document domRoundTrip(Document document) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); org.w3c.dom.Document domDocument = builder.parse(new InputSource( new StringReader(document.asXML()))); // now lets read it back as a DOM4J object DOMReader domReader = new DOMReader(); return domReader.read(domDocument); } protected void assertNamespaces(List elements, String prefix, String uri) throws Exception { for (Iterator iter = elements.iterator(); iter.hasNext();) { Element element = (Element) iter.next(); assertNamespace(element.getNamespace(), prefix, uri); } } protected void assertNamespace(Namespace ns, String prefix, String uri) throws Exception { assertEquals("namespace prefix", prefix, ns.getPrefix()); assertEquals("namespace URI", uri, ns.getURI()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/util/0000755000175000017500000000000012133227266016417 5ustar ebourgebourgdom4j-1.6.1/src/test/org/dom4j/util/PerThreadSingletonTest.java0000644000175000017500000001272310242117777023674 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.util; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.TestCase; import junit.extensions.RepeatedTest; import java.util.HashMap; import java.util.Map; import com.clarkware.junitperf.LoadTest; import com.clarkware.junitperf.TimedTest; /** * PerThreadSingleton Tester. * * @author ddlucas * @since * *
 * 01 / 05 / 2005
 * 
* * @version 1.0 */ public class PerThreadSingletonTest extends TestCase { public PerThreadSingletonTest(String name) { super(name); } private static SingletonStrategy singleton; private static ThreadLocal reference = new ThreadLocal(); public void setUp() throws Exception { super.setUp(); synchronized (PerThreadSingletonTest.class) { if (singleton == null) { singleton = new PerThreadSingleton(); singleton.setSingletonClassName(HashMap.class.getName()); } } } public void tearDown() throws Exception { super.tearDown(); } public void testInstance() throws Exception { String tid = Thread.currentThread().getName(); Map map = (Map) singleton.instance(); String expected = "new value"; if (!map.containsKey(tid) && reference.get() != null) { System.out.println("tid=" + tid + " map=" + map); System.out.println("reference=" + reference); System.out.println("singleton=" + singleton); fail("created singleton more than once"); } else { map.put(tid, expected); reference.set(map); } String actual = (String) map.get(tid); // System.out.println("tid="+tid+ " map="+map); assertEquals("testInstance", expected, actual); map = (Map) singleton.instance(); expected = "new value"; actual = (String) map.get(tid); // System.out.println("tid="+tid+ " map="+map); // System.out.println("reference="+reference); // System.out.println("singleton="+singleton); assertEquals("testInstance", expected, actual); assertEquals("testInstance reference", reference.get(), map); } /** * Assembles and returns a test suite. * * @return The suite */ public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(makeRepeatedLoadTest(5, 100, "testInstance")); return suite; } /** * JUnit method to exercise test via threads and loops * * @param users * Number of users to simulate (i.e. Threads). * @param iterations * Number of iterations per user ( repeat the test x times). * @param testMethod * method to execute (testXXX). * * @return A Junit test */ protected static Test makeRepeatedLoadTest(int users, int iterations, String testMethod) { long maxElapsedTime = 1200 + (1000 * users * iterations); Test testCase = new PerThreadSingletonTest(testMethod); Test repeatedTest = new RepeatedTest(testCase, iterations); Test loadTest = new LoadTest(repeatedTest, users); Test timedTest = new TimedTest(loadTest, maxElapsedTime); return timedTest; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/util/SimpleSingletonTest.java0000644000175000017500000001013110242120007023212 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.util; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.TestCase; import java.util.HashMap; import java.util.Map; /** * PerThreadSingleton Tester. * * @author ddlucas * @since * *
 * 01 / 05 / 2005
 * 
* * @version 1.0 */ public class SimpleSingletonTest extends TestCase { public SimpleSingletonTest(String name) { super(name); } private static SingletonStrategy singleton; private static Object reference; public void setUp() throws Exception { super.setUp(); if (singleton == null) { singleton = new PerThreadSingleton(); singleton.setSingletonClassName(HashMap.class.getName()); } } public void tearDown() throws Exception { super.tearDown(); } public void testFirstInstance() throws Exception { Map map = (Map) singleton.instance(); String expected = null; String actual = (String) map.get("Test"); assertEquals("testInstance", expected, actual); expected = "new value"; map.put("Test", expected); map = (Map) singleton.instance(); reference = map; actual = (String) map.get("Test"); assertEquals("testFirstInstance", expected, actual); } public void testSecondInstance() throws Exception { Map map = (Map) singleton.instance(); assertEquals("testSecondInstance reference", reference, map); String actual = (String) map.get("Test"); String expected = "new value"; assertEquals("testInstance", expected, actual); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestSuite.createTest(SimpleSingletonTest.class, "testFirstInstance")); suite.addTest(TestSuite.createTest(SimpleSingletonTest.class, "testSecondInstance")); return suite; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/XMLSpaceAttributeTest.java0000644000175000017500000002551010242120007022430 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.io.IOException; /** * A test harness to test the xml:space attribute for preserve. If it is * preserve, then keep whitespace. * * @author David Lucas * @version $Revision: 1.4 $ */ public class XMLSpaceAttributeTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(XMLSpaceAttributeTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testWithTextTrimOn() throws Exception { String xmlString = "" + " This is a test!" + " This is a test!" + " This is a test!" + ""; Document doc1 = DocumentHelper.parseText(xmlString); Element c2 = (Element) doc1.selectSingleNode("/top/row[2]/col"); String expected = " New Text TrimOn! "; c2.setText(expected); String xml = rewriteToXmlString(doc1, true); Document doc2 = DocumentHelper.parseText(xml); Element c4 = (Element) doc2.selectSingleNode("/top/row[2]/col"); String actual = c4.getText(); assertEquals("compared element text expecting whitespace", expected, actual); expected = expected.trim(); actual = c4.getTextTrim(); assertEquals("compared element getTextTrim", expected, actual); expected = "This is a test!"; Element c5 = (Element) doc2.selectSingleNode("/top/row[3]/col"); actual = c5.getText(); assertEquals("compared element text expecting trimmed whitespace", expected, actual); } // ------------------------------------------------------------------------- public void testWithTextTrimOff() throws Exception { String xmlString = "" + " This is a test!" + " This is a test!" + " This is a test!" + ""; Document doc1 = DocumentHelper.parseText(xmlString); Element c2 = (Element) doc1.selectSingleNode("/top/row[2]/col"); String expected = " New Text TrimOff! "; c2.setText(expected); String xml = rewriteToXmlString(doc1, false); Document doc2 = DocumentHelper.parseText(xml); Element c4 = (Element) doc2.selectSingleNode("/top/row[2]/col"); String actual = c4.getText(); assertEquals("compared element text expecting whitespace", expected, actual); } // ------------------------------------------------------------------------- public void testWithTextTrimOnFollow() throws Exception { String xmlString = "" + " This is a test!" + "" + "" + " This is embedded!" + " This is space=preserve too!" + "" + "" + " This is a test!" + ""; Document doc1 = DocumentHelper.parseText(xmlString); Element c2 = (Element) doc1.selectSingleNode("/top/row[2]/col/a[1]/b"); String expected = " New Text TrimOnFollow! "; c2.setText(expected); String xml = rewriteToXmlString(doc1, true); Document doc2 = DocumentHelper.parseText(xml); Element c4 = (Element) doc2.selectSingleNode("/top/row[2]/col/a[1]/b"); String actual = c4.getText(); assertEquals("compared element text expecting whitespace", expected, actual); Element c8 = (Element) doc2.selectSingleNode("/top/row[2]/col/a[2]/b"); expected = " This is space=preserve too!"; actual = c8.getText(); assertEquals("compared element text follow trimmed whitespace", expected, actual); expected = expected.trim(); actual = c8.getTextTrim(); assertEquals("compared element getTextTrim", expected, actual); Element c12 = (Element) doc2.selectSingleNode("/top/row[3]/col"); expected = "This is a test!"; actual = c12.getText(); assertEquals("compared element text follow trimmed whitespace", expected, actual); } // ------------------------------------------------------------------------- public void testWithTextTrimOnNested() throws Exception { String xmlString = "" + " This is a test!" + "" + "" + "" + " This is embedded! " + " This should do global default! " + " This is embedded! " + "" + "" + "" + " This is a test!" + ""; Document doc1 = DocumentHelper.parseText(xmlString); Element c2 = (Element) doc1.selectSingleNode("/top/row[2]/col/a[1]/b"); String expected = " New Text TrimOnNested! "; c2.setText(expected); String xml = rewriteToXmlString(doc1, true); Document doc2 = DocumentHelper.parseText(xml); Element c4 = (Element) doc2 .selectSingleNode("/top/row[2]/col/a[1]/b[1]"); String actual = c4.getText(); assertEquals("compared element text expecting whitespace", expected, actual); Element c8 = (Element) doc2 .selectSingleNode("/top/row[2]/col/a[1]/b[2]"); expected = "This should do global default!"; actual = c8.getText(); assertEquals("compared element text nested trimmed whitespace", expected, actual); Element c12 = (Element) doc2 .selectSingleNode("/top/row[2]/col/a[1]/b[3]"); expected = " This is embedded! "; actual = c12.getText(); assertEquals("compared element text nested preserved whitespace", expected, actual); } // Implementation methods // ------------------------------------------------------------------------- private String rewriteToXmlString(Document doc, boolean trimOn) throws IOException { org.dom4j.io.OutputFormat of = org.dom4j.io.OutputFormat .createCompactFormat(); of.setIndent(true); of.setNewlines(true); of.setExpandEmptyElements(false); of.setSuppressDeclaration(false); of.setOmitEncoding(false); of.setEncoding("UTF-8"); of.setTrimText(trimOn); java.io.ByteArrayOutputStream os = new java.io.ByteArrayOutputStream(); java.io.BufferedOutputStream bos = new java.io.BufferedOutputStream(os); org.dom4j.io.XMLWriter xmlWriter = new org.dom4j.io.XMLWriter(of); xmlWriter.setOutputStream(bos); xmlWriter.write(doc); xmlWriter.close(); String xml = os.toString(); // System.out.println("***** xml out *****\n"+xml); return xml; } // ------------------------------------------------------------------------- public void testWithEscapeTextTrimOn() throws Exception { String xmlString = "" + " This is a test!" + " This is a test!\r\n" + "With a new line, special character like & , and\t tab." + " This is a test!\r\nWith a new line," + " special character like & , and\t tab." + ""; Document doc1 = DocumentHelper.parseText(xmlString); String xml = rewriteToXmlString(doc1, true); Document doc2 = DocumentHelper.parseText(xml); Element c2 = (Element) doc2.selectSingleNode("/top/row[2]/col"); String expected = " This is a test!\nWith a new line, special " + "character like & , and\t tab."; String actual = c2.getText(); assertEquals("compared element text expecting whitespace", expected, actual); Element c4 = (Element) doc2.selectSingleNode("/top/row[3]/col"); expected = "This is a test! With a new line, special character " + "like & , and tab."; actual = c4.getText(); assertEquals("compared element text expecting whitespace", expected, actual); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/UserDataTest.java0000644000175000017500000001353310242120017020643 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import org.dom4j.io.SAXReader; import org.dom4j.util.UserDataAttribute; import org.dom4j.util.UserDataDocumentFactory; import org.dom4j.util.UserDataElement; /** * Tests the UserDataDocumentFactory * * @author James Strachan * @version $Revision: 1.4 $ */ public class UserDataTest extends AbstractTestCase { /** Input XML file to read */ private static final String INPUT_XML_FILE = "/xml/web.xml"; private Object userData = new Double(1.23456); public static void main(String[] args) { TestRunner.run(UserDataTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testSetData() throws Exception { Element root = getRootElement(); assertTrue("Element instanceof UserDataElement", root instanceof UserDataElement); root.setData(userData); assertTrue("Stored user data!", root.getData() == userData); log("root: " + root); assertUserData(root, userData); Element cloned = (Element) root.clone(); assertTrue("Cloned new instance", cloned != root); assertUserData(cloned, userData); cloned = root.createCopy(); assertTrue("Cloned new instance", cloned != root); assertUserData(cloned, userData); } public void testCloneAttribute() throws Exception { Element root = getRootElement(); root.addAttribute("name", "value"); Attribute attribute = root.attribute("name"); assertTrue(attribute instanceof UserDataAttribute); Element cloned = (Element) root.clone(); Attribute clonedAttribute = cloned.attribute("name"); assertTrue(clonedAttribute instanceof UserDataAttribute); } public void testNewAdditions() throws Exception { Element root = getRootElement(); Element newElement = root.addElement("foo1234"); assertTrue("New Element is a UserDataElement", newElement instanceof UserDataElement); root.addAttribute("bar456", "123"); Attribute newAttribute = root.attribute("bar456"); assertTrue("New Attribute is a UserDataAttribute", newAttribute instanceof UserDataAttribute); } public void testNewDocument() throws Exception { DocumentFactory factory = UserDataDocumentFactory.getInstance(); Document document = factory.createDocument(); Element root = document.addElement("root"); assertTrue("Root Element is a UserDataElement", root instanceof UserDataElement); Element newElement = root.addElement("foo1234"); assertTrue("New Element is a UserDataElement", newElement instanceof UserDataElement); root.addAttribute("bar456", "123"); Attribute newAttribute = root.attribute("bar456"); assertTrue("New Attribute is a UserDataAttribute", newAttribute instanceof UserDataAttribute); } // Implementation methods // ------------------------------------------------------------------------- protected void assertUserData(Element root, Object data) throws Exception { Object result = root.getData(); assertTrue("No user data!", result != null); assertTrue("Stored user data correctly", data.equals(result)); } protected void setUp() throws Exception { super.setUp(); SAXReader reader = new SAXReader(); reader.setDocumentFactory(UserDataDocumentFactory.getInstance()); document = getDocument(INPUT_XML_FILE, reader); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/XPathExamplesTest.java0000644000175000017500000002057010242120024021653 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.Iterator; import java.util.List; import org.dom4j.io.SAXReader; import org.dom4j.rule.Pattern; /** * Performs a number of unit test cases on the XPath engine * * @author James Strachan * @version $Revision: 1.5 $ */ public class XPathExamplesTest extends AbstractTestCase { protected SAXReader xmlReader = new SAXReader(); /** The document on which the tests are being run */ protected Document testDocument; /** The context node on which the tests are being run */ protected Node testContext; /** factory for XPath, Patterns and nodes */ protected DocumentFactory factory = DocumentFactory.getInstance(); public static void main(String[] args) { TestRunner.run(XPathExamplesTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testXPaths() throws Exception { Document document = getDocument("/xml/test/xpath/tests.xml"); Element root = document.getRootElement(); Iterator iter = root.elementIterator("document"); while (iter.hasNext()) { Element documentTest = (Element) iter.next(); testDocument(documentTest); } } // Implementation methods // ------------------------------------------------------------------------- protected void testDocument(Element documentTest) throws Exception { String url = documentTest.attributeValue("url"); testDocument = xmlReader.read(getFile(url)); assertTrue("Loaded test document: " + url, testDocument != null); log("Loaded document: " + url); for (Iterator iter = documentTest.elementIterator("context"); iter .hasNext();) { Element context = (Element) iter.next(); testContext(documentTest, context); } } protected void testContext(Element documentTest, Element context) throws Exception { String xpath = context.attributeValue("select"); List list = testDocument.selectNodes(xpath); assertTrue("Found at least one context nodes to test for path: " + xpath, (list != null) && (list.size() > 0)); for (Iterator iter = list.iterator(); iter.hasNext();) { Object object = iter.next(); assertTrue("Context node is a Node: " + object, object instanceof Node); testContext = (Node) object; log("Context is now: " + testContext); runTests(documentTest, context); log(""); } } protected void runTests(Element documentTest, Element context) throws Exception { for (Iterator iter = context.elementIterator("test"); iter.hasNext();) { Element test = (Element) iter.next(); runTest(documentTest, context, test); } for (Iterator it = context.elementIterator("valueOf"); it.hasNext();) { Element valueOf = (Element) it.next(); testValueOf(documentTest, context, valueOf); } for (Iterator it = context.elementIterator("pattern"); it.hasNext();) { Element pattern = (Element) it.next(); testPattern(documentTest, context, pattern); } Iterator it = context.elementIterator("fileter"); while (it.hasNext()) { Element filter = (Element) it.next(); testFilter(documentTest, context, filter); } } protected void runTest(Element documentTest, Element context, Element test) throws Exception { String xpath = test.attributeValue("select"); String description = "Path: " + xpath; String exception = test.attributeValue("exception"); if ((exception != null) && exception.equals("true")) { try { testContext.selectNodes(xpath); fail("Exception was not thrown"); } catch (XPathException e) { return; } } String count = test.attributeValue("count"); if (count != null) { int expectedSize = Integer.parseInt(count); List results = testContext.selectNodes(xpath); log(description + " found result size: " + results.size()); assertEquals(description + " wrong result size", expectedSize, results.size()); } Element valueOf = test.element("valueOf"); if (valueOf != null) { Node node = testContext.selectSingleNode(xpath); assertTrue(description + " found node", node != null); String expected = valueOf.getText(); String result = node.valueOf(valueOf.attributeValue("select")); log(description); log("\texpected: " + expected + " result: " + result); assertEquals(description, expected, result); } } protected void testValueOf(Element documentTest, Element context, Element valueOf) throws Exception { String xpath = valueOf.attributeValue("select"); String description = "valueOf: " + xpath; String expected = valueOf.getText(); String result = testContext.valueOf(xpath); log(description); log("\texpected: " + expected + " result: " + result); assertEquals(description, expected, result); } protected void testPattern(Element documentTest, Element context, Element patternElement) throws Exception { String match = patternElement.attributeValue("match"); String description = "match: " + match; log(""); log(description); Pattern pattern = factory.createPattern(match); assertTrue(description, pattern.matches(testContext)); } protected void testFilter(Element documentTest, Element context, Element pattern) throws Exception { String match = pattern.attributeValue("match"); String description = "match: " + match; assertTrue(description, testContext.matches(match)); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/EmbeddedHandlerTest.java0000644000175000017500000001422310242120007022116 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.io.File; import org.dom4j.io.SAXReader; /** * TestEmbeddedHandler * * @author FB */ public class EmbeddedHandlerTest extends AbstractTestCase { private static final int MAIN_READER = 0; private static final int ON_END_READER = 1; protected String[] testDocuments = {"xml/test/FranzBeilMain.xml"}; private StringBuffer[] results = {new StringBuffer(), new StringBuffer()}; protected int test; public static void main(String[] args) { TestRunner.run(EmbeddedHandlerTest.class); } // --------------------------------------------- // Test case(s) // --------------------------------------------- public void testMainReader() throws Exception { test = MAIN_READER; readDocuments(); } public void testOnEndReader() throws Exception { test = ON_END_READER; readDocuments(); } public void testBothReaders() throws Exception { testMainReader(); testOnEndReader(); if (!results[MAIN_READER].toString().equals( results[ON_END_READER].toString())) { StringBuffer msg = new StringBuffer(); msg.append("Results of tests should be equal!\n"); msg.append("Results testMainReader():\n" + results[MAIN_READER].toString()); msg.append("Results testOnEndReader():\n" + results[ON_END_READER].toString()); throw new Exception(msg.toString()); } } // --------------------------------------------- // Implementation methods // --------------------------------------------- private void readDocuments() throws Exception { for (int i = 0; i < testDocuments.length; i++) { File testDoc = getFile(testDocuments[i]); String mainDir = testDoc.getParent(); SAXReader reader = new SAXReader(); ElementHandler mainHandler = new MainHandler(mainDir); reader.addHandler("/main/import", mainHandler); getDocument(testDocuments[i], reader); } } // Handler classes // --------------------------------------------- class MainHandler implements ElementHandler { private SAXReader mainReader; private String mainDir; public MainHandler(String dir) { mainReader = new SAXReader(); mainDir = dir; mainReader.addHandler("/import/stuff", new EmbeddedHandler()); } public void onStart(ElementPath path) { } public void onEnd(ElementPath path) { String href = path.getCurrent().attribute("href").getValue(); Element importRef = path.getCurrent(); Element parentElement = importRef.getParent(); SAXReader onEndReader = new SAXReader(); onEndReader.addHandler("/import/stuff", new EmbeddedHandler()); File file = new File(mainDir + File.separator + href); Element importElement = null; try { if (test == MAIN_READER) { importElement = mainReader.read(file).getRootElement(); } else if (test == ON_END_READER) { importElement = onEndReader.read(file).getRootElement(); } } catch (Exception e) { // too bad that it's not possible to throw the exception at the // caller e.printStackTrace(); } // prune and replace importRef.detach(); parentElement.add(importElement); } } public class EmbeddedHandler implements ElementHandler { public void onStart(ElementPath path) { results[test].append(path.getCurrent().attribute("name").getValue() + "\n"); } public void onEnd(ElementPath path) { } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/ContentTest.java0000644000175000017500000002225110242120000020532 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.Iterator; import java.util.List; /** * A test harness to test the content API in DOM4J * * @author James Strachan * @version $Revision: 1.3 $ */ public class ContentTest extends AbstractTestCase { protected DocumentFactory factory = new DocumentFactory(); public static void main(String[] args) { TestRunner.run(ContentTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testRoot() throws Exception { Element root = document.getRootElement(); assertTrue("Has root element", root != null); List authors = root.elements("author"); assertTrue("Root has children", (authors != null) && (authors.size() == 2)); Element author1 = (Element) authors.get(0); Element author2 = (Element) authors.get(1); assertTrue("Author1 is James", author1.attributeValue("name").equals( "James")); assertTrue("Author2 is Bob", author2.attributeValue("name").equals( "Bob")); testGetAttributes(author1); testGetAttributes(author2); } public void testContent() throws Exception { Element root = document.getRootElement(); assertTrue("Has root element", root != null); List content = root.content(); assertTrue("Root has content", (content != null) && (content.size() >= 2)); boolean iterated = false; for (Iterator iter = content.iterator(); iter.hasNext();) { Object object = iter.next(); assertTrue("Content object is a node", object instanceof Node); iterated = true; } assertTrue("Iteration completed", iterated); } public void testGetNode() throws Exception { Element root = document.getRootElement(); assertTrue("Has root element", root != null); int count = root.nodeCount(); assertTrue("Root has correct node count", count == 2); boolean iterated = false; for (int i = 0; i < count; i++) { Node node = root.node(i); assertTrue("Valid node returned from node()", node != null); iterated = true; } assertTrue("Iteration completed", iterated); } public void testGetXPathNode() throws Exception { Element root = document.getRootElement(); assertTrue("Has root element", root != null); int count = root.nodeCount(); assertTrue("Root has correct node count", count == 2); boolean iterated = false; for (int i = 0; i < count; i++) { Node node = root.getXPathResult(i); assertTrue("Valid node returned from node()", node != null); assertTrue("Node supports the parent relationship", node .supportsParent()); iterated = true; } assertTrue("Iteration completed", iterated); } public void testOrderOfPI() throws Exception { Document document = factory.createDocument(); document.addProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"...\""); document.addElement("root"); List list = document.content(); assertNotNull(list); assertEquals(2, list.size()); Object pi = list.get(0); Object root = list.get(1); assertTrue("First element is not a PI", pi instanceof ProcessingInstruction); assertTrue("Second element is an element", root instanceof Element); String xml = "\n" + "\n" + ""; document = DocumentHelper.parseText(xml); list = document.content(); assertNotNull(list); assertEquals(2, list.size()); pi = list.get(0); root = list.get(1); assertTrue("First element is not a PI", pi instanceof ProcessingInstruction); assertTrue("Second element is an element", root instanceof Element); } public void testAddingInTheMiddle() throws Exception { Document doc = factory.createDocument(); Element root = doc.addElement("html"); Element header = root.addElement("header"); Element footer = root.addElement("footer"); // now lets add in between header & footer List list = root.content(); Element foo = factory.createElement("foo"); list.add(1, foo); // assertions assertTrue(list.size() == 3); assertTrue(list.get(0) == header); assertTrue(list.get(1) == foo); assertTrue(list.get(2) == footer); } public void testAddAtIndex() throws Exception { Document doc = factory.createDocument(); Element root = doc.addElement("html"); Element header = root.addElement("header"); Element body = root.addElement("body"); Element foo = factory.createElement("foo"); Element bar = factory.createElement("bar"); List content = header.content(); content.add(0, foo); content.add(0, bar); assertEquals("foo", header.node(1).getName()); assertEquals("bar", header.node(0).getName()); foo = factory.createElement("foo"); bar = factory.createElement("bar"); content = body.content(); content.add(0, foo); content.add(1, bar); assertEquals("foo", body.node(0).getName()); assertEquals("bar", body.node(1).getName()); } public void testAddAtIndex2() throws Exception { Document doc = factory.createDocument(); Element parent = doc.addElement("parent"); Element child = parent.addElement("child"); Element anotherChild = factory.createElement("child2"); List elements = parent.elements(); int index = elements.indexOf(child); assertEquals(0, index); elements.add(1, anotherChild); elements = parent.elements(); assertEquals(child, elements.get(0)); assertEquals(anotherChild, elements.get(1)); } // Implementation methods // ------------------------------------------------------------------------- protected void testGetAttributes(Element author) throws Exception { String definedName = "name"; String undefinedName = "undefined-attribute-name"; String defaultValue = "** Default Value **"; String value = author.attributeValue(definedName, defaultValue); assertTrue("Defined value doesn't return specified default value", value != defaultValue); value = author.attributeValue(undefinedName, defaultValue); assertTrue("Undefined value returns specified default value", value == defaultValue); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/SetContentTest.java0000644000175000017500000001245210242120012021213 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; /** * Tests the setContent method * * @author James Strachan * @version $Revision: 1.3 $ */ public class SetContentTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(SetContentTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testDocument() throws Exception { document.setName("doc1"); Element oldRoot = document.getRootElement(); assertTrue("Current root has document", oldRoot.getDocument() == document); Document doc2 = DocumentHelper.createDocument(); doc2.setName("doc2"); assertTrue("Doc2 has no root element", doc2.getRootElement() == null); doc2.setContent(document.content()); Element newRoot = doc2.getRootElement(); assertTrue("Current root has document", oldRoot.getDocument() == document); assertTrue("Doc2 has now has root element", newRoot != null); assertTrue("Doc2 has different root element", newRoot != oldRoot); assertTrue("Root element now has document", newRoot.getDocument() == doc2); testParent(doc2.getRootElement()); testDocument(doc2, doc2); doc2.clearContent(); assertTrue("New Doc has no root", doc2.getRootElement() == null); assertTrue("New root has no document", newRoot.getDocument() == null); } public void testRootElement() throws Exception { Document doc3 = DocumentHelper.createDocument(); doc3.setName("doc3"); Element root = doc3.addElement("root"); Element oldElement = root.addElement("old"); assertTrue("Doc3 has root element", root != null); root.setContent(document.getRootElement().content()); assertTrue("Doc3's root now has content", root.nodeCount() > 0); assertTrue("Old element has no parent now", oldElement.getParent() == null); assertTrue("Old element has no document now", oldElement.getDocument() == null); testParent(root); testDocument(root, doc3); } /** * Tests all the children of the branch have the correct parent * * @param parent * DOCUMENT ME! */ protected void testParent(Branch parent) { for (int i = 0, size = parent.nodeCount(); i < size; i++) { Node node = parent.node(i); assertTrue("Child node of root has parent of root", node .getParent() == parent); } } /** * Tests all the children of the branch have the correct document * * @param branch * DOCUMENT ME! * @param doc * DOCUMENT ME! */ protected void testDocument(Branch branch, Document doc) { for (int i = 0, size = branch.nodeCount(); i < size; i++) { Node node = branch.node(i); assertTrue("Node has correct document", node.getDocument() == doc); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/RoundTripTest.java0000644000175000017500000002032410242120021021050 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.io.StringReader; import java.io.StringWriter; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.dom4j.io.DOMReader; import org.dom4j.io.DOMWriter; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; import org.dom4j.io.SAXContentHandler; import org.dom4j.io.SAXReader; import org.dom4j.io.SAXWriter; import org.dom4j.io.XMLWriter; /** * A test harness to test the the round trips of Documents. * * @author James Strachan * @version $Revision: 1.4 $ */ public class RoundTripTest extends AbstractTestCase { protected String[] testDocuments = {"/xml/test/encode.xml", "/xml/fibo.xml", "/xml/test/schema/personal-prefix.xsd", "/xml/test/soap2.xml", "/xml/test/test_schema.xml"}; public static void main(String[] args) { TestRunner.run(RoundTripTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testTextRoundTrip() throws Exception { for (int i = 0, size = testDocuments.length; i < size; i++) { Document doc = getDocument(testDocuments[i]); roundTripText(doc); } } public void testSAXRoundTrip() throws Exception { for (int i = 0, size = testDocuments.length; i < size; i++) { Document doc = getDocument(testDocuments[i]); roundTripSAX(doc); } } public void testDOMRoundTrip() throws Exception { for (int i = 0, size = testDocuments.length; i < size; i++) { Document doc = getDocument(testDocuments[i]); roundTripDOM(doc); } } public void testJAXPRoundTrip() throws Exception { for (int i = 0, size = testDocuments.length; i < size; i++) { Document doc = getDocument(testDocuments[i]); roundTripJAXP(doc); } } public void testFullRoundTrip() throws Exception { for (int i = 0, size = testDocuments.length; i < size; i++) { Document doc = getDocument(testDocuments[i]); roundTripFull(doc); } } public void testRoundTrip() throws Exception { Document document = getDocument("/xml/xmlspec.xml"); // Document doc1 = roundTripText( document ); Document doc1 = roundTripSAX(document); Document doc2 = roundTripDOM(doc1); Document doc3 = roundTripSAX(doc2); Document doc4 = roundTripText(doc3); Document doc5 = roundTripDOM(doc4); // Document doc5 = roundTripDOM( doc3 ); assertDocumentsEqual(document, doc5); } // Implementation methods // ------------------------------------------------------------------------- protected Document roundTripDOM(Document document) throws Exception { // now lets make a DOM object DOMWriter domWriter = new DOMWriter(); org.w3c.dom.Document domDocument = domWriter.write(document); // now lets read it back as a DOM4J object DOMReader domReader = new DOMReader(); Document newDocument = domReader.read(domDocument); // lets ensure names are same newDocument.setName(document.getName()); assertDocumentsEqual(document, newDocument); return newDocument; } protected Document roundTripJAXP(Document document) throws Exception { // output the document to a text buffer via JAXP TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); StringWriter buffer = new StringWriter(); StreamResult streamResult = new StreamResult(buffer); DocumentSource documentSource = new DocumentSource(document); transformer.transform(documentSource, streamResult); // now lets parse it back again via JAXP DocumentResult documentResult = new DocumentResult(); StreamSource streamSource = new StreamSource(new StringReader(buffer .toString())); transformer.transform(streamSource, documentResult); Document newDocument = documentResult.getDocument(); // lets ensure names are same newDocument.setName(document.getName()); assertDocumentsEqual(document, newDocument); return newDocument; } protected Document roundTripSAX(Document document) throws Exception { // now lets write it back as SAX events to // a SAX ContentHandler which should build up a new document SAXContentHandler contentHandler = new SAXContentHandler(); SAXWriter saxWriter = new SAXWriter(contentHandler, contentHandler, contentHandler); saxWriter.write(document); Document newDocument = contentHandler.getDocument(); // lets ensure names are same newDocument.setName(document.getName()); assertDocumentsEqual(document, newDocument); return newDocument; } protected Document roundTripText(Document document) throws Exception { StringWriter out = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(out); xmlWriter.write(document); // now lets read it back String xml = out.toString(); StringReader in = new StringReader(xml); SAXReader reader = new SAXReader(); Document newDocument = reader.read(in); // lets ensure names are same newDocument.setName(document.getName()); assertDocumentsEqual(document, newDocument); return newDocument; } protected Document roundTripFull(Document document) throws Exception { Document doc2 = roundTripDOM(document); Document doc3 = roundTripSAX(doc2); Document doc4 = roundTripText(doc3); assertDocumentsEqual(document, doc4); return doc4; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/ElementByIDTest.java0000644000175000017500000000675010242120010021230 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; /** * Tests the elementByID() method * * @author James Strachan * @version $Revision: 1.4 $ */ public class ElementByIDTest extends AbstractTestCase { /** Input XML file to read */ protected static final String INPUT_XML_FILE = "xml/test/elementByID.xml"; public static void main(String[] args) { TestRunner.run(ElementByIDTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testElementByID() throws Exception { String id = "message"; Document document = getDocument(INPUT_XML_FILE); // test XPath Element element = (Element) document.selectSingleNode("//*[@ID='" + id + "']"); assertTrue("Found element by ID: " + id, element != null); assertEquals("ID is equal", id, element.attributeValue("ID")); // test with elementByID element = document.elementByID(id); assertTrue("Found element by ID: " + id, element != null); assertEquals("ID is equal", id, element.attributeValue("ID")); log("Found element: " + element.getText()); element = document.elementByID("DoesNotExist"); assertTrue("Found no element", element == null); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/ParentTest.java0000644000175000017500000001103310242120011020347 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.Iterator; import java.util.List; /** * A test harness to test the parent relationship and use of the {@link * Node#asXPathResult} method. * * @author James Strachan * @version $Revision: 1.3 $ */ public class ParentTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(ParentTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testDocument() throws Exception { testParentRelationship(document.getRootElement()); } public void testFragment() throws Exception { DocumentFactory factory = new DocumentFactory(); Element root = factory.createElement("root"); Element first = root.addElement("child"); Element second = root.addElement("child"); testXPathNode(root, first); testXPathNode(root, second); } // Implementation methods // ------------------------------------------------------------------------- protected void testParentRelationship(Element parent, List content) { for (Iterator iter = content.iterator(); iter.hasNext();) { Object object = iter.next(); if (object instanceof Element) { testParentRelationship((Element) object); } testXPathNode(parent, (Node) object); } } protected void testParentRelationship(Element element) { testParentRelationship(element, element.attributes()); testParentRelationship(element, element.content()); } protected void testXPathNode(Element parent, Node node) { if (node.supportsParent()) { log("Node: " + node); log("Parent: " + parent); log("getParent(): " + node.getParent()); assertTrue("getParent() returns parent for: " + node, node .getParent() == parent); } else { // lets create an XPath node Node xpathNode = node.asXPathResult(parent); assertTrue("XPath Node supports parent for: " + xpathNode, xpathNode.supportsParent()); assertTrue("getParent() returns parent for: " + xpathNode, xpathNode.getParent() == parent); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/dtd/0000755000175000017500000000000012133227266016215 5ustar ebourgebourgdom4j-1.6.1/src/test/org/dom4j/dtd/ElementDeclTest.java0000644000175000017500000000722210242120003022060 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dtd; import junit.textui.TestRunner; import org.dom4j.AbstractTestCase; /** * Tests the {@link ElementDecl}functionality. Tests each of the property * access methods and the serialization mechanisms. Correct parsing is tested by * {@link DocTypeTest}. * *

*

* * @author Bryan Thompson * @author Maarten Coene * @version $Revision: 1.3 $ * * @todo The dom4j documentation needs to describe what representation SHOULD be * generated by {@link ElementDecl#toString()}. */ public class ElementDeclTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(ElementDeclTest.class); } // Test case(s) // ------------------------------------------------------------------------- /** * Test * *
     * 
     *  <!ELEMENT an-element (#PCDATA)>
     *  
     * 
*/ public void testSimpleElementDecl() { String expectedName = "an-element"; String expectedModel = "(#PCDATA)"; String expectedText = ""; ElementDecl actual = new ElementDecl(expectedName, expectedModel); assertEquals("name is correct", expectedName, actual.getName()); assertEquals("model is correct", expectedModel, actual.getModel()); assertEquals("toString() is correct", expectedText, actual.toString()); } // Implementation methods // ------------------------------------------------------------------------- } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/dtd/ExternalEntityDeclTest.java0000644000175000017500000001254010242120015023450 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dtd; import junit.textui.TestRunner; import org.dom4j.AbstractTestCase; /** * Tests the {@link ExternalEntityDecl}functionality. Tests each of the * property access methods and the serialization mechanisms. Correct parsing is * tested by {@link DocTypeTest}. * *

*

* * @author Bryan Thompson * @author Maarten Coene * @version $Revision: 1.3 $ * * @todo The dom4j documentation needs to describe what representation SHOULD be * generated by {@link ExternalEntityDecl#toString()}. * @todo Test support for NOTATION and NDATA when used as part of an external * entity declaration. dom4j does not appear to support NOTATION and NDATA * at this time. */ public class ExternalEntityDeclTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(ExternalEntityDeclTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testToString() { ExternalEntityDecl decl1 = new ExternalEntityDecl("name", null, "systemID"); ExternalEntityDecl decl2 = new ExternalEntityDecl("%name", null, "systemID"); assertEquals("", decl1.toString()); assertEquals("", decl2.toString()); } /** * Tests external entity declaration using only the SYSTEM identifier. */ public void testSystemId() { String expectedName = "anEntity"; String expectedPublicID = null; String expectedSystemID = "http://www.myorg.org/foo"; String expectedText = ""; ExternalEntityDecl actual = new ExternalEntityDecl(expectedName, expectedPublicID, expectedSystemID); assertEquals("name is correct", expectedName, actual.getName()); assertEquals("publicID is correct", expectedPublicID, actual .getPublicID()); assertEquals("systemID is correct", expectedSystemID, actual .getSystemID()); assertEquals("toString() is correct", expectedText, actual.toString()); } /** * Tests external entity declaration using both SYSTEM and PUBLIC * identifiers. */ public void testPublicIdSystemId() { String expectedName = "anEntity"; String expectedPublicID = "-//dom4j//DTD sample"; String expectedSystemID = "http://www.myorg.org/foo"; String expectedText = ""; ExternalEntityDecl actual = new ExternalEntityDecl(expectedName, expectedPublicID, expectedSystemID); assertEquals("name is correct", expectedName, actual.getName()); assertEquals("publicID is correct", expectedPublicID, actual .getPublicID()); assertEquals("systemID is correct", expectedSystemID, actual .getSystemID()); assertEquals("toString() is correct", expectedText, actual.toString()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/dtd/AttributeDeclTest.java0000644000175000017500000002255710242120012022442 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dtd; import junit.textui.TestRunner; import org.dom4j.AbstractTestCase; /** * Tests the {@link AttributeDecl}functionality. Tests each of the property * access methods and the serialization mechanisms. Correct parsing is tested by * {@link DocTypeTest}. * *

* There are several key variations that need to be tested both here and in * {@link DocTypeTest}, which is responsible for testing correct parsing of the * {@link DocumentType}. Those variations include the different * valueDefault and value variations so that we * can test for correct acceptance and correct rejection of attribute * declarations. *

* *

*

* * @author Bryan Thompson * @author Maarten Coene * @version $Revision: 1.3 $ * * @todo The dom4j documentation needs to describe what representation SHOULD be * generated by {@link AttributeDecl#toString()}. * @todo The dom4j AttributeDecl should expose some methods that make it easier * for people to use the DTD grammar, e.g., isFixed(), isRequired(), * isImplied(). */ public class AttributeDeclTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(AttributeDeclTest.class); } // Test case(s) // ------------------------------------------------------------------------- /** * Test * *
     * 
     *  <!ATTLIST foo bar ID #IMPLIED>
     *  
     * 
. */ public void testIdImpliedNone() { MyTestAttributeDecl decl = new MyTestAttributeDecl("foo", // elementName "bar", // attributeName "ID", // type "#IMPLIED", // valueDefault null, // value ""); assertSameAttributeDecl(decl, new AttributeDecl("foo", "bar", "ID", "#IMPLIED", null)); } /** * Test * *
     * 
     *  <!ATTLIST foo bar CDATA #FIXED \"goo\">
     *  
     * 
. */ public void testCDataFixedValue() { MyTestAttributeDecl decl = new MyTestAttributeDecl("foo", // elementName "bar", // attributeName "CDATA", // type "#FIXED", // valueDefault "goo", // value ""); assertSameAttributeDecl(decl, new AttributeDecl("foo", "bar", "CDATA", "#FIXED", "goo")); } /** * Test * *
     * 
     *  <!ATTLIST foo bar CDATA "goo">
     *  
     * 
. */ public void testCDataNoneValue() { MyTestAttributeDecl decl = new MyTestAttributeDecl("foo", // elementName "bar", // attributeName "CDATA", // type null, // valueDefault "goo", // value ""); assertSameAttributeDecl(decl, new AttributeDecl("foo", "bar", "CDATA", null, "goo")); } // Implementation methods // ------------------------------------------------------------------------- protected void assertSameAttributeDecl(MyTestAttributeDecl expected, AttributeDecl actual) { assertEquals("elementName is correct", expected.getElementName(), actual.getElementName()); assertEquals("attributeName is correct", expected.getAttributeName(), actual.getAttributeName()); assertEquals("type is correct", expected.getType(), actual.getType()); assertEquals("valueDefault is correct", expected.getValueDefault(), actual.getValueDefault()); assertEquals("toString() is correct", expected.getText(), actual .toString()); } /** * Helper is useful since we are trying to exhaustively test the ATTLIST * variations and their correct serialization. */ protected static class MyTestAttributeDecl { private String elName; private String attName; private String declType; private String defaultValue; private String declValue; private String txt; /** * DOCUMENT ME! * * @param elementName * The name of the element whose attribute is being * described. * @param attributeName * The name of the attribute. * @param type * The type of the declared attribute, e.g., CDATA, ID, * IDREF, IDREFS, ENTITY, ENTITIES, NMTOKEN, NKTOKENS * @param valueDefault * The type of default that applies for this attribute * declaration, e.g., #REQUIRED, #IMPLIED, #FIXED (in which * case the value MUST be non- null * and specifies the fixed value for the attribute, or * null if no valueDefault was specified in * the attribute declaration (in which case the value * MUST be non- null and specifies the default * value for the attribute). * @param value * The value of the attribute assigned in the attribute * declaration -or- null if no value was * provided in the attribute declaration. The value MUST be * null unless the valueDefault is * either "#FIXED" or null. * @param text * The text representation of the attribute declaration, * e.g., <!ATTLIST foo id ID #IMPLIED>. * * @todo The constructor and properties in {@link AttributeDecl}should * have some similar javadoc so that people more easily understand * the interaction and difference between the valueDefault * and value properties. The constructor SHOULD be clear * about whether and when the valueDefault and * value properties MUST be null. */ public MyTestAttributeDecl(String elementName, String attributeName, String type, String valueDefault, String value, String text) { elName = elementName; attName = attributeName; declType = type; defaultValue = valueDefault; declValue = value; txt = text; } public String getElementName() { return elName; } public String getAttributeName() { return attName; } public String getType() { return declType; } public String getValueDefault() { return defaultValue; } public String getValue() { return declValue; } public String getText() { return txt; } } // Class TestAttributeDecl } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/dtd/InternalEntityDeclTest.java0000644000175000017500000001277410242117777023500 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.dtd; import junit.textui.TestRunner; import org.dom4j.AbstractTestCase; /** * Tests the {@link InternalEntityDecl}functionality. Tests each of the * property access methods and the serialization mechanisms. Correct parsing is * tested by {@link DocTypeTest}. * *

*

* * @author Bryan Thompson * @author Maarten Coene * @version $Revision: 1.3 $ * * @todo The dom4j documentation needs to describe what representation SHOULD be * generated by {@link InternalEntityDecl#toString()}. */ public class InternalEntityDeclTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(InternalEntityDeclTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testToString() { InternalEntityDecl decl1 = new InternalEntityDecl("name", "value"); InternalEntityDecl decl2 = new InternalEntityDecl("%name", "value"); assertEquals("", decl1.toString()); assertEquals("", decl2.toString()); } /** * Tests parameter entity declaration, such as * *
     * 
     *  
     *   <!ENTITY % boolean "( true | false )">
     *   
     *  
     * 
* * Note: There is a required whitespace between the "%" and the name of the * entity. This whitespace is required in the declaration and is not allowed * when writing a reference to the entity, e.g., "%boolean;" is a legal * reference but not "% boolean;". * *

* Note: The "%" is part of the parameter entity name as reported by the SAX * API. See LexicalHandler , which * states: * *

     * 
     *  
     *   General entities are reported with their regular names,
     *   parameter entities have '%' prepended to their names, and the
     *   external DTD subset has the pseudo-entity name "[dtd]".
     *   
     *  
     * 
* *

*/ public void testParameterEntity() { String expectedName = "%boolean"; String expectedValue = "( true | false )"; String expectedText = ""; InternalEntityDecl actual = new InternalEntityDecl(expectedName, expectedValue); assertEquals("name is correct", expectedName, actual.getName()); assertEquals("value is correct", expectedValue, actual.getValue()); assertEquals("toString() is correct", expectedText, actual.toString()); } /** * Tests general entity declaration, such as: * *
     * 
     *  
     *   <!ENTITY foo "bar">
     *   
     *  
     * 
*/ public void testGeneralEntity() { String expectedName = "foo"; String expectedValue = "bar"; String expectedText = ""; InternalEntityDecl actual = new InternalEntityDecl(expectedName, expectedValue); assertEquals("name is correct", expectedName, actual.getName()); assertEquals("value is correct", expectedValue, actual.getValue()); assertEquals("toString() is correct", expectedText, actual.toString()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/BackedListTest.java0000644000175000017500000001231010242120017021130 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.List; import org.dom4j.io.XMLWriter; /** * A test harness to test the backed list feature of DOM4J * * @author James Strachan * @version $Revision: 1.3 $ */ public class BackedListTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(BackedListTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testXPaths() throws Exception { Element element = (Element) document.selectSingleNode("/root"); mutate(element); element = (Element) document.selectSingleNode("//author"); mutate(element); } public void testAddRemove() throws Exception { Element parentElement = (Element) document.selectSingleNode("/root"); List children = parentElement.elements(); int lastPos = children.size() - 1; Element child = (Element) children.get(lastPos); try { // should throw an exception cause we cannot add same child twice children.add(0, child); fail(); } catch (IllegalAddException e) { } } public void testAddWithIndex() throws Exception { DocumentFactory factory = DocumentFactory.getInstance(); Element root = (Element) document.selectSingleNode("/root"); List children = root.elements(); // return a list of 2 author // elements assertEquals(2, children.size()); children.add(1, factory.createElement("dummy1")); children = root.elements(); assertEquals(3, children.size()); children = root.elements("author"); assertEquals(2, children.size()); children.add(1, factory.createElement("dummy2")); children = root.elements(); assertEquals(4, children.size()); assertEquals("dummy1", ((Node) children.get(1)).getName()); assertEquals("dummy2", ((Node) children.get(2)).getName()); /* * Some tests for issue reported at http://tinyurl.com/4jxrc */ children.add(children.size(), factory.createElement("dummy3")); children = root.elements("author"); children.add(children.size(), factory.createElement("dummy4")); } // Implementation methods // ------------------------------------------------------------------------- protected void mutate(Element element) throws Exception { DocumentFactory factory = DocumentFactory.getInstance(); List list = element.elements(); list.add(factory.createElement("last")); list.add(0, factory.createElement("first")); List list2 = element.elements(); assertTrue("Both lists should contain same number of elements", list .size() == list2.size()); XMLWriter writer = new XMLWriter(System.out); log("Element content is now: " + element.content()); writer.write(element); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/LineFeedTest.java0000644000175000017500000001055210242120010020575 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.io.StringWriter; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class LineFeedTest extends AbstractTestCase { private static final String ATT_TEXT = "Hello There <>&"; private static final String TEXT = "Hello\nThere\n<>&"; private static final String EXPECTED_TEXT = "Hello\nThere\n<>&"; private static final String EXPECTED_ATT_TEXT = "Hello There <>&"; public static void main(String[] args) { TestRunner.run(LineFeedTest.class); } public void testElement() throws Exception { Document doc = DocumentHelper.parseText("" + TEXT + ""); Element elem = doc.getRootElement(); assertEquals(EXPECTED_TEXT, elem.getText()); } public void testAttribute() throws Exception { Document doc = DocumentHelper .parseText(""); Element elem = doc.getRootElement(); // System.out.println(elem.attributeValue("attr")); assertEquals(EXPECTED_ATT_TEXT, elem.attributeValue("attr")); doc = DocumentHelper.parseText(""); elem = doc.getRootElement(); // System.out.println(elem.attributeValue("attr")); assertEquals(EXPECTED_TEXT, elem.attributeValue("attr")); } public void testCDATA() throws Exception { Document doc = DocumentHelper.parseText(""); Element elem = doc.getRootElement(); assertEquals(EXPECTED_TEXT, elem.getText()); } public void testXmlWriter() throws Exception { Element elem = DocumentHelper.createElement("elem"); Document doc = DocumentHelper.createDocument(elem); elem.addCDATA(EXPECTED_TEXT); StringWriter sw = new StringWriter(); XMLWriter xWriter = new XMLWriter(sw, OutputFormat.createPrettyPrint()); xWriter.write(doc); xWriter.close(); String xmlString = sw.toString(); doc = DocumentHelper.parseText(xmlString); elem = doc.getRootElement(); assertEquals(EXPECTED_TEXT, elem.getText()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/SAXContentHandlerTest.java0000644000175000017500000001071310242120020022406 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.dom4j.io.SAXContentHandler; import org.xml.sax.XMLReader; public class SAXContentHandlerTest extends AbstractTestCase { private XMLReader xmlReader; protected String[] testDocuments = {"/xml/test/test_schema.xml", "/xml/test/encode.xml", "/xml/fibo.xml", "/xml/test/schema/personal-prefix.xsd", "/xml/test/soap2.xml"}; public static void main(String[] args) { TestRunner.run(SAXContentHandlerTest.class); } protected void setUp() throws Exception { super.setUp(); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); SAXParser parser = spf.newSAXParser(); xmlReader = parser.getXMLReader(); } public void testSAXContentHandler() throws Exception { SAXContentHandler contentHandler = new SAXContentHandler(); xmlReader.setContentHandler(contentHandler); xmlReader.setDTDHandler(contentHandler); xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", contentHandler); for (int i = 0, size = testDocuments.length; i < size; i++) { Document docFromSAXReader = getDocument(testDocuments[i]); xmlReader.parse(getFile(testDocuments[i]).toString()); Document docFromSAXContentHandler = contentHandler.getDocument(); docFromSAXContentHandler.setName(docFromSAXReader.getName()); assertDocumentsEqual(docFromSAXReader, docFromSAXContentHandler); assertEquals(docFromSAXReader.asXML(), docFromSAXContentHandler .asXML()); } } public void testBug926713() throws Exception { Document doc = getDocument("/xml/test/cdata.xml"); Element foo = doc.getRootElement(); Element bar = foo.element("bar"); List content = bar.content(); assertEquals(3, content.size()); assertEquals(Node.TEXT_NODE, ((Node) content.get(0)).getNodeType()); assertEquals(Node.CDATA_SECTION_NODE, ((Node) content.get(1)) .getNodeType()); assertEquals(Node.TEXT_NODE, ((Node) content.get(2)).getNodeType()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/datatype/0000755000175000017500000000000012133227266017255 5ustar ebourgebourgdom4j-1.6.1/src/test/org/dom4j/datatype/ManualSchemaPrefixTest.java0000644000175000017500000000610710242120005024456 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.datatype; import junit.textui.TestRunner; import org.dom4j.Document; import org.dom4j.DocumentFactory; /** * Test harness for the XML Schema Data Type integration. These tests manually * load the schemas using prefixes in the XSD file. * * @author James Strachan * @version $Revision: 1.4 $ */ public class ManualSchemaPrefixTest extends AutoSchemaTest { public static void main(String[] args) { TestRunner.run(ManualSchemaPrefixTest.class); } // Implementation methods // ------------------------------------------------------------------------- protected DocumentFactory loadDocumentFactory() throws Exception { DatatypeDocumentFactory factory = new DatatypeDocumentFactory(); Document schemaDocument = getDocument("/xml/test/schema/personal-prefix.xsd"); factory.loadSchema(schemaDocument); return factory; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/datatype/SetDataTest.java0000644000175000017500000001561010242120023022266 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.datatype; import junit.textui.TestRunner; import java.math.BigInteger; import org.dom4j.AbstractTestCase; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.QName; /** * Tests setting the value of datatype aware element or attribute value * * @author James Strachan * @version $Revision: 1.4 $ */ public class SetDataTest extends AbstractTestCase { private DatatypeDocumentFactory factory = new DatatypeDocumentFactory(); public static void main(String[] args) { TestRunner.run(SetDataTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testAttribute() throws Exception { QName personName = factory.createQName("person"); QName ageName = factory.createQName("age"); Element person = factory.createElement(personName); person.addAttribute(ageName, "10"); Attribute age = person.attribute(ageName); assertTrue("Created DatatypeAttribute not correct", age instanceof DatatypeAttribute); log("Found attribute: " + age); Object data = age.getData(); Object expected = new BigInteger("10"); assertEquals("Data is correct type", BigInteger.class, data.getClass()); assertEquals("Set age correctly", expected, data); age.setValue("32"); data = age.getData(); expected = new BigInteger("32"); assertEquals("Set age correctly", expected, data); /** * not sure if numeric types should be round tripped back to BigDecimal * (say) age.setData( new Long( 21 ) ); data = age.getData(); expected = * new BigInteger( "21" ); assertEquals( "Set age correctly", expected, * data ); */ // now lets set an invalid value try { age.setValue("abc"); fail("Appeared to set an invalid value"); } catch (IllegalArgumentException e) { } } public void testAttributeWithNamespace() throws Exception { QName personName = factory.createQName("person", "t", "urn://testing"); QName ageName = factory.createQName("age", "t", "urn://testing"); Element person = factory.createElement(personName); person.addAttribute(ageName, "10"); Attribute age = person.attribute(ageName); assertTrue("Created DatatypeAttribute not correct", age instanceof DatatypeAttribute); log("Found attribute: " + age); Object data = age.getData(); Object expected = new BigInteger("10"); assertEquals("Data is correct type", BigInteger.class, data.getClass()); assertEquals("Set age correctly", expected, data); age.setValue("32"); data = age.getData(); expected = new BigInteger("32"); assertEquals("Set age correctly", expected, data); try { age.setValue("abc"); fail("Appeared to set an invalid value"); } catch (IllegalArgumentException e) { } } public void testElement() throws Exception { QName personName = factory.createQName("person"); QName numberOfCarsName = factory.createQName("numberOfCars"); Element person = factory.createElement(personName); Element cars = person.addElement(numberOfCarsName); log("Found element: " + cars); Object expected = new Short((short) 10); cars.setData(expected); Object data = cars.getData(); assertEquals("Data is correct type", Short.class, data.getClass()); assertEquals("Set cars correctly", expected, data); cars.setData(new Short((short) 32)); data = cars.getData(); expected = new Short((short) 32); assertEquals("Set cars correctly", expected, data); cars.setText("34"); data = cars.getData(); expected = new Short((short) 34); assertEquals("Set cars correctly", expected, data); // now lets set an invalid value try { cars.setText("abc"); fail("Appeared to set an invalid value"); } catch (IllegalArgumentException e) { } } // Implementation methods // ------------------------------------------------------------------------- protected void setUp() throws Exception { super.setUp(); Document schema = getDocument("/xml/test/schema/personal.xsd"); factory.loadSchema(schema); Namespace ns = new Namespace("t", "urn://testing"); factory.loadSchema(schema, ns); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/datatype/ManualSchemaTest.java0000644000175000017500000000614510242117776023327 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.datatype; import junit.textui.TestRunner; import org.dom4j.Document; import org.dom4j.DocumentFactory; /** * Test harness for the XML Schema Data Type integration. These tests manually * load the schemas * * @author James Strachan * @version $Revision: 1.4 $ */ public class ManualSchemaTest extends AutoSchemaTest { public static void main(String[] args) { TestRunner.run(ManualSchemaTest.class); } // Implementation methods // ------------------------------------------------------------------------- protected String getDocumentURI() { return "/xml/test/schema/personal.xml"; } protected DocumentFactory loadDocumentFactory() throws Exception { DatatypeDocumentFactory factory = new DatatypeDocumentFactory(); Document schemaDocument = getDocument("/xml/test/schema/personal.xsd"); factory.loadSchema(schemaDocument); return factory; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/datatype/SchemaParseTest.java0000644000175000017500000000616510242120000023134 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.datatype; import junit.textui.TestRunner; import org.dom4j.AbstractTestCase; import org.dom4j.Document; import org.dom4j.io.SAXReader; /** * Tests the SchemaParser based on a test case provided by Luis Pea Snchez * * @author James Strachan * @version $Revision: 1.4 $ */ public class SchemaParseTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(SchemaParseTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testParseSchema() throws Exception { DatatypeDocumentFactory factory = new DatatypeDocumentFactory(); SAXReader reader = new SAXReader(); reader.setDocumentFactory(factory); Document schema = getDocument("/xml/test/LuisSchema.xsd", reader); factory.loadSchema(schema); log("Loaded the schema"); // now load an instance document } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/datatype/Datatype2Test.java0000644000175000017500000002660410242120010022577 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.datatype; import junit.textui.TestRunner; import java.io.StringReader; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.SimpleTimeZone; import java.util.TimeZone; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * Test harness for XML Schema Datatypes support * * @author Yuxin Ruan * @version $Revision: 1.3 $ */ public class Datatype2Test extends AbstractDataTypeTestCase { public static final int YEAR = 2001; public static final int MONTH = 10; public static final int DATE = 31; public static void main(String[] args) { TestRunner.run(Datatype2Test.class); } public void testSchema() throws Exception { Document schema = getSchema(); validateDocumentWithSchema(schema); } public void testSchemaWithNamedComplexType() throws Exception { Document schema = getSchemaWithNamedComplexType(); validateDocumentWithSchema(schema); } public void testSchemaWithReference() throws Exception { Document schema = getSchemaWithReference(); validateDocumentWithSchema(schema); } public void testSchemaWithNamedSimpleType() throws Exception { Document schema = getSchemaWithNamedSimpleType(); validateDocumentWithSchema(schema); } private void validateDocumentWithSchema(Document schema) throws Exception { Document doc = getSource(schema); Element root = doc.getRootElement(); validateLongAttribute(root); validateFloatElement(root); validateDateElement(root); } private void validateLongAttribute(Element root) throws Exception { Attribute attr = root.attribute("longAttribute"); Object attrData = attr.getData(); validateData("testLongAttribute", attrData, new Long(123)); System.out.println("retrieved attribute " + attrData); } private void validateFloatElement(Element root) throws Exception { Element elem = root.element("floatElement"); Object elemData = elem.getData(); validateData("testFloatElement", elemData, new Float(1.23)); System.out.println("retrieved element:" + elemData); } private void validateDateElement(Element root) throws Exception { Element elem = root.element("dateElement"); Object elemData = elem.getData(); Calendar expected = getDate(); System.out.println("retrieved element:" + elemData); // don't compare the Calendar instances, compare their strings instead! assertTrue(elemData instanceof Calendar); Calendar elemCal = (Calendar) elemData; DateFormat format = new SimpleDateFormat("MM/dd/yyyyZ"); format.setTimeZone(elemCal.getTimeZone()); String elemStr = format.format(elemCal.getTime()); format.setTimeZone(expected.getTimeZone()); String expectedStr = format.format(expected.getTime()); assertEquals("testDateElement", expectedStr, elemStr); } private void validateData(String test, Object retrieved, Object expected) throws Exception { Class retrievedClass = retrieved.getClass(); Class expectedClass = expected.getClass(); // compare class if (!expectedClass.equals(retrievedClass)) { String msg = "class mismatch in " + test + ":expected " + expectedClass + ", retrieved " + retrievedClass; throw new Exception(msg); } // compare value if (!expected.equals(retrieved)) { String msg = "value mismatch in " + test + ":expected " + expected + ", retrieved " + retrieved; throw new Exception(msg); } } private Document getSource(Document schema) throws Exception { StringBuffer b = new StringBuffer(); b.append(""); b.append(""); b.append(" 1.23"); b.append(" " + getDateString() + ""); b.append(""); StringReader in = new StringReader(b.toString()); DatatypeDocumentFactory docFactory = new DatatypeDocumentFactory(); docFactory.loadSchema(schema); SAXReader parser = new SAXReader(docFactory); return parser.read(in); } private Document getSchema() throws Exception { StringBuffer b = new StringBuffer(); b.append(""); b.append(""); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(""); StringReader in = new StringReader(b.toString()); SAXReader parser = new SAXReader(); return parser.read(in); } private Document getSchemaWithNamedComplexType() throws Exception { StringBuffer b = new StringBuffer(); b.append(""); b.append(""); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(""); StringReader in = new StringReader(b.toString()); SAXReader parser = new SAXReader(); return parser.read(in); } private Document getSchemaWithReference() throws Exception { StringBuffer b = new StringBuffer(); b.append(""); b.append(""); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(""); StringReader in = new StringReader(b.toString()); SAXReader parser = new SAXReader(); return parser.read(in); } private Document getSchemaWithNamedSimpleType() throws Exception { StringBuffer b = new StringBuffer(); b.append(""); b.append(""); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(" "); b.append(""); StringReader in = new StringReader(b.toString()); SAXReader parser = new SAXReader(); return parser.read(in); } private static String getDateString() { // return dateTime in ISO8601 format String yyyy = Integer.toString(YEAR); String mm = Integer.toString(MONTH); String dd = Integer.toString(DATE); return yyyy + "-" + mm + "-" + dd + "Z"; } private static Calendar getDate() { Calendar calendar = new GregorianCalendar(); calendar.clear(); calendar.set(Calendar.YEAR, YEAR); calendar.set(Calendar.MONTH, MONTH - 1); calendar.set(Calendar.DAY_OF_MONTH, DATE); calendar.setTimeZone(TimeZone.getTimeZone("UTC")); calendar.setTimeZone(new SimpleTimeZone(0, "XSD 'Z' timezone")); return calendar; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/datatype/DataTypesTest.java0000644000175000017500000001427710242120025022651 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.datatype; import junit.textui.TestRunner; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Calendar; import org.dom4j.DocumentFactory; import org.dom4j.io.SAXReader; /** * Test harness to test the various data types supported in the XML Schema Data * Type integration. * * @author James Strachan * @version $Revision: 1.4 $ */ public class DataTypesTest extends AbstractDataTypeTestCase { public static void main(String[] args) { TestRunner.run(DataTypesTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testgMonthDay() throws Exception { testNodes("//gMonthDayTag", Calendar.class); } public void testgDay() throws Exception { testNodes("//gDayTag", Calendar.class); } public void testgMonth() throws Exception { testNodes("//gMonthTag", Calendar.class); } public void testDate() throws Exception { testNodes("//dateTag", Calendar.class); } public void testTime() throws Exception { testNodes("//timeTag", Calendar.class); } public void testDateTime() throws Exception { testNodes("//dateTimeTag", Calendar.class); } public void testgYearMonth() throws Exception { testNodes("//gYearMonthTag", Calendar.class); } public void testgYear() throws Exception { testNodes("//gYearTag", Calendar.class); } public void testBoolean() throws Exception { testNodes("//booleanTag", Boolean.class); } public void testBase64Binary() throws Exception { testNodes("//base64BinaryTag", byte[].class); } public void testHexBinary() throws Exception { testNodes("//hexBinaryTag", byte[].class); } // Number types public void testFloat() throws Exception { testNodes("//floatTag", Float.class); } public void testDouble() throws Exception { testNodes("//doubleTag", Double.class); } public void testDecimal() throws Exception { testNodes("//decimalTag", BigDecimal.class); } public void testInteger() throws Exception { testNodes("//integerTag", BigInteger.class); } public void testNonPositiveInteger() throws Exception { testNodes("//nonPositiveIntegerTag", BigInteger.class); } public void testNegativeInteger() throws Exception { testNodes("//negativeIntegerTag", BigInteger.class); } public void testLong() throws Exception { testNodes("//longTag", Long.class); } public void testInt() throws Exception { testNodes("//intTag", Integer.class); } public void testShort() throws Exception { testNodes("//shortTag", Short.class); } public void testByte() throws Exception { testNodes("//byteTag", Byte.class); } public void testNonNegativeInteger() throws Exception { testNodes("//nonNegativeIntegerTag", BigInteger.class); } public void testUnsignedLong() throws Exception { testNodes("//unsignedLongTag", BigInteger.class); } public void testUnsignedInt() throws Exception { testNodes("//unsignedIntTag", Long.class); } public void testUnsignedShort() throws Exception { testNodes("//unsignedShortTag", Integer.class); } public void testUnsignedByte() throws Exception { testNodes("//unsignedByteTag", Short.class); } public void testPositiveInteger() throws Exception { testNodes("//positiveIntegerTag", BigInteger.class); } // Implementation methods // ------------------------------------------------------------------------- protected void setUp() throws Exception { super.setUp(); DocumentFactory factory = DatatypeDocumentFactory.getInstance(); SAXReader reader = new SAXReader(factory); document = getDocument("/xml/test/schema/test.xml", reader); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/datatype/AbstractDataTypeTestCase.java0000644000175000017500000000747210242120000024736 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.datatype; import java.util.Iterator; import java.util.List; import org.dom4j.AbstractTestCase; import org.dom4j.Attribute; import org.dom4j.Element; import org.dom4j.Node; /** * Abstract base class useful for implementation inheritence for testing XML * Schema Data Type integration. * * @author James Strachan * @version $Revision: 1.3 $ */ public class AbstractDataTypeTestCase extends AbstractTestCase { // Implementation methods // ------------------------------------------------------------------------- protected void testNodes(String xpath, Class type) { List list = document.selectNodes(xpath); assertTrue("Results are not empty", !list.isEmpty()); for (Iterator iter = list.iterator(); iter.hasNext();) { Node node = (Node) iter.next(); if (node instanceof Element) { Element element = (Element) node; testDataType(element, element.getData(), type); } else if (node instanceof Attribute) { Attribute attribute = (Attribute) node; testDataType(attribute, attribute.getData(), type); } else { assertTrue("Did not find an attribute or element: " + node, false); } } } protected void testDataType(Node node, Object data, Class type) { assertTrue("Data object is not null", data != null); assertTrue("Data object is of the correct type. Expected: " + type.getName() + " and found: " + data.getClass().getName(), type.isAssignableFrom(data.getClass())); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/datatype/AutoSchemaTest.java0000644000175000017500000001003010242120007022763 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.datatype; import junit.textui.TestRunner; import java.math.BigInteger; import java.util.Calendar; import org.dom4j.DocumentFactory; import org.dom4j.io.SAXReader; /** * Test harness for the XML Schema Data Type integration. These tests use * auto-loading of the XML Schema document * * @author James Strachan * @version $Revision: 1.4 $ */ public class AutoSchemaTest extends AbstractDataTypeTestCase { public static void main(String[] args) { TestRunner.run(AutoSchemaTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testIntAttribute() throws Exception { testNodes("//person/@x", Integer.class); } public void testIntElement() throws Exception { testNodes("//person/salary", Integer.class); } public void testString() throws Exception { testNodes("//person/note", String.class); } public void testDate() throws Exception { testNodes("//person/@d", Calendar.class); } public void testDateTime() throws Exception { testNodes("//person/@dt", Calendar.class); } public void testInteger() throws Exception { testNodes("//person/@age", BigInteger.class); } // Implementation methods // ------------------------------------------------------------------------- protected void setUp() throws Exception { super.setUp(); DocumentFactory factory = loadDocumentFactory(); SAXReader reader = new SAXReader(factory); document = getDocument(getDocumentURI(), reader); } protected String getDocumentURI() { return "/xml/test/schema/personal-schema.xml"; } protected DocumentFactory loadDocumentFactory() throws Exception { return DatatypeDocumentFactory.getInstance(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/AddAttributeTest.java0000644000175000017500000000724610242120014021510 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; /** * A test harness to test the addAttribute() methods on attributes * * @author Maarten Coene */ public class AddAttributeTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(AddAttributeTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testAddAttributeNormalValue() throws Exception { String testAttributeName = "testAtt"; String testAttributeValue = "testValue"; Node authorNode = document.selectSingleNode("//root/author[1]"); assertTrue(authorNode instanceof Element); Element authorEl = (Element) authorNode; authorEl.addAttribute(testAttributeName, testAttributeValue); assertEquals(3, authorEl.attributeCount()); assertEquals(testAttributeValue, authorEl .attributeValue(testAttributeName)); } public void testAddAttributeNullValue() throws Exception { String testAttributeName = "location"; String testAttributeValue = null; Node authorNode = document.selectSingleNode("//root/author[1]"); assertTrue(authorNode instanceof Element); Element authorEl = (Element) authorNode; authorEl.addAttribute(testAttributeName, testAttributeValue); assertEquals(1, authorEl.attributeCount()); assertNull(authorEl.attributeValue(testAttributeName)); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/NullAttributesTest.java0000644000175000017500000001066510242120011022111 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; /** * Tests the use of null attribute values * * @author James Strachan * @version $Revision: 1.3 $ */ public class NullAttributesTest extends AbstractTestCase { protected DocumentFactory factory = DocumentFactory.getInstance(); protected Document document = factory.createDocument(); protected Element element = document.addElement("root"); public static void main(String[] args) { TestRunner.run(NullAttributesTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testStringNames() throws Exception { element.addAttribute("foo", null); Attribute attribute = element.attribute("foo"); assertTrue(attribute == null); element.addAttribute("foo", "123"); attribute = element.attribute("foo"); assertTrue(attribute != null); element.addAttribute("foo", null); attribute = element.attribute("foo"); assertTrue(attribute == null); } public void testQNames() throws Exception { QName bar = QName.get("bar"); element.addAttribute(bar, null); Attribute attribute = element.attribute(bar); assertTrue(attribute == null); element.addAttribute(bar, "123"); attribute = element.attribute(bar); assertTrue(attribute != null); element.addAttribute(bar, null); attribute = element.attribute(bar); assertTrue(attribute == null); } public void testAttributes() throws Exception { Attribute attribute = factory.createAttribute(element, "v", null); assertTrue(attribute.getText() == null); assertTrue(attribute.getValue() == null); element.add(attribute); attribute = element.attribute("v"); assertTrue(attribute == null); attribute = factory.createAttribute(element, "v", "123"); element.add(attribute); attribute = element.attribute("v"); assertTrue(attribute != null); attribute = factory.createAttribute(element, "v", null); element.add(attribute); attribute = element.attribute("v"); assertTrue(attribute == null); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/IndexedElementTest.java0000644000175000017500000000763510242120010022024 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import junit.textui.TestRunner; import java.util.List; import org.dom4j.util.IndexedDocumentFactory; /** * A test harness for the IndexedElement implementation * * @author James Strachan * @version $Revision: 1.3 $ */ public class IndexedElementTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(IndexedElementTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testXPaths() throws Exception { testXPath("//author"); } // Implementation methods // ------------------------------------------------------------------------- protected void testXPath(String xpath) { List list = document.selectNodes(xpath); log("Searched path: " + xpath); log("Found : " + list.size() + " result(s)"); log("Results"); if (list == null) { log("null"); } else { log("["); for (int i = 0, size = list.size(); i < size; i++) { Object object = list.get(i); String text = "null"; if (object instanceof Node) { Node node = (Node) object; text = node.asXML(); } else if (object != null) { text = object.toString(); } log(" " + text); } log("]"); } log("..........................................."); assertTrue("Found some results", list.size() > 0); } protected Document createDocument() { return IndexedDocumentFactory.getInstance().createDocument(); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/0000755000175000017500000000000012133227266016566 5ustar ebourgebourgdom4j-1.6.1/src/test/org/dom4j/xpath/SortByTest.java0000644000175000017500000000642210242120014021475 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import java.io.File; import java.util.List; import org.dom4j.AbstractTestCase; import org.dom4j.io.SAXReader; /** * Test harness for the sorting version of the selectNodes() function * * @author James Strachan * @version $Revision: 1.3 $ */ public class SortByTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(SortByTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testXPaths() throws Exception { List list = document.selectNodes("//SPEAKER", "NAME"); log("Number of SPEAKER instances: " + list.size()); List noDuplicates = document.selectNodes("//SPEAKER", ".", true); log("Number of distinct SPEAKER instances: " + noDuplicates.size()); log("Number of distinct SPEAKER instances: " + noDuplicates.size()); } protected void setUp() throws Exception { super.setUp(); document = new SAXReader().read(new File("xml/much_ado.xml")); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/PrefixTest.java0000644000175000017500000000775410242120016021523 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import java.io.File; import java.util.List; import org.dom4j.AbstractTestCase; import org.dom4j.DocumentHelper; import org.dom4j.XPath; import org.dom4j.io.SAXReader; import org.jaxen.SimpleNamespaceContext; /** * Tests finding items using a namespace prefix * * @author James Strachan * @version $Revision: 1.3 $ */ public class PrefixTest extends AbstractTestCase { protected static String[] paths = {"//xplt:anyElement", "//xpl:insertText", "/Template/Application1/xpl:insertText", "/Template/Application2/xpl:insertText"}; public static void main(String[] args) { TestRunner.run(PrefixTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testXPaths() throws Exception { int size = paths.length; for (int i = 0; i < size; i++) { testXPath(paths[i]); } } // Implementation methods // ------------------------------------------------------------------------- protected void testXPath(String xpathText) { XPath xpath = DocumentHelper.createXPath(xpathText); SimpleNamespaceContext context = new SimpleNamespaceContext(); context.addNamespace("xplt", "www.xxxx.com"); context.addNamespace("xpl", "www.xxxx.com"); xpath.setNamespaceContext(context); List list = xpath.selectNodes(document); log("Searched path: " + xpathText + " found: " + list.size() + " result(s)"); assertTrue("Should have found at lest one result", list.size() > 0); } protected void setUp() throws Exception { super.setUp(); document = new SAXReader().read(new File("xml/testNamespaces.xml")); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/AttributeTest.java0000644000175000017500000001022610242120013022212 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import java.util.Iterator; import java.util.List; import org.dom4j.AbstractTestCase; import org.dom4j.Attribute; import org.dom4j.DocumentHelper; import org.dom4j.XPath; /** * Test harness for the attribute axis * * @author James Strachan * @version $Revision: 1.3 $ */ public class AttributeTest extends AbstractTestCase { protected static String[] paths = {"attribute::*", "/root/author/attribute::*", "//attribute::*", "@name"}; public static void main(String[] args) { TestRunner.run(AttributeTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testXPaths() throws Exception { int size = paths.length; for (int i = 0; i < size; i++) { testXPath(paths[i]); } } // Implementation methods // ------------------------------------------------------------------------- protected void testXPath(String xpathText) { XPath xpath = DocumentHelper.createXPath(xpathText); List list = xpath.selectNodes(document); log("Searched path: " + xpathText + " found: " + list.size() + " result(s)"); for (Iterator iter = list.iterator(); iter.hasNext();) { Object object = iter.next(); log("Found Result: " + object); assertTrue("Results should be Attribute objects", object instanceof Attribute); Attribute attribute = (Attribute) object; assertTrue("Results should support the parent relationship", attribute.supportsParent()); assertTrue( "Results should contain reference to the parent element", attribute.getParent() != null); assertTrue("Resulting document not correct", attribute .getDocument() != null); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/TextTest.java0000644000175000017500000000747310242117776021233 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import java.util.Iterator; import java.util.List; import org.dom4j.AbstractTestCase; import org.dom4j.Text; /** * Test harness for the text() function * * @author James Strachan * @version $Revision: 1.3 $ */ public class TextTest extends AbstractTestCase { protected static String[] paths = {"text()", "//author/text()"}; public static void main(String[] args) { TestRunner.run(TextTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testXPaths() throws Exception { int size = paths.length; for (int i = 0; i < size; i++) { testXPath(paths[i]); } } // Implementation methods // ------------------------------------------------------------------------- protected void testXPath(String xpath) { List list = document.selectNodes(xpath); for (Iterator iter = list.iterator(); iter.hasNext();) { Object object = iter.next(); log("Found Result: " + object); assertTrue("Results not Text objects", object instanceof Text); Text text = (Text) object; assertTrue("Results should support the parent relationship", text .supportsParent()); assertTrue( "Results should contain reference to the parent element", text.getParent() != null); assertTrue("Results should not reference to the owning document", text.getDocument() != null); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/VariableTest.java0000644000175000017500000001035110242120021021772 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import java.util.List; import org.dom4j.AbstractTestCase; import org.dom4j.DocumentHelper; import org.dom4j.Node; import org.dom4j.XPath; import org.jaxen.SimpleVariableContext; /** * Test harness for the valueOf() function * * @author James Strachan * @version $Revision: 1.4 $ */ public class VariableTest extends AbstractTestCase { // TODO: uncomment these if jaxen bug is fixed // http://jira.codehaus.org/browse/JAXEN-73 protected static String[] paths = { "$author", // "$author/@name", // "$root/author", // "$root/author[1]", // "$root/author[1]/@name", // "$author/@name" }; private SimpleVariableContext variableContext = new SimpleVariableContext(); private Node rootNode; private Node authorNode; public static void main(String[] args) { TestRunner.run(VariableTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testXPaths() throws Exception { int size = paths.length; for (int i = 0; i < size; i++) { testXPath(paths[i]); } } protected void testXPath(String xpathText) { XPath xpath = createXPath(xpathText); List list = xpath.selectNodes(document); log("Searched path: " + xpathText + " found: " + list.size() + " result(s)"); assertTrue("Results should not contain the root node", !list .contains(rootNode)); } protected XPath createXPath(String xpath) { return DocumentHelper.createXPath(xpath, variableContext); } protected void setUp() throws Exception { super.setUp(); rootNode = document.selectSingleNode("/root"); authorNode = document.selectSingleNode("/root/author[1]"); variableContext.setVariableValue("root", rootNode); variableContext.setVariableValue("author", authorNode); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/SubstringTest.java0000644000175000017500000000765410242120016022245 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import java.io.File; import java.util.List; import org.dom4j.AbstractTestCase; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * Test harness for the substring function * * @author James Strachan * @version $Revision: 1.3 $ */ public class SubstringTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(SubstringTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testSubstring() throws Exception { String[] results1 = {"1100", "1101"}; testSubstring("//field[substring(@id,1,2)='11']", results1); String[] results2 = {"2111", "3111"}; testSubstring("//field[substring(@id,3)='11']", results2); } // Implementation methods // ------------------------------------------------------------------------- protected void testSubstring(String path, String[] results) throws Exception { log("Using XPath: " + path); List list = document.selectNodes(path); log("Found: " + list); // Object object = list.get(0); // log( "(0) = " + object + " type: " + object.getClass() ); int size = results.length; assertTrue("List should contain " + size + " results: " + list, list .size() == size); for (int i = 0; i < size; i++) { Element element = (Element) list.get(i); assertEquals(element.attributeValue("id"), results[i]); } } protected void setUp() throws Exception { super.setUp(); document = new SAXReader().read(new File("xml/test/fields.xml")); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/NumberTest.java0000644000175000017500000001046510242120023021505 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import org.dom4j.AbstractTestCase; import org.dom4j.Node; import org.dom4j.XPath; /** * Test harness for numeric XPath expressions * * @author James Strachan * @version $Revision: 1.3 $ */ public class NumberTest extends AbstractTestCase { protected static String[] paths = {"2+2", "2 + 2", "2 + number(1) + 2", "number(1) * 2", "2 + count(//author) + 2", "2 + (2 * 5)", "count(//author) + count(//author/attribute::*)", "(12 + count(//author) + count(//author/attribute::*)) div 2", "count(//author)", "count(//author/attribute::*)", "2 + number(1) * 2", "count(descendant::author)", "count(ancestor::author)", "count(descendant::*)", "count(descendant::author)+1", "count(ancestor::*)", "10 + count(ancestor-or-self::author) + 5", "10 + count(descendant::author) * 5", "10 + (count(descendant::author) * 5)"}; public static void main(String[] args) { TestRunner.run(NumberTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testXPaths() throws Exception { Node element = document.selectSingleNode("//author"); int size = paths.length; for (int i = 0; i < size; i++) { testXPath(document, paths[i]); testXPath(element, paths[i]); } log("Finished successfully"); } // Implementation methods // ------------------------------------------------------------------------- protected void testXPath(Node node, String xpathText) throws Exception { try { XPath xpath = node.createXPath(xpathText); Number number = xpath.numberValueOf(node); log("Searched path: " + xpathText + " found: " + number); } catch (Throwable e) { log("Caught exception: " + e); e.printStackTrace(); assertTrue("Failed to process: " + xpathText + " caught exception: " + e, false); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/NamespaceTest.java0000644000175000017500000001076010242120004022146 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import java.io.File; import java.util.Iterator; import java.util.List; import org.dom4j.AbstractTestCase; import org.dom4j.DocumentHelper; import org.dom4j.Namespace; import org.dom4j.XPath; import org.dom4j.io.SAXReader; /** * Test harness for the namespace axis * * @author James Strachan * @version $Revision: 1.3 $ */ public class NamespaceTest extends AbstractTestCase { protected static String[] paths = {"namespace::*", "/Template/Application1/namespace::*", "/Template/Application1/namespace::xplt", "//namespace::*"}; public static void main(String[] args) { TestRunner.run(NamespaceTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testXPaths() throws Exception { int size = paths.length; for (int i = 0; i < size; i++) { testXPath(paths[i]); } } // Implementation methods // ------------------------------------------------------------------------- protected void testXPath(String xpathText) { XPath xpath = DocumentHelper.createXPath(xpathText); List list = xpath.selectNodes(document); log("Searched path: " + xpathText + " found: " + list.size() + " result(s)"); for (Iterator iter = list.iterator(); iter.hasNext();) { Object object = iter.next(); log("Found Result: " + object); assertTrue("Results should be Namespace objects", object instanceof Namespace); Namespace namespace = (Namespace) object; log("Parent node: " + namespace.getParent()); assertTrue("Results should support the parent relationship", namespace.supportsParent()); assertTrue( "Results should contain reference to the parent element", namespace.getParent() != null); assertTrue("Results should contain reference to the document", namespace.getDocument() != null); } } protected void setUp() throws Exception { super.setUp(); document = new SAXReader().read(new File("xml/testNamespaces.xml")); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/UriMapTest.java0000644000175000017500000000667610242120002021460 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import java.io.File; import java.util.HashMap; import java.util.Map; import org.dom4j.AbstractTestCase; import org.dom4j.Node; import org.dom4j.XPath; import org.dom4j.io.SAXReader; /** * Tests the use of a Map for defining namespace URIs * * @author James Strachan * @version $Revision: 1.3 $ */ public class UriMapTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(UriMapTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testURIMap() throws Exception { Map uris = new HashMap(); uris.put("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/"); uris.put("m", "urn:xmethodsBabelFish"); String path = "/SOAP-ENV:Envelope/SOAP-ENV:Body/m:BabelFish"; XPath xpath = document.createXPath(path); xpath.setNamespaceURIs(uris); Node babelfish = xpath.selectSingleNode(document); // log( "Found: " + babelfish ); assertTrue("Found valid node", babelfish != null); } protected void setUp() throws Exception { super.setUp(); document = new SAXReader().read(new File("xml/soap.xml")); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/FilterTest.java0000644000175000017500000000741610242120016021506 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import java.util.Iterator; import java.util.List; import org.dom4j.AbstractTestCase; import org.dom4j.DocumentHelper; import org.dom4j.Node; import org.dom4j.NodeFilter; /** * Test harness for XPath filters * * @author James Strachan * @version $Revision: 1.3 $ */ public class FilterTest extends AbstractTestCase { protected static String[] paths = {".[name()='author']", ".[name()='XXXX']", ".[.='James Strachan']", ".[.='XXXX']"}; public static void main(String[] args) { TestRunner.run(FilterTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testXPaths() throws Exception { int size = paths.length; for (int i = 0; i < size; i++) { testXPath(paths[i]); } } // Implementation methods // ------------------------------------------------------------------------- protected void testXPath(String xpathExpression) { NodeFilter nodeFilter = DocumentHelper .createXPathFilter(xpathExpression); assertTrue("No NodeFilter object was created", nodeFilter != null); List list = document.selectNodes("//author"); for (Iterator iter = list.iterator(); iter.hasNext();) { Node node = (Node) iter.next(); if (nodeFilter.matches(node)) { log("Matches node: " + node.asXML()); } else { log("No match for node: " + node.asXML()); } } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/BooleanTest.java0000644000175000017500000000750410242120010021630 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import java.util.Iterator; import java.util.List; import org.dom4j.AbstractTestCase; import org.dom4j.DocumentHelper; import org.dom4j.Node; import org.dom4j.XPath; /** * Test harness for the boolean expressions * * @author James Strachan * @version $Revision: 1.3 $ */ public class BooleanTest extends AbstractTestCase { protected static String[] paths = {".[name()='author']", ".[.='James Strachan']", ".[name()='XXXX']", ".[.='XXXX']", "name()='author'", "name()='XXXX'", ".='James Strachan'", ".='XXXX'"}; public static void main(String[] args) { TestRunner.run(BooleanTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testXPaths() throws Exception { int size = paths.length; for (int i = 0; i < size; i++) { testXPath(paths[i]); } } // Implementation methods // ------------------------------------------------------------------------- protected void testXPath(String xpathExpression) { XPath xpath = DocumentHelper.createXPath(xpathExpression); assertTrue("No xpath object was created", xpath != null); log("Evaluating xpath: " + xpath); List list = document.selectNodes("//author"); for (Iterator iter = list.iterator(); iter.hasNext();) { Node node = (Node) iter.next(); testXPath(node, xpath); } } protected void testXPath(Node node, XPath xpath) { List list = xpath.selectNodes(node); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/ValueOfTest.java0000644000175000017500000001050110242120012021603 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import java.util.List; import org.dom4j.AbstractTestCase; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.XPath; /** * Test harness for the valueOf() function * * @author James Strachan * @version $Revision: 1.3 $ */ public class ValueOfTest extends AbstractTestCase { protected static String[] paths = {"/root", "//author", "//author/@name", "/root/author[1]", "/root/author[1]/@name", "/root/author[2]", "/root/author[2]/@name", "/root/author[3]", "/root/author[3]/@name", "name()", "name(.)", "name(..)", "name(child::node())", "name(parent::*)", "name(../*)", "name(../child::node())", "local-name()", "local-name(..)", "local-name(parent::*)", "local-name(../*)", "parent::*", "name(/.)", "name(/child::node())", "name(/*)", ".", "..", "../*", "../child::node()", "/.", "/*", "*", "/child::node()"}; public static void main(String[] args) { TestRunner.run(ValueOfTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testXPaths() throws Exception { Element root = document.getRootElement(); List children = root.elements("author"); Element child1 = (Element) children.get(0); testXPath(document); testXPath(root); testXPath(child1); } protected void testXPath(Node node) throws Exception { log("Testing XPath on: " + node); log("==============================="); int size = paths.length; for (int i = 0; i < size; i++) { testXPath(node, paths[i]); } } protected void testXPath(Node node, String xpathExpr) throws Exception { try { XPath xpath = node.createXPath(xpathExpr); String value = xpath.valueOf(node); log("valueOf: " + xpathExpr + " is: " + value); } catch (Throwable e) { e.printStackTrace(); assertTrue("Failed with exception: " + e, false); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/GetPathTest.java0000644000175000017500000001660410242120003021610 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import java.util.Iterator; import java.util.List; import org.dom4j.AbstractTestCase; import org.dom4j.Attribute; import org.dom4j.Branch; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.QName; /** * Test harness for the GetPath() method * * @author James Strachan * @version $Revision: 1.4 $ */ public class GetPathTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(GetPathTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testGetPath() throws Exception { log("Testing paths"); // testBranchPath( document ); testPath(document, "/"); Element root = document.getRootElement(); testPath(root, "/root"); List elements = root.elements(); testPath((Node) elements.get(0), "/root/author", "/root/author[1]"); for (int i = 0, size = elements.size(); i < size; i++) { String path = "/root/author"; String uniquePath = "/root/author"; String pathRel = "author"; String uniquePathRel = "author"; if (size > 1) { uniquePath = "/root/author[" + (i + 1) + "]"; uniquePathRel = "author[" + (i + 1) + "]"; } Element element = (Element) elements.get(i); testPath(element, path, uniquePath); testRelativePath(root, element, pathRel, uniquePathRel); Attribute attribute = element.attribute("name"); testPath(attribute, path + "/@name", uniquePath + "/@name"); testRelativePath(root, attribute, pathRel + "/@name", uniquePathRel + "/@name"); Element child = element.element("url"); testPath(child, path + "/url", uniquePath + "/url"); testRelativePath(root, child, pathRel + "/url", uniquePathRel + "/url"); } } public void testDefaultNamespace() throws Exception { Document doc = getDocument("/xml/test/defaultNamespace.xml"); Element root = doc.getRootElement(); testPath(root, "/*[name()='a']"); Element child = (Element) root.elements().get(0); testPath(child, "/*[name()='a']/*[name()='b']"); testRelativePath(root, child, "*[name()='b']"); } public void testBug770410() { Document doc = DocumentHelper.createDocument(); Element a = doc.addElement("a"); Element b = a.addElement("b"); Element c = b.addElement("c"); b.detach(); String relativePath = b.getPath(b); assertSame(b, b.selectSingleNode(relativePath)); } public void testBug569927() { Document doc = DocumentHelper.createDocument(); QName elName = DocumentFactory.getInstance().createQName("a", "ns", "uri://myuri"); Element a = doc.addElement(elName); QName attName = DocumentFactory.getInstance().createQName("attribute", "ns", "uri://myuri"); a = a.addAttribute(attName, "test"); Attribute att = a.attribute(attName); assertSame(att, doc.selectSingleNode(att.getPath())); assertSame(att, doc.selectSingleNode(att.getUniquePath())); } protected void testPath(Node node, String value) { testPath(node, value, value); } protected void testPath(Node node, String path, String uniquePath) { assertEquals("getPath expression should be what is expected", path, node.getPath()); assertEquals("getUniquePath expression should be what is expected", uniquePath, node.getUniquePath()); } protected void testRelativePath(Element context, Node node, String path) { testRelativePath(context, node, path, path); } protected void testRelativePath(Element context, Node node, String pathRel, String uniquePathRel) { assertEquals("relative getPath expression should be what is expected", pathRel, node.getPath(context)); assertEquals("relative getUniquePath expression not correct", uniquePathRel, node.getUniquePath(context)); } protected void testBranchPath(Branch branch) { testNodePath(branch); if (branch instanceof Element) { Element element = (Element) branch; for (Iterator iter = element.attributeIterator(); iter.hasNext();) { Node node = (Node) iter.next(); testNodePath(node); } } for (Iterator iter = branch.nodeIterator(); iter.hasNext();) { Node node = (Node) iter.next(); if (node instanceof Branch) { testBranchPath((Branch) node); } else { testNodePath(node); } } } protected void testNodePath(Node node) { String path = node.getPath(); log("Path: " + path + " node: " + node); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/ObjectTest.java0000644000175000017500000000644110242120020021457 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import org.dom4j.AbstractTestCase; import org.dom4j.Node; import org.dom4j.XPath; /** * Test harness for numeric XPath expressions * * @author James Strachan * @version $Revision: 1.3 $ */ public class ObjectTest extends AbstractTestCase { protected static String[] paths = {"name(/.)", "name()"}; public static void main(String[] args) { TestRunner.run(ObjectTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testXPaths() throws Exception { Node element = document.selectSingleNode("//author"); int size = paths.length; for (int i = 0; i < size; i++) { testXPath(document, paths[i]); testXPath(element, paths[i]); } } // Implementation methods // ------------------------------------------------------------------------- protected void testXPath(Node node, String xpathText) { XPath xpath = node.createXPath(xpathText); Object object = xpath.evaluate(node); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/SelectSingleNodeTest.java0000644000175000017500000001026310242120006023441 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import org.dom4j.AbstractTestCase; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Node; /** * Tests the selectSingleNode method * * @author James Strachan * @version $Revision: 1.4 $ */ public class SelectSingleNodeTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(SelectSingleNodeTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testSelectSingleNode() throws Exception { Document document = getDocument("/xml/test/jimBrain.xml"); Node node = document.selectSingleNode("/properties/client/threadsafe"); assertTrue("Found a valid node", node != null); Element server = (Element) document .selectSingleNode("/properties/server"); assertTrue("Found a valid server", server != null); Element root = document.getRootElement(); server = (Element) root.selectSingleNode("/properties/server"); assertTrue("Found a valid server", server != null); // try finding it via a relative path server = (Element) document.selectSingleNode("properties/server"); assertTrue("Found a valid server", server != null); // now lets use a relative path Element connection = (Element) server.selectSingleNode("db/connection"); assertTrue("Found a valid connection", connection != null); } /** * Test out Steen's bug * * @throws Exception * DOCUMENT ME! */ public void testSteensBug() throws Exception { Document document = getDocument("/xml/schema/personal.xsd"); String xpath = "/xs:schema/xs:element[@name='person']"; assertNotNull("element is null", document.selectSingleNode(xpath)); Element root = document.getRootElement(); assertNotNull("element is null", root.selectSingleNode(xpath)); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/MatrixConcatTest.java0000644000175000017500000000774210242117777022703 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import java.io.File; import java.util.List; import org.dom4j.AbstractTestCase; import org.dom4j.io.SAXReader; /** * Test harness for the matrix-concat extension function * * @author James Strachan * @version $Revision: 1.3 $ */ public class MatrixConcatTest extends AbstractTestCase { public static void main(String[] args) { TestRunner.run(MatrixConcatTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testMatrixConcat() throws Exception { String[] exp1 = {"EQUITY_CF1", "EQUITY_CF2", "EQUITY_CF3"}; String[] exp2 = {"EQUITY_BAR_CF1", "EQUITY_BAR_CF2", "EQUITY_BAR_CF3"}; testMatrixConcat("'EQUITY_',/product/cashflows/CashFlow/XREF", exp1); testMatrixConcat("'EQUITY_','BAR_',/product/cashflows/CashFlow/XREF", exp2); } // Implementation methods // ------------------------------------------------------------------------- protected void testMatrixConcat(String path, String[] results) throws Exception { log("Using XPath: " + path); List list = document.selectNodes("matrix-concat(" + path + ")"); log("Found: " + list); // Object object = list.get(0); // log( "(0) = " + object + " type: " + object.getClass() ); int size = results.length; assertTrue("List should contain " + size + " results: " + list, list .size() == size); for (int i = 0; i < size; i++) { assertEquals(list.get(i), results[i]); } } protected void setUp() throws Exception { super.setUp(); document = new SAXReader().read(new File("xml/test/product.xml")); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/test/org/dom4j/xpath/BadPathTest.java0000644000175000017500000000656310242117776021611 0ustar ebourgebourg/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.xpath; import junit.textui.TestRunner; import org.dom4j.AbstractTestCase; import org.dom4j.XPath; /** * Tests bad XPath expressions * * @author James Strachan * @version $Revision: 1.3 $ */ public class BadPathTest extends AbstractTestCase { private String[] paths = {"+", "/foo/bar/"}; public static void main(String[] args) { TestRunner.run(BadPathTest.class); } // Test case(s) // ------------------------------------------------------------------------- public void testBadPaths() throws Exception { for (int i = 0, size = paths.length; i < size; i++) { String path = paths[i]; testBadPath(path); } } protected void testBadPath(String path) throws Exception { try { document.selectObject(path); fail("Should have thrown exception for: " + path); } catch (Exception e) { log("Successfully caught: " + e); } try { XPath xpath = document.createXPath(path); fail("Should have thrown exception for: " + path); } catch (Exception e) { log("Successfully caught: " + e); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */ dom4j-1.6.1/src/docbook/0000755000175000017500000000000012133227266014277 5ustar ebourgebourgdom4j-1.6.1/src/docbook/cookbook.xml0000644000175000017500000020550710242120020016613 0ustar ebourgebourg dom4j cookbook MrTobiasRademacher MrJamesStrachan 0.1.0 02-05-09 tradem Fixed typos Better understable description of some situations Use of programlistingco for rule API 0.0.9 02-05-01 tradem Added rule API description & samples Added JRV API sample to schemata chapter Used width constrains for programlistings Extented XPath samples 0.0.8 01-09-25 tradem Fixed the MSV sample in order make it compilable. Lot's of thanks to Martijn Koster for pointing that out. 0.0.7 01-09-03 tradem Completed the Schema chapter. Fixed the XPath sample. 0.0.6 01-08-03 jstrachan Fixed a few typos and corrected the odd bit of grammar and code. 0.0.5 01-07-09 tradem Fixing xml structure mistake Make Writer samples dom4j 0.6 compliant 0.0.4 01-07-06 tradem Fixing spelling/gramma mistakes Complete vistor listing 0.0.3 01-06-20 tradem Completed doc for alpha release 0.0.2 01-06-06 tradem Added "Secret of DocumentBuilder" and "Serialization" 0.0.1 01-06-02 tradem Created the document September 2001 This document provides a practical introduction to dom4j. It guides you through by using a lot of examples and is based on dom4j v1.0 Foreword Introducing dom4j dom4j is a object model representing an XML Tree in memory. dom4j offers a easy-to-use API that provides a powerful set of features to process, manipulate or navigate XML and work with XPath and XSLT as well as integrate with SAX, JAXP and DOM. dom4j is designed to be interface-based in order to provide highly configurable implementation strategies. You are able to create your own XML tree implementations by simply providing a DocumentFactory implementation. This makes it very simple to reuse much of the dom4j code while extending it to provide whatever implementation features you wish. This document will guide you through dom4j's features in a practical way using a lot of examples with source code. The document is also designed as a reference so that you don't have to read the entire document at once. This guide concentrates on daily work with dom4j and is therefore called cookbook. Creation of an XML Object Model using dom4j Normally all starts with a set of xml-files or a single xml file that you want to process, manipulate or navigate through to extract some values necessary in your application. Most Java Open-Source projects using XML for deployment or as a replacement for property files in order to get easily readable property data.
Reading XML data How does dom4j help you to get at the data stored in XML? dom4j comes with a set of builder classes that parse the xml data and create a tree-like object structure in memory. You can easily manipulate and navigate through that model. The following example shows how you can read your data using dom4j API. import java.io.File; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; public class DeployFileLoaderSample { /** dom4j object model representation of a xml document. Note: We use the interface(!) not its implementation */ private Document doc; /** * Loads a document from a file. * * @throw a org.dom4j.DocumentException occurs whenever the buildprocess fails. */ public void parseWithSAX(File aFile) throws DocumentException { SAXReader xmlReader = new SAXReader(); this.doc = xmlReader.read(aFile); } } The above example code should clarify the use of org.dom4j.io.SAXReader to build a complete dom4j tree from a given file. The org.dom4j.io package contains a set of classes for creation and serialization of XML objects. The read() method is overloaded so that you able to pass different kind of object that represents a source. java.lang.String - a SystemId is a String that contains a URI e.g. a URL to a XML file java.net.URL - represents a Uniform Resource Loader or a Uniform Resource Identifier. Encapsulates a URL. java.io.InputStream - an open input stream that transports xml data java.io.Reader - more compatible. Has abilitiy to specify encoding scheme org.sax.InputSource - a single input source for a XML entity. Lets add more more flexibility to our DeployFileLoaderSample by adding new methods. import java.io.File; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; public class DeployFileLoaderSample { /** dom4j object model representation of a xml document. Note: We use the interface(!) not its implementation */ private Document doc; /** * Loads a document from a file. * * @param aFile the data source * @throw a org.dom4j.DocumentExcepiton occurs on parsing failure. */ public void parseWithSAX(File aFile) throws DocumentException { SAXReader xmlReader = new SAXReader(); this.doc = xmlReader.read(aFile); } /** * Loads a document from a file. * * @param aURL the data source * @throw a org.dom4j.DocumentExcepiton occurs on parsing failure. */ public void parseWithSAX(URL aURL) throws DocumentException { SAXReader xmlReader = new SAXReader(); this.doc = xmlReader.read(aURL); } }
Integrating with other XML APIs dom4j also offers classes for integration with the two original XML processing APIs - SAX and DOM. So far we have been talking about reading a document with SAX. The org.dom4j.SAXContentHandler class implements several SAX interfaces directly (such as ContentHandler) so that you can embed dom4j directly inside any SAX application. You can also use this class to implement your own specific SAX-based Reader class if you need to. The DOMReader class allows you to convert an existing DOM tree into a dom4j tree. This could be useful if you already used DOM and want to replace it step by step with dom4j or if you just needs some of DOM's behavior and want to save memory resources by transforming it in a dom4j Model. You are able to transform a DOM Document, a DOM node branch and a single element. import org.sax.Document; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.DOMReader; public class DOMIntegratorSample { /** converts a W3C DOM document into a dom4j document */ public Document buildDocment(org.w3c.dom.Document domDocument) { DOMReader xmlReader = new DOMReader(); return xmlReader.read(domDocument); } }
The secret of DocumentFactory We have talked a lot of reading existing XML information e.g. from files, URL's or even Streams. Sometimes it's necessary to generate a XML document programmatically. The class org.dom4j.DocumentFactory defines a set of factory methods to create documents, document types, elements, attributes, unparsed character data (CDATA), a namespace, an XPath object, a NodeFilter and some other useful instances. This makes the DocumentFactory a central class whenever you have to create one of these instances by yourself.
import org.dom4j.DocumentFactory; import org.dom4j.Document; import org.dom4j.Element; public class DeployFileCreator { private DocumentFactory factory = DocumentFactory.getInstance(); private Document doc; public void generateDoc(String aRootElement) { doc = DocumentFactory.getInstance().createDocument(); Element root = doc.addElement(aRootElement); } } The listing shows how to generate a new Document from scratch. The method generateDoc(String aRootElement) takes a String parameter. The string value contains the name of the root element of the new document. As you can see org.dom4j.DocumentFactory is a singleton accessible via getInstance(). The DocumentFactory methods follow the createXXX() naming convention. For example, if you want to create a Attribute you would call createAttribute(). If your class often calls DocumentFactory or uses a different DocumentFactory instance you could add it as a member variable and initiate it via getInstance in your constructor. import org.dom4j.DocumentFactory; import org.dom4j.Document; import org.dom4j.Element; public class GranuatedDeployFileCreator { private DocumentFactory factory; private Document doc; public GranuatedDeployFileCreator() { this.factory = DocumentFactory.getInstance(); } public void generateDoc(String aRootElement) { doc = factory.createDocument(); Element root = doc.addElement(aRootElement); } } The Document and Element interfaces have a number of helper methods for creating an XML document programmatically in a simple way. import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; public class Foo { public Document createDocument() { Document document = DocumentHelper.createDocument(); Element root = document.addElement( "root" ); Element author2 = root.addElement( "author" ) .addAttribute( "name", "Toby" ) .addAttribute( "location", "Germany" ) .addText( "Tobias Rademacher" ); Element author1 = root.addElement( "author" ) .addAttribute( "name", "James" ) .addAttribute( "location", "UK" ) .addText( "James Strachan" ); return document; } } As mentioned earlier dom4j is an interface based API. This means that DocumentFactory and the reader classes in the org.dom4j.io package always use the org.dom4j interfaces rather than any concrete implementation classes. The Collection API and W3C's DOM are other examples of APIs that use this design approach. This widespread design is described by BillVenners.
Serialization and Output Once you parsed or created a document you want to serialize it to disk or into a plain (or encrypted) stream. dom4j provides a set of classes to serialize your dom4j tree in four ways: XML HTML DOM SAX Events
Serializing to XML org.dom4j.io.XMLWriter is a easy-to-use and easy-to-understand class used to serialize a dom4j tree to a plain XML. You are able to write the XML tree to either an java.io.OutputStream or a java.io.Writer. This can be configured with the overloaded constructor or via the setOutputStream() or setReader() methods. Let's have a look at a example. import java.io.OutputStream; import org.dom4j.Document; import org.dom4j.io.XMLWriter; import org.dom4j.io.OutputFormat; public class DeployFileCreator { private Document doc; public void serializetoXML(OutputStream out, String aEncodingScheme) throws Exception { OutputFormat outformat = OutputFormat.createPrettyPrint(); outformat.setEncoding(aEncodingScheme); XMLWriter writer = new XMLWriter(out, outformat); writer.write(this.doc); writer.flush(); } } We use the XMLWriter constructor to pass OutputStream along with the required character encoding. It is easier to use a Writer rather than an OutputStream, because the Writer is String based and so has less character encoding issues. The write() methods of Writer are overloaded so that you can write all of the dom4j objects individually if required.
Customizing the output format The default output format is to write the XML document as-is. If you want to change the output format then there is a class org.dom4j.io.OutputFormat which allows you to define pretty-printing options, suppress output of XML declaration, change line ending and so on. There is also a helper method OutputFormat.createPrettyPrint() which creates a default pretty-printing format that you can further customize if you wish. import java.io.OutputStream; import org.dom4j.Document; import org.dom4j.io.XMLWriter; import org.dom4j.io.OutputFormat; public class DeployFileCreator { private Document doc; public void serializetoXML(OutputStream out, String aEncodingScheme) throws Exception { OutputFormat outformat = OutputFormat.createPrettyPrint(); outformat.setEncoding(aEncodingScheme); XMLWriter writer = new XMLWriter(out, outformat); writer.write(this.doc); writer.flush(); } } An interesting feature of OutputFormat is the ability to set character encoding. It is a good idiom to use this mechansim for setting the encoding for XMLWriter to use this encoding to create an OutputStream as well as to output XML declaration. The close() method closes the underlying Writer. import java.io.OutputStream; import org.dom4j.Document; import org.dom4j.io.XMLWriter; import org.dom4j.io.OutputFormat; public class DeployFileCreator { private Document doc; private OutputFormat outFormat; public DeployFileCreator() { this.outFormat = OuputFormat.getPrettyPrinting(); } public DeployFileCreator(OutputFormat outFormat) { this.outFormat = outFormat; } public void writeAsXML(OutputStream out) throws Exception { XMLWriter writer = new XMLWriter(outFormat, this.outFormat); writer.write(this.doc); } public void writeAsXML(OutputStream out, String encoding) throws Exception { this.outFormat.setEncoding(encoding); this.writeAsXML(out); } } The serialization methods in our little example set encoding using OutputFormat. The default encoding if none is specifed is UTF-8. If you need a simple output on screen for debugging or testing you can omit setting of a Writer or an OutputStream completely as XMLWriter will default to System.out.
Printing HTML HTMLWriter takes a dom4j tree and formats it to a stream as HTML. This formatter is similar to XMLWriter but outputs the text of CDATA and Entity sections rather than the serialized format as in XML and also supports many HTML element which have no corresponding close tag such as for <BR> and <P> import java.io.OutputStream; import org.dom4j.Document; import org.dom4j.io.HTMLWriter; import org.dom4j.io.OutputFormat; public class DeployFileCreator { private Document doc; private OutputFormat outFormat; public DeployFileCreator() { this.outFormat = OuputFormat.getPrettyPrinting(); } public DeployFileCreator(OutputFormat outFormat) { this.outFormat = outFormat; } public void writeAsHTML(OutputStream out) throws Exception { HTMLWriter writer = new HTMLWriter(outFormat, this.outFormat); writer.write(this.doc); writer.flush(); } }
Building a DOM tree Sometimes it's necessary to transform your dom4j tree into a DOM tree, because you are currently refactoring your application. dom4j is very convenient for integration with older XML API's like DOM or SAX (see Generating SAX Events). Let's move to an example: import org.w3c.dom.Document; import org.dom4j.Document; import org.dom4j.io.DOMWriter; public class DeployFileLoaderSample { private org.dom4j.Document doc; public org.w3c.dom.Document transformtoDOM() { DOMWriter writer = new DOMWriter(); return writer.write(this.doc); } }
Generating SAX Events If you want to output a document as sax events in order to integrate with some existing SAX code, you can use the org.dom4j.SAXWriter class. import org.xml.ConentHandler; import org.dom4j.Document; import org.dom4j.io.SAXWriter; public class DeployFileLoaderSample { private org.dom4j.Document doc; public void transformtoSAX(ContentHandler ctxHandler) { SAXWriter writer = new SAXWriter(); writer.setContentHandler(ctxHandler); writer.write(doc); } } As you can see using SAXWriter is fairly easy. You can also pass org.dom.Element so you are able to process a single element branch or even a single node with SAX.
Navigation in dom4j dom4j offers several powerful mechanisms for navigating through a document: Using Iterators Fast index based navigation Using a backed List Using XPath In-Build GOF Visitor Pattern
Using Iterator Most Java developers used java.util.Iterator or it's ancestor java.util.Enumeration. Both classes are part of the Collection API and used to visit elements of a collection. Here is an example of using Iterator:
import java.util.Iterator; import org.dom4j.Document; import org.dom4j.Element; public class DeployFileLoaderSample { private org.dom4j.Document doc; private org.dom4j.Element root; public void iterateRootChildren() { root = this.doc.getRootElement(); Iterator elementIterator = root.elementIterator(); while(elementIterator.hasNext()){ Element elmeent = (Element)elementIterator.next(); System.out.println(element.getName()); } } } The above example might be a little bit confusing if you are not familiar with the Collections API. Casting is necessary when you want to access the object. In JDK 1.5 Java Generics solve this problem . import java.util.Iterator; import org.dom4j.Document; import org.dom4j.Element; public class DeployFileLoaderSample { private org.dom4j.Document doc; private org.dom4j.Element root; public void iterateRootChildren(String aFilterElementName) { root = this.doc.getRootElement(); Iterator elementIterator = root.elementIterator(aFilterElementName); while(elementIterator.hasNext()){ Element elmeent = (Element)elementIterator.next(); System.out.println(element.getName()); } } } Now the the method iterates on such Elements that have the same name as the parameterized String only. This can be used as a kind of filter applied on top of Collection API's Iterator.
Fast index based Navigation Sometimes if you need to walk a large tree very quickly, creating an java.io.Iterator instance to loop through each Element's children can be too expensive. To help this situation, dom4j provides a fast index based looping as follows. public void treeWalk(Document document) { treeWalk( document.getRootElement() ); } public void treeWalk(Element element) { for ( int i = 0, size = element.nodeCount(); i < size; i++ ) { Node node = element.node(i); if ( node instanceof Element ) { treeWalk( (Element) node ); } else { // do something.... } } }
Using a backed List You can navigate through an Element's children using a backed List so the modifications to the List are reflected back into the Element. All of the methods on List can be used. import java.util.List; import org.dom4j.Document; import org.dom4j.Element; public class DeployFileLoaderSample { private org.dom4j.Document doc; public void iterateRootChildren() { Element root = doc.getRootElement(); List elements = root.elements; // we have access to the size() and other List methods if ( elements.size() > 4 ) { // now lets remove a range of elements elements.subList( 3, 4 ).clear(); } } }
Using XPath XPath is is one of the most useful features of dom4j. You can use it to retrieve nodes from any location as well as evaluating complex expressions. A good XPath reference can be found in Michael Kay's XSLT book XSLTReference along with the Zvon Zvon tutorial.
import java.util.Iterator; import org.dom4j.Documet; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.XPath; public class DeployFileLoaderSample { private org.dom4j.Document doc; private org.dom4j.Element root; public void browseRootChildren() { /* Let's look how many "James" are in our XML Document an iterate them ( Yes, there are three James in this project ;) ) */ XPath xpathSelector = DocumentHelper.createXPath("/people/person[@name='James']"); List results = xpathSelector.selectNodes(doc); for ( Iterator iter = result.iterator(); iter.hasNext(); ) { Element element = (Element) iter.next(); System.out.println(element.getName(); } // select all children of address element having person element with attribute and value "Toby" as parent String address = doc.valueOf( "//person[@name='Toby']/address" ); // Bob's hobby String hobby = doc.valueOf( "//person[@name='Bob']/hobby/@name" ); // the second person living in UK String name = doc.value( "/people[@country='UK']/person[2]" ); // select people elements which have location attriute with the value "London" Number count = doc.numberValueOf( "//people[@location='London']" ); } } As selectNodes returns a List we can apply Iterator or any other operation avalilable on java.util.List. You can also select a single node via selectSingleNode() as well as to select a String expression via valueOf() or Number value of an XPath expression via numberValueOf().
Using Visitor Pattern The visitor pattern has a recursive behavior and acts like SAX in the way that partial traversal is not possible. This means complete document or complete branch will be visited. You should carefully consider situations when you want to use Visitor pattern, but then it offers a powerful and elegant way of navigation. This document doesn't explain Vistor Pattern in depth, GoF98 covers more information. import java.util.Iterator; import org.dom4j.Visitor; import org.dom4j.VisitorSupport; import org.dom4j.Document; import org.dom4j.Element; public class VisitorSample { public void demo(Document doc) { Visitor visitor = new VisitorSupport() { public void visit(Element element) { System.out.println( "Entity name: " + element.getName() + "text " + element.getText(); ); } }; doc.accept( visitor ); } } As you can see we used anonymous inner class to override the VisitorSupport callback adapter method visit(Element element) and the accept() method starts the visitor mechanism.
Manipulating dom4j Accessing XML content statically alone would not very special. Thus dom4j offers several methods for manipulation a documents content.
What <classname>org.dom4j.Document</classname> provides A org.dom4j.Document allows you to configure and retrieve the root element. You are also able to set the DOCTYPE or a SAX based EntityResolver. An empty Document should be created via org.dom4j.DocumentFactory.
Working with <classname>org.dom4j.Element</classname> org.dom4j.Element is a powerful interface providing many methods for manipulating Element. public void changeElementName(String aName) { this.element.setName(aName); } public void changeElementText(String aText) { this.element.setText(aText); }
Qualified Names An XML Element should have a qualified name. Normally qualified name consists normally of a Namespace and local name. It's recommended to use org.dom4j.DocumentFactory to create Qualified Names that are provided by org.dom4j.QName instances. import org.dom4j.Element; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.QName; public class DeployFileCreator { protected Document deployDoc; protected Element root; public void DeployFileCreator() { QName rootName = DocumentFactory.getInstance().createQName("preferences", "", "http://java.sun.com/dtd/preferences.dtd"); this.root = DocumentFactory.getInstance().createElement(rootName); this.deployDoc = DocumentFactory.getInstance().createDocument(this.root); } }
Inserting elements Sometimes it's necessary to insert an element in a existing XML Tree. This is easy to do using dom4j Collection API. public void insertElementAt(Element newElement, int index) { Element parent = this.element.getParent(); List list = parent.content(); list.add(index, newElement); } public void testInsertElementAt() { //insert an clone of current element after the current element Element newElement = this.element.clone(); this.insertElementAt(newElement, this.root.indexOf(this.element)+1); // insert an clone of current element before the current element this.insertElementAt(newElement, this.root.indexOf(this.element)); }
Cloning - How many sheep do you need? Elements can be cloned. Usually cloning is supported in Java with clone() method that is derived from Object. The cloneable Object has to implement interface Cloneable. By default clone() method performs shallow copying. dom4j implements deep cloning because shallow copies would not make sense in context of an XML object model. This means that cloning can take a while because the complete tree branch or event the document will be cloned. Now have a short look how dom4j cloning mechanism is used. import org.dom4j.Document; import org.dom4j.Element; public class DeployFileCreator { private Element cloneElement(String name) { return this.root.element(name).clone(); } private Element cloneDetachElement(String name) { return this.root.createCopy(name); } public class TestElement extends junit.framework.TestCase { public void testCloning() throws junit.framwork.AssertionFailedException { assert("Test cloning with clone() failed!", this.creator.cloneElement("Key") != null); assert("Test cloning with createCopy() failed!", this.creator.cloneDetachElement() != null); } } } The difference between createCopy(...) and clone() is that first method creates a detached deep copy whereas clone() returns exact copy of the current document or element. Consider use of Cloning Cloning might be useful when you want to build element pool. Memory consumpsion should be carefully considered during design of such pool. Alternatively you can consider to use Reference API Pawlan98 or Dave Millers approach JavaWorldTip76.
Using dom4j with XSLT With eXtensible Stylesheet Language XML got a powerfull method of transformation. XML XSL greately simplified job of developing export filters for different data formats. The transformation is done by XSL Processor. XSL covers following subjects: XSL Style Sheet XSL Processor for XSLT FOP Processor for FOP An XML source Since JaXP 1.1 TraX is the common API for proceeding a XSL Stylesheet inside of Java. You start with a TransformerFactory, specify Result and Source. Source contains source xml file that should be transformed. Result contains result of the transformation. dom4j offers org.dom4j.io.DocumentResult and org.dom4j.io.DocumenSource for TrAX compatibility. Whereas org.dom4j.io.DocumentResult contains a org.dom4j.Document as result tree, DocumentSource takes dom4j Documents and prepares them for transformation. Both classes are build on top of TraX own SAX classes. This approach has much better performance than a DOM adaptation. The following example explains the use of XSLT with TraX and dom4j. import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import org.dom4j.Document; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; public class DocumentStyler { private Transformer transformer; public DocumentStyler(Source aStyleSheet) throws Exception { // create transformer TransformerFactory factory = TransformerFactory.newInstance(); transformer = factory.newTransformer( aStyleSheet ); } public Document transform(Document aDocument, Source aStyleSheet) throws Exception { // perform transformation DocumentSource source = new DocumentSource( aDocument ); DocumentResult result = new DocumentResult(); transformer.transform(source, result); // return resulting document return result.getDocument(); } } One could use XSLT to process a XML Schema and generate an empty template xml file according the schema constraints. The code above shows how easy to do that with dom4j and its TraX support. TemplateGenerator can be shared but for this example I avoided this for simplicity. More information about TraX is provided here. Schemata-Support First way to describe XML document structure is as old as XML itself. Document Type Definitions are used since publishing of the XML specification. Many applications use DTD to describe and validate documents. Unfortunately the DTD Syntax was not that powerful. Written in SGML, DTDs are also not as easy to handle as XML. Since then other, more powerful ways to describe XML format were invented. The W3C published XML Schema Specification which provides significant improvements over DTD. XML Schemas are described using XML. A growing group of people use XML Schema now. But XML Schema isn't perfect. So a few people swear by Relax or Relax NG. The reader of this document is able to choose one of the following technologies: Relax NG (Regular Language description for XML Next Generation)RelaxNG Relax (Regular Language description for XML)Relax TREXTREX XML DTDsDTD XML SchemaXSD
Using XML Schema Data Types in dom4j dom4j currently supports only XML Schema Data Types DataTypes. The dom4j implementation is based on top of MSV. Earlier dom4j releases are built on top of Sun Tranquilo (xsdlib.jar) library but later moved to MSV now, because MSV provides the same Tranquilo plus exciting additional features we will discuss later. import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.XPath; import org.dom4j.io.SAXReader; import org.dom4j.dataType.DataTypeElement; public class SchemaTypeDemo { public static void main(String[] args) { SAXReader reader = new SAXReader(); reader.setDocumentFactory( DatatypeDocumentFactory.getInstance() ); Document schema = return reader.read(xmlFile) XPath xpathSelector = DocumentHelper.createXPath("xsd:schema/xsd:complexType[@name='Address']/xsd:structure/xsd:element[@type]"); List xsdElements = xpathSelector.selectNodes(schema); for (int i=0; i < xsdElements.size(); i++) { DataElement tempXsdElement = (DatatypeElement)xsdElements.get(i); if (tempXsdElement.getData() instanceof Integer) { tempXsdElement.setData(new Integer(23)); } } } Alpha status Note that the Data Type support is still alpha. If you find any bug, please report it to the mailing list. This helps us to make more stable Data Type support.
Validation Currently dom4j does not come with a validation engine. You are forced to use a external validator. In the past we recommended Xerces, but now you are able to use Sun Multi-Schema XML Validator. Xerces is able to validate against DTDs and XML Schema, but not against TREX or Relax. The Suns Multi Schema Validator supports all mentioned kinds of validation. Consider use of Validation Validation consumes valuable resources. Use it wisely.
Using Apaches Xerces 1.4.x and dom4j for validation It is easy to use Xerces 1.4.x for validation. Download Xerces from Apaches XML web sites. Experience shows that the newest version is not always the best. View Xerces mailing lists in order to find out issues with specific versions. Xerces provides Schema support strarting from 1.4.0. Turn on validation mode - which is false for default - using a SAXReader instance Set the following Xerces property http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation using the schema URI. Create a SAX XMLErrorHandler and install it to your SAXReader instance. Parse and validate the Document. Output Validation/Parsing errors. import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.dom4j.util.XMLErrorHandler; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException public class SimpleValidationDemo { public static void main(String[] args) { SAXReader reader = new SAXReader(); reader.setValidation(true); // specify the schema to use reader.setProperty( "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "prices.xsd" ); // add error handler which turns any errors into XML XMLErrorHandler errorHandler = new XMLErrorHandler(); reader.setErrorHandler( errorHandler ); // parse the document Document document = reader.read(args[0]); // output the errors XML XMLWriter writer = new XMLWriter( OutputFormat.createPrettyPrint() ); writer.write( errorHandler.getErrors() ); } Xerces and Crimson Both, Xerecs and Crimson, are JaXPable parsers. Be careful while using Crimson and Xerces in same class path. Xerces will work correctly only when it is specified in class path before Crimson. At this time I recommend that you should either Xereces or Crimson.
A perfect team - Multi Schema Validator<citation>MSV</citation> and dom4j Kohsuke Kawaguchi a developer from Sun created a extremly usefull tool for XML validation. Multi Schema Validator (MSV) supports following specifications: Relax NG Relax TREX XML DTDs XML Schema Currently its not clear whether XML Schema will be the next standard for validation. Relax NG has an ever more growing lobby. If you want to build a open application that is not fixed to a specific XML parser and specific type of XML validation you should use this powerfull tool. As usage of MSV is not trivial the next section shows how to use it in simpler way.
Simplified Multi-Schema Validation by using Java API for RELAX Verifiers (JARV) The Java API for RELAX Verifiers JARV defines a set of Interfaces and provide a schemata and vendor neutral API for validation of XML documents. The above explained MSV offers a Factory that supports JARV. So you can use the JARV API on top of MSV and dom4j to validate a dom4j documents. import org.iso_relax.verifier.Schema; import org.iso_relax.verifier.Verifier; import org.iso_relax.verifier.VerifierFactory; import org.iso_relax.verifier.VerifierHandler; import com.sun.msv.verifier.jarv.TheFactoryImpl; import org.apache.log4j.Category; import org.dom4j.Document; import org.dom4j.io.SAXWriter; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; public class Validator { private final static CATEGORY = Category.getInstance(Validator.class); private String schemaURI; private Document document; public Validator(Document document, String schemaURI) { this.schemaURI = schemaURI; this.document = document; } public boolean validate() throws Exception { // (1) use autodetection of schemas VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl(); Schema schema = factory.compileSchema( schemaURI ); // (2) configure a Vertifier Verifier verifier = schema.newVerifier(); verifier.setErrorHandler( new ErrorHandler() { public void error(SAXParseException saxParseEx) { CATEGORY.error( "Error during validation.", saxParseEx); } public void fatalError(SAXParseException saxParseEx) { CATEGORY.fatal( "Fatal error during validation.", saxParseEx); } public void warning(SAXParseException saxParseEx) { CATEGORY.warn( saxParseEx ); } } ); // (3) starting validation by resolving the dom4j document into sax VerifierHandler handler = verifier.getVerifierHandler(); SAXWriter writer = new SAXWriter( handler ); writer.write( document ); return handler.isValid(); } } } The whole work in the above example is done in validate() method. Foremost the we create a Factory instance and use it to create a JAVR org.iso_relax.verifier.Schema instance. In second step we create and configure a org.iso_relax.verifier.Verifier using a org.sax.ErrorHandler. I use Apaches Log4j API to log possible errors. You can also use System.out.println() or, depending of the applications desired robustness, any other method to provide information about failures. Third and last step resolves the org.dom4j.Document instance using SAX in order to start the validation. Finally we return a boolean value that informs about success of the validation. Using teamwork of dom4j, MSV, JAVR and good old SAX simplifies the usage of multi schemata validation while gaining the power of MSV.
Declarative Rule Processing XSLT defines a declarative rule-based way to transform XML tree into plain text, HTML, FO or any other text-based format. XSLT is very powerful. Ironically it does not need variables to hold data. As Michael Kay XSLTReference says: "This style of coding without assignment statements, is called Functional Programming. The earliest and most famous functional programming language was Lisp ..., while modern examples include ML and Scheme." In XSLT you define a so called template that matches a certain XPath expression. The XSLT Processor traverse the source tree using a recursive tree descent algorithm and performs the commands you defined when a specific tree branch matches the template rule. dom4j offers an API that supports XSLT similar rule based processing. The API can be found in org.dom4j.rule package and this chapter will introduce you to this powerful feature of dom4j.
Introducing dom4j's declarative rule processing This section will demonstrate the usage of dom4j's rule API by example. Consider we have the following XML document, but that we want to transform into another XML document containing less information. Simon Lifehouse No Name Face 2000 Alternative Rock 6 Hands Clean Alanis Morrisette Under Rug Swept 2002 Alternative Rock 3 Alive Payable On Deatch Satellit 2002 Metal Crawling In The Dark Hoobastank Hoobastank (Selftitled) 2002 Alternative Rock ]]> A common method to transform one XML document into another is XSLT. It's quite powerful but it is very different from Java and uses paradigms different from OO. Such style sheet may look like this. ]]> This stylesheet filters all song titles and creates a xml wrapper for it. After applying the stylesheet with XSLT processor you will get the following xml document. Simon Hands Clean Alive Crawling in the Dark ]]> Okay. Now it's time to present a possible solution using dom4j's rule API. As you will see this API is very compact. The Classes you have to write are neither complex nor extremely hard to understand. We want to get the same result as your former stylesheet. import java.io.File; import org.dom4j.DocumentHelper; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.dom4j.io.OutputFormat; import org.dom4j.rule.Action; import org.dom4j.rule.Pattern; import org.dom4j.rule.Stylesheet; import org.dom4j.rule.Rule; public class SongFilter { private Document resultDoc; private Element songElement; private Element currentSongElement; private Stylesheet style; public SongFilter() { this.songElement = DocumentHelper.createElement( "song" ); } public Document filtering(org.dom4j.Document doc) throws Exception { Element resultRoot = DocumentHelper.createElement( "Song-Titles" ); this.resultDoc = DocumentHelper.createDocument( resultRoot ); Rule songElementRule = new Rule(); songElementRule.setPattern( DocumentHelper.createPattern( "/Songs/song/mp3/id3" ) ); songElementRule.setAction( new SongElementBuilder() ); Rule titleTextNodeFilter = new Rule(); titleTextNodeFilter.setPattern( DocumentHelper.createPattern( "/Songs/song/mp3/id3/title" ) ); titleTextNodeFilter.setAction( new NodeTextFilter() ); this.style = new Stylesheet(); this.style.addRule( songElementRule ); this.style.addRule( titleTextNodeFilter ); style.run( doc ); return this.resultDoc; } private class SongElementBuilder implements Action { public void run(Node node) throws Exception { currentSongElement = songElement.createCopy(); resultDoc.getRootElement().add ( currentSongElement ); style.applyTemplates(node); } } private class NodeTextFilter implements Action { public void run(Node node) throws Exception { if ( currentSongElement != null ) { currentSongElement.setText( node.getText() ); } } } } Define the root element or another container element for the filtered out information. Create as many instances of org.dom4j.rule.Rule as needed. Install for each rule a instance of org.dom4j.rule.Pattern and org.dom4j.rule.Action. A org.dom4j.rule.Pattern consists of a XPath Expression, which is used for Node matching. A org.dom4j.rule.Action defines the process if a matching occured. Create a instance of org.dom4j.rule.Stylesheet Start the processing If you are familiar with Java Threads you may encounter usage similarities between java.lang.Runnable and org.dom4j.rule.Action. Both act as a plugin or listener. And this Observer Pattern has a wide usage in OO and especially in Java. We implemented observers here as private inner classes. You may decide to declare them as outer classes as well. However if you do that, the design becomes more complex because you need to share instance of org.dom4j.rule.StyleSheet. Anonymous adapters Moreover it's possible to create an anonymous inner class for org.dom4j.rule.Action interface.
Understanding dom4j's rule API Comparing Visitor with Rule API Visitor Declartive Rule Processing Use of Interfaces in design Use of Interfaces in design Uncontrolled automatic recursive descent traversal Rule controlled automatic recursive descent traversal Needs knowledge of Visitor pattern to understand Knowledge of Observer/Publish-Subscriber pattern (ligua franca pattern besides Singleton) useful Provides adapater class to simplify usage of interface Adapter not necessary due to interface using single method Basic knowledge of dom4j's tree object model necessary Additional XPath knowlege for pattern specification necessary Implementation is more compact More code necessary to define the rules and action High and easy modularity High modularity for controlled recursive processing, but more complex handling if you abandon inner or anonymous inner classes.
As shown above, dom4j's uses a very flexible OO-Representation of a XSLT Stylesheet. The smart handling of actions produces compact code. The rule API is a OO representation of W3C XSLT. The API defines another way of traversing the in-memory dom4j tree. The traversal algorithm is called recursive descent and is the same as XSLT defines. Such algorithms are also used in compiler construction and described in literature. XSLT defines a way of tree merging or filtering. If you output an eXtensible stylesheet result to another xml you merge an existing tree to another one using the instruction of the Stylesheet and if output to plain text a styling is used for filtering. First usage is addressed by this API. The second is also possible but not so easy to implement as in XSLT. How does the rule API work? Each Stylesheet has a rule. A rule consists of an action and a pattern. Patterns are described with XPath. You start the processing of a Stylesheet on a specific source with must be a dom4j Node. Calling method style.applyTemplates(node); traverses the Node using a recursive descent algorithm - branch after branch. If a pattern matches the assigned action is activated. If you are interested more in the way a xml document is traversed by XSLT processors I recommend Michael Kay's book XSLTReference.
Further Reading Books XSLTReference MichaelKay 2001 Worx Press, Inc. 1-861-005067 Worx Press XSLT Programmer's Reference 2'nd Edition Programmer To Programmer Worx Press GoF95 ErichGamma RichardHelm RalphJohnson JohnVlissides 1995 Addison Wesley Pub, Co. 0-201-633-612 Addison-Wesley Design Patterns: Elements of Reusable Object-Orientated Software Articles Pawlan98 MonicaPawlan 1998 http://developer.java.sun.com/javatips/jw-tips76.html Reference Objects and Garbage Collection JavaTip76 DaveMiller http://www.javaworld.com/javaworld/javatips/jw-javatip76.html An alternative to the deep copying technique BillVenners BillVenners http://www.artima.com/designtechniques/interfaces.html Designing with Interfaces - One Programmer's Struggle to Understand the Interface Zvon http://www.zvon.org/xxl/XPathTutorial/General/examples.html Zvon XPath tutorial RelaxNG http://www.oasis-open.org/committees/relax-ng/ Developing RELAX NG, the next generation schema language for XML: clean, simple and powerful Relax http://www.xml.gr.jp/relax/ The offical site of Relax TREX http://www.thaiopensource.com/trex/ TREX - Tree Regular Expressions for XML DTD http://www.w3schools.com/dtd/default.asp Document Type Definitions Tutorial XSD http://www.w3.org/XML/Schema http://www.w3.org/XML/1998/06/xmlspec-report XML Schema JARV http://iso-relax.sourceforge.net/JARV/ Java API for RELAX Verifiers
dom4j-1.6.1/LICENSE.txt0000644000175000017500000000357610242117541013717 0ustar ebourgebourgCopyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. Redistribution and use of this software and associated documentation ("Software"), with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain copyright statements and notices. Redistributions must also contain a copy of this document. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name "DOM4J" must not be used to endorse or promote products derived from this Software without prior written permission of MetaStuff, Ltd. For written permission, please contact dom4j-info@metastuff.com. 4. Products derived from this Software may not be called "DOM4J" nor may "DOM4J" appear in their names without prior written permission of MetaStuff, Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. dom4j-1.6.1/lib/0000755000175000017500000000000012133227266012636 5ustar ebourgebourgdom4j-1.6.1/lib/endorsed/0000755000175000017500000000000012133227266014441 5ustar ebourgebourgdom4j-1.6.1/lib/test/0000755000175000017500000000000012133227266013615 5ustar ebourgebourgdom4j-1.6.1/lib/tools/0000755000175000017500000000000012133227266013776 5ustar ebourgebourgdom4j-1.6.1/docs/0000755000175000017500000000000012133227266013020 5ustar ebourgebourgdom4j-1.6.1/docs/changes.rss0000644000175000017500000000305610242117733015161 0ustar ebourgebourg Changes report http://dom4j.org Changes report en-us Copyright 2004 The Apache Software Foundation 3 change(s) for version 1.6.1 http://dom4j.org/changes-report.html
Type Changes By
update Updated the XPP2 implementation to version 2.1.10. Thanks to Wolfgang Baer . maartenc
fix Fixed a problem with XMLWriter that was causing too many new lines to be written to the resulting XML. Thanks to Thomas Fromm . maartenc
update Include more information about the cause if an XPathException or InvalidXPathException is thrown. Thanks to Gili Tzabari . maartenc
dom4j-1.6.1/docs/cookbook.html0000644000175000017500000016316410242117726015525 0ustar ebourgebourg pub. September 2001 Mr. Tobias Rademacher Mr. James Strachan

Revision History

Revision 0.1.0 (02-05-09)

  • changed (tradem)

Revision 0.0.9 (02-05-01)

  • changed (tradem)

Revision 0.0.8 (01-09-25)

  • changed (tradem)

Revision 0.0.7 (01-09-03)

  • changed (tradem)

Revision 0.0.6 (01-08-03)

  • changed (jstrachan)

Revision 0.0.5 (01-07-09)

  • changed (tradem)

Revision 0.0.4 (01-07-06)

  • changed (tradem)

Revision 0.0.3 (01-06-20)

  • changed (tradem)

Revision 0.0.2 (01-06-06)

  • changed (tradem)

Revision 0.0.1 (01-06-02)

  • changed (tradem)

This document provides a practical introduction to dom4j. It guides you through by using a lot of examples and is based on dom4j v1.0

dom4j is a object model representing an XML Tree in memory. dom4j offers a easy-to-use API that provides a powerful set of features to process, manipulate or navigate XML and work with XPath and XSLT as well as integrate with SAX, JAXP and DOM.

dom4j is designed to be interface-based in order to provide highly configurable implementation strategies. You are able to create your own XML tree implementations by simply providing a DocumentFactory implementation. This makes it very simple to reuse much of the dom4j code while extending it to provide whatever implementation features you wish.

This document will guide you through dom4j's features in a practical way using a lot of examples with source code. The document is also designed as a reference so that you don't have to read the entire document at once. This guide concentrates on daily work with dom4j and is therefore called cookbook.

Normally all starts with a set of xml-files or a single xml file that you want to process, manipulate or navigate through to extract some values necessary in your application. Most Java Open-Source projects using XML for deployment or as a replacement for property files in order to get easily readable property data.

Reading XML data

How does dom4j help you to get at the data stored in XML? dom4j comes with a set of builder classes that parse the xml data and create a tree-like object structure in memory. You can easily manipulate and navigate through that model. The following example shows how you can read your data using dom4j API.

import java.io.File;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class DeployFileLoaderSample {

  /** dom4j object model representation of a xml document. Note: We use the interface(!) not its implementation */
  private Document doc;

  /**
   * Loads a document from a file.
   *
   * @throw a org.dom4j.DocumentException occurs whenever the buildprocess fails.
   */
  public void parseWithSAX(File aFile) throws DocumentException {
    SAXReader xmlReader = new SAXReader();
    this.doc = xmlReader.read(aFile);
  }
}

The above example code should clarify the use of org.dom4j.io.SAXReader to build a complete dom4j tree from a given file. The org.dom4j.io package contains a set of classes for creation and serialization of XML objects. The read() method is overloaded so that you able to pass different kind of object that represents a source.

  • java.lang.String - a SystemId is a String that contains a URI e.g. a URL to a XML file

  • java.net.URL - represents a Uniform Resource Loader or a Uniform Resource Identifier. Encapsulates a URL.

  • java.io.InputStream - an open input stream that transports xml data

  • java.io.Reader - more compatible. Has abilitiy to specify encoding scheme

  • org.sax.InputSource - a single input source for a XML entity.

Lets add more more flexibility to our DeployFileLoaderSample by adding new methods.

import java.io.File;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class DeployFileLoaderSample {

  /** dom4j object model representation of a xml document. Note: We use the interface(!) not its implementation */
  private Document doc;

  /**
   * Loads a document from a file.
   *
   * @param aFile the data source
   * @throw a org.dom4j.DocumentExcepiton occurs on parsing failure.
   */
  public void parseWithSAX(File aFile) throws DocumentException {
    SAXReader xmlReader = new SAXReader();
    this.doc = xmlReader.read(aFile);
  }

  /**
   * Loads a document from a file.
   *
   * @param aURL the data source
   * @throw a org.dom4j.DocumentExcepiton occurs on parsing failure.
   */
  public void parseWithSAX(URL aURL) throws DocumentException {
    SAXReader xmlReader = new SAXReader();
    this.doc = xmlReader.read(aURL);
  }


}

Integrating with other XML APIs

dom4j also offers classes for integration with the two original XML processing APIs - SAX and DOM. So far we have been talking about reading a document with SAX. The org.dom4j.SAXContentHandler class implements several SAX interfaces directly (such as ContentHandler) so that you can embed dom4j directly inside any SAX application. You can also use this class to implement your own specific SAX-based Reader class if you need to.

The DOMReader class allows you to convert an existing DOM tree into a dom4j tree. This could be useful if you already used DOM and want to replace it step by step with dom4j or if you just needs some of DOM's behavior and want to save memory resources by transforming it in a dom4j Model. You are able to transform a DOM Document, a DOM node branch and a single element.

import org.sax.Document;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.DOMReader;

public class DOMIntegratorSample {

  /** converts a W3C DOM document into a dom4j document */
  public Document buildDocment(org.w3c.dom.Document domDocument) {
    DOMReader xmlReader = new DOMReader();
    return xmlReader.read(domDocument);
  }
}

The secret of DocumentFactory

org.dom4j.DocumentFactoryXPathDocumentFactory

import org.dom4j.DocumentFactory;
import org.dom4j.Document;
import org.dom4j.Element;

public class DeployFileCreator {

  private DocumentFactory factory = DocumentFactory.getInstance();
  private Document doc;

  public void generateDoc(String aRootElement) {
    doc = DocumentFactory.getInstance().createDocument();
    Element root = doc.addElement(aRootElement);
  }

}

The listing shows how to generate a new Document from scratch. The method generateDoc(String aRootElement) takes a String parameter. The string value contains the name of the root element of the new document. As you can see org.dom4j.DocumentFactory is a singleton accessible via getInstance(). The DocumentFactory methods follow the createXXX() naming convention. For example, if you want to create a Attribute you would call createAttribute(). If your class often calls DocumentFactory or uses a different DocumentFactory instance you could add it as a member variable and initiate it via getInstance in your constructor.


import org.dom4j.DocumentFactory;
import org.dom4j.Document;
import org.dom4j.Element;

public class GranuatedDeployFileCreator {

 private DocumentFactory factory;
 private Document doc;

 public GranuatedDeployFileCreator() {
   this.factory = DocumentFactory.getInstance();
 }

 public void generateDoc(String aRootElement) {
    doc = factory.createDocument();
    Element root = doc.addElement(aRootElement);
 }

}

The Document and Element interfaces have a number of helper methods for creating an XML document programmatically in a simple way.


import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Foo {

  public Document createDocument() {
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement( "root" );

    Element author2 = root.addElement( "author" )
      .addAttribute( "name", "Toby" )
      .addAttribute( "location", "Germany" )
      .addText( "Tobias Rademacher" );

    Element author1 = root.addElement( "author" )
      .addAttribute( "name", "James" )
      .addAttribute( "location", "UK" )
      .addText( "James Strachan" );

    return document;
  }
}

As mentioned earlier dom4j is an interface based API. This means that DocumentFactory and the reader classes in the org.dom4j.io package always use the org.dom4j interfaces rather than any concrete implementation classes. The Collection API and W3C's DOM are other examples of APIs that use this design approach. This widespread design is described by BillVenners.

Once you parsed or created a document you want to serialize it to disk or into a plain (or encrypted) stream. dom4j provides a set of classes to serialize your dom4j tree in four ways:

  • XML

  • HTML

  • DOM

  • SAX Events

Serializing to XML

org.dom4j.io.XMLWriterdom4jXMLXMLjava.io.OutputStreamjava.io.WritersetOutputStream()setReader()

import java.io.OutputStream;

import org.dom4j.Document;
import org.dom4j.io.XMLWriter;
import org.dom4j.io.OutputFormat;

public class DeployFileCreator {

 private Document doc;

 public void serializetoXML(OutputStream out, String aEncodingScheme) throws Exception {
   OutputFormat outformat = OutputFormat.createPrettyPrint();
   outformat.setEncoding(aEncodingScheme);
   XMLWriter writer = new XMLWriter(out, outformat);
   writer.write(this.doc);
   writer.flush();
 }

}

We use the XMLWriter constructor to pass OutputStream along with the required character encoding. It is easier to use a Writer rather than an OutputStream, because the Writer is String based and so has less character encoding issues. The write() methods of Writer are overloaded so that you can write all of the dom4j objects individually if required.

Customizing the output format

The default output format is to write the XML document as-is. If you want to change the output format then there is a class org.dom4j.io.OutputFormat which allows you to define pretty-printing options, suppress output of XML declaration, change line ending and so on. There is also a helper method OutputFormat.createPrettyPrint() which creates a default pretty-printing format that you can further customize if you wish.


import java.io.OutputStream;

import org.dom4j.Document;
import org.dom4j.io.XMLWriter;
import org.dom4j.io.OutputFormat;

public class DeployFileCreator {

 private Document doc;

  public void serializetoXML(OutputStream out, String aEncodingScheme) throws Exception {
   OutputFormat outformat = OutputFormat.createPrettyPrint();
   outformat.setEncoding(aEncodingScheme);
   XMLWriter writer = new XMLWriter(out, outformat);
   writer.write(this.doc);
   writer.flush();
 }


}

An interesting feature of OutputFormat is the ability to set character encoding. It is a good idiom to use this mechansim for setting the encoding for XMLWriter to use this encoding to create an OutputStream as well as to output XML declaration.

The close() method closes the underlying Writer.


import java.io.OutputStream;

import org.dom4j.Document;
import org.dom4j.io.XMLWriter;
import org.dom4j.io.OutputFormat;

public class DeployFileCreator {

 private Document doc;
 private OutputFormat outFormat;

 public DeployFileCreator() {
   this.outFormat = OuputFormat.getPrettyPrinting();
 }

 public DeployFileCreator(OutputFormat outFormat) {
   this.outFormat = outFormat;
 }

 public void writeAsXML(OutputStream out) throws Exception {
   XMLWriter writer = new XMLWriter(outFormat, this.outFormat);
   writer.write(this.doc);
 }

 public void writeAsXML(OutputStream out, String encoding) throws Exception {
   this.outFormat.setEncoding(encoding);
   this.writeAsXML(out);
 }

}

The serialization methods in our little example set encoding using OutputFormat. The default encoding if none is specifed is UTF-8. If you need a simple output on screen for debugging or testing you can omit setting of a Writer or an OutputStream completely as XMLWriter will default to System.out.

Printing HTML

HTMLWriter takes a dom4j tree and formats it to a stream as HTML. This formatter is similar to XMLWriter but outputs the text of CDATA and Entity sections rather than the serialized format as in XML and also supports many HTML element which have no corresponding close tag such as for <BR> and <P>


import java.io.OutputStream;

import org.dom4j.Document;
import org.dom4j.io.HTMLWriter;
import org.dom4j.io.OutputFormat;

public class DeployFileCreator {

 private Document doc;
 private OutputFormat outFormat;

 public DeployFileCreator() {
   this.outFormat = OuputFormat.getPrettyPrinting();
 }

 public DeployFileCreator(OutputFormat outFormat) {
   this.outFormat = outFormat;
 }

 public void writeAsHTML(OutputStream out) throws Exception {
   HTMLWriter writer = new HTMLWriter(outFormat, this.outFormat);
   writer.write(this.doc);
   writer.flush();
 }

}

Building a DOM tree

Sometimes it's necessary to transform your dom4j tree into a DOM tree, because you are currently refactoring your application. dom4j is very convenient for integration with older XML API's like DOM or SAX (see Generating SAX Events). Let's move to an example:

import org.w3c.dom.Document;

import org.dom4j.Document;
import org.dom4j.io.DOMWriter;

public class DeployFileLoaderSample {

  private org.dom4j.Document doc;

  public org.w3c.dom.Document transformtoDOM() {
    DOMWriter writer = new DOMWriter();
    return writer.write(this.doc);
  }
}

Generating SAX Events

If you want to output a document as sax events in order to integrate with some existing SAX code, you can use the org.dom4j.SAXWriter class.

import org.xml.ConentHandler;

import org.dom4j.Document;
import org.dom4j.io.SAXWriter;

public class DeployFileLoaderSample {

  private org.dom4j.Document doc;

  public void transformtoSAX(ContentHandler ctxHandler) {
     SAXWriter writer = new SAXWriter();
     writer.setContentHandler(ctxHandler);
     writer.write(doc);
  }
}

As you can see using SAXWriter is fairly easy. You can also pass org.dom.Element so you are able to process a single element branch or even a single node with SAX.

dom4j offers several powerful mechanisms for navigating through a document:

  • Using Iterators

  • Fast index based navigation

  • Using a backed List

  • Using XPath

  • In-Build GOF Visitor Pattern

Using Iterator

Most Java developers used java.util.Iterator or it's ancestor java.util.Enumeration. Both classes are part of the Collection API and used to visit elements of a collection. Here is an example of using Iterator:


import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.Element;

public class DeployFileLoaderSample {

  private org.dom4j.Document doc;
  private org.dom4j.Element root;

  public void iterateRootChildren() {
    root = this.doc.getRootElement();
    Iterator elementIterator = root.elementIterator();
    while(elementIterator.hasNext()){
      Element elmeent = (Element)elementIterator.next();
      System.out.println(element.getName());
    }
  }
}

The above example might be a little bit confusing if you are not familiar with the Collections API. Casting is necessary when you want to access the object. In JDK 1.5 Java Generics solve this problem .

import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.Element;

public class DeployFileLoaderSample {

  private org.dom4j.Document doc;
  private org.dom4j.Element root;

  public void iterateRootChildren(String aFilterElementName) {
    root = this.doc.getRootElement();
    Iterator elementIterator = root.elementIterator(aFilterElementName);
    while(elementIterator.hasNext()){
      Element elmeent = (Element)elementIterator.next();
      System.out.println(element.getName());
    }
  }
}

Now the the method iterates on such Elements that have the same name as the parameterized String only. This can be used as a kind of filter applied on top of Collection API's Iterator.

Fast index based Navigation

Sometimes if you need to walk a large tree very quickly, creating an java.io.Iterator instance to loop through each Element's children can be too expensive. To help this situation, dom4j provides a fast index based looping as follows.

  public void treeWalk(Document document) {
    treeWalk( document.getRootElement() );
  }

  public void treeWalk(Element element) {
    for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
      Node node = element.node(i);
      if ( node instanceof Element ) {
        treeWalk( (Element) node );
      }
      else {
        // do something....
      }
    }
  }

Using a backed List

You can navigate through an Element's children using a backed List so the modifications to the List are reflected back into the Element. All of the methods on List can be used.

import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;

public class DeployFileLoaderSample {

  private org.dom4j.Document doc;

  public void iterateRootChildren() {
    Element root = doc.getRootElement();

    List elements = root.elements;

    // we have access to the size() and other List methods
    if ( elements.size() > 4 ) {
      // now lets remove a range of elements
      elements.subList( 3, 4 ).clear();
    }
  }
}

Using XPath

XPath is is one of the most useful features of dom4j. You can use it to retrieve nodes from any location as well as evaluating complex expressions. A good XPath reference can be found in Michael Kay's XSLT book XSLTReference along with the Zvon Zvon tutorial.

import java.util.Iterator;

import org.dom4j.Documet;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.XPath;

public class DeployFileLoaderSample {

  private org.dom4j.Document doc;
  private org.dom4j.Element root;

  public void browseRootChildren() {

    /* 
      Let's look how many "James" are in our XML Document an iterate them  
      ( Yes, there are three James in this project ;) )
    */
      
    XPath xpathSelector = DocumentHelper.createXPath("/people/person[@name='James']");
    List results = xpathSelector.selectNodes(doc);
    for ( Iterator iter = result.iterator(); iter.hasNext(); ) {
      Element element = (Element) iter.next();
      System.out.println(element.getName();
    }

    // select all children of address element having person element with attribute and value "Toby" as parent
    String address = doc.valueOf( "//person[@name='Toby']/address" );

    // Bob's hobby
    String hobby = doc.valueOf( "//person[@name='Bob']/hobby/@name" );

    // the second person living in UK
    String name = doc.value( "/people[@country='UK']/person[2]" );
    
    // select people elements which have location attriute with the value "London"
    Number count = doc.numberValueOf( "//people[@location='London']" );
   
  }

}

As selectNodes returns a List we can apply Iterator or any other operation avalilable on java.util.List. You can also select a single node via selectSingleNode() as well as to select a String expression via valueOf() or Number value of an XPath expression via numberValueOf().

Using Visitor Pattern

The visitor pattern has a recursive behavior and acts like SAX in the way that partial traversal is not possible. This means complete document or complete branch will be visited. You should carefully consider situations when you want to use Visitor pattern, but then it offers a powerful and elegant way of navigation. This document doesn't explain Vistor Pattern in depth, GoF98 covers more information.

import java.util.Iterator;

import org.dom4j.Visitor;
import org.dom4j.VisitorSupport;
import org.dom4j.Document;
import org.dom4j.Element;

public class VisitorSample {

  public void demo(Document doc) {

    Visitor visitor = new VisitorSupport() {
      public void visit(Element element) {
        System.out.println(
          "Entity name: " + element.getName()  + "text " + element.getText();
        );
      }
    };

    doc.accept( visitor );
  }
}

As you can see we used anonymous inner class to override the VisitorSupport callback adapter method visit(Element element) and the accept() method starts the visitor mechanism.

Accessing XML content statically alone would not very special. Thus dom4j offers several methods for manipulation a documents content.

What org.dom4j.Document provides

A org.dom4j.Document allows you to configure and retrieve the root element. You are also able to set the DOCTYPE or a SAX based EntityResolver. An empty Document should be created via org.dom4j.DocumentFactory.

Working with org.dom4j.Element

org.dom4j.Element is a powerful interface providing many methods for manipulating Element.


  public void changeElementName(String aName) {
    this.element.setName(aName);
  }

  public void changeElementText(String aText) {
    this.element.setText(aText);
  }

Qualified Names

An XML Element should have a qualified name. Normally qualified name consists normally of a Namespace and local name. It's recommended to use org.dom4j.DocumentFactory to create Qualified Names that are provided by org.dom4j.QName instances.


  import org.dom4j.Element;
  import org.dom4j.Document;
  import org.dom4j.DocumentFactory;
  import org.dom4j.QName;

  public class DeployFileCreator {

   protected Document deployDoc;
   protected Element root;

   public void DeployFileCreator()
   {
     QName rootName = DocumentFactory.getInstance().createQName("preferences", "", "http://java.sun.com/dtd/preferences.dtd");
     this.root = DocumentFactory.getInstance().createElement(rootName);
     this.deployDoc = DocumentFactory.getInstance().createDocument(this.root);
   }
  }

  

Inserting elements

Sometimes it's necessary to insert an element in a existing XML Tree. This is easy to do using dom4j Collection API.


    public void insertElementAt(Element newElement, int index) {
      Element parent = this.element.getParent();
      List list = parent.content();
      list.add(index, newElement);
    }

    public void testInsertElementAt() {

    //insert an clone of current element after the current element
      Element newElement = this.element.clone();
      this.insertElementAt(newElement, this.root.indexOf(this.element)+1);

    // insert an clone of current element before the current element
      this.insertElementAt(newElement, this.root.indexOf(this.element));
    }
  

Cloning - How many sheep do you need?

Elements can be cloned. Usually cloning is supported in Java with clone() method that is derived from Object. The cloneable Object has to implement interface Cloneable. By default clone() method performs shallow copying. dom4j implements deep cloning because shallow copies would not make sense in context of an XML object model. This means that cloning can take a while because the complete tree branch or event the document will be cloned. Now have a short look how dom4j cloning mechanism is used.


  import org.dom4j.Document;
  import org.dom4j.Element;

  public class DeployFileCreator {


   private Element cloneElement(String name) {
    return this.root.element(name).clone();
   }

   private Element cloneDetachElement(String name) {
     return this.root.createCopy(name);
   }

   public class TestElement extends junit.framework.TestCase {

     public void testCloning() throws junit.framwork.AssertionFailedException {
       assert("Test cloning with clone() failed!", this.creator.cloneElement("Key") != null);
       assert("Test cloning with createCopy() failed!", this.creator.cloneDetachElement() != null);
     }
   }
  }
  

The difference between createCopy(...) and clone() is that first method creates a detached deep copy whereas clone() returns exact copy of the current document or element.

Cloning might be useful when you want to build element pool. Memory consumpsion should be carefully considered during design of such pool. Alternatively you can consider to use Reference API Pawlan98 or Dave Millers approach JavaWorldTip76.

With eXtensible Stylesheet Language XML got a powerfull method of transformation. XML XSL greately simplified job of developing export filters for different data formats. The transformation is done by XSL Processor. XSL covers following subjects:

  • XSL Style Sheet

  • XSL Processor for XSLT

  • FOP Processor for FOP

  • An XML source

Since JaXP 1.1 TraX is the common API for proceeding a XSL Stylesheet inside of Java. You start with a TransformerFactory, specify Result and Source. Source contains source xml file that should be transformed. Result contains result of the transformation. dom4j offers org.dom4j.io.DocumentResult and org.dom4j.io.DocumenSource for TrAX compatibility. Whereas org.dom4j.io.DocumentResult contains a org.dom4j.Document as result tree, DocumentSource takes dom4j Documents and prepares them for transformation. Both classes are build on top of TraX own SAX classes. This approach has much better performance than a DOM adaptation. The following example explains the use of XSLT with TraX and dom4j.

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;

import org.dom4j.Document;
import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;

public class DocumentStyler
{
    private Transformer transformer;

    public DocumentStyler(Source aStyleSheet) throws Exception {
        // create transformer
        TransformerFactory factory = TransformerFactory.newInstance();
        transformer = factory.newTransformer( aStyleSheet );
    }

    public Document transform(Document aDocument, Source aStyleSheet) throws Exception {

        // perform transformation
        DocumentSource source = new DocumentSource( aDocument );
        DocumentResult result = new DocumentResult();
        transformer.transform(source, result);

        // return resulting document
        return result.getDocument();
    }
}

One could use XSLT to process a XML Schema and generate an empty template xml file according the schema constraints. The code above shows how easy to do that with dom4j and its TraX support. TemplateGenerator can be shared but for this example I avoided this for simplicity. More information about TraX is provided here.

First way to describe XML document structure is as old as XML itself. Document Type Definitions are used since publishing of the XML specification. Many applications use DTD to describe and validate documents. Unfortunately the DTD Syntax was not that powerful. Written in SGML, DTDs are also not as easy to handle as XML.

Since then other, more powerful ways to describe XML format were invented. The W3C published XML Schema Specification which provides significant improvements over DTD. XML Schemas are described using XML. A growing group of people use XML Schema now. But XML Schema isn't perfect. So a few people swear by Relax or Relax NG. The reader of this document is able to choose one of the following technologies:

  • Relax NG (Regular Language description for XML Next Generation)RelaxNG

  • Relax (Regular Language description for XML)Relax

  • TREXTREX

  • XML DTDsDTD

  • XML SchemaXSD

Using XML Schema Data Types in dom4j

dom4j currently supports only XML Schema Data Types DataTypes. The dom4j implementation is based on top of MSV. Earlier dom4j releases are built on top of Sun Tranquilo (xsdlib.jar) library but later moved to MSV now, because MSV provides the same Tranquilo plus exciting additional features we will discuss later.

import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.dom4j.dataType.DataTypeElement;

public class SchemaTypeDemo {

public static void main(String[] args) {

  SAXReader reader = new SAXReader();
  reader.setDocumentFactory( DatatypeDocumentFactory.getInstance() );
  Document schema =  return reader.read(xmlFile)
  XPath xpathSelector = DocumentHelper.createXPath("xsd:schema/xsd:complexType[@name='Address']/xsd:structure/xsd:element[@type]");
  List xsdElements = xpathSelector.selectNodes(schema);

  for (int i=0; i < xsdElements.size(); i++) {
    DataElement tempXsdElement = (DatatypeElement)xsdElements.get(i);

    if (tempXsdElement.getData() instanceof Integer) {
       tempXsdElement.setData(new Integer(23));
     }
  }
}

Note that the Data Type support is still alpha. If you find any bug, please report it to the mailing list. This helps us to make more stable Data Type support.

Validation

Currently dom4j does not come with a validation engine. You are forced to use a external validator. In the past we recommended Xerces, but now you are able to use Sun Multi-Schema XML Validator. Xerces is able to validate against DTDs and XML Schema, but not against TREX or Relax. The Suns Multi Schema Validator supports all mentioned kinds of validation.

Validation consumes valuable resources. Use it wisely.

Using Apaches Xerces 1.4.x and dom4j for validation

It is easy to use Xerces 1.4.x for validation. Download Xerces from Apaches XML web sites. Experience shows that the newest version is not always the best. View Xerces mailing lists in order to find out issues with specific versions. Xerces provides Schema support strarting from 1.4.0.

  • Turn on validation mode - which is false for default - using a SAXReader instance

  • Set the following Xerces property http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation using the schema URI.

  • Create a SAX XMLErrorHandler and install it to your SAXReader instance.

  • Parse and validate the Document.

  • Output Validation/Parsing errors.

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dom4j.util.XMLErrorHandler;


import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException

public class SimpleValidationDemo {

public static void main(String[] args) {
  SAXReader reader = new SAXReader();

  reader.setValidation(true);

  // specify the schema to use
  reader.setProperty(
   "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
   "prices.xsd"
  );

  // add error handler which turns any errors into XML
   XMLErrorHandler errorHandler = new XMLErrorHandler();
   reader.setErrorHandler( errorHandler );

  // parse the document
  Document document = reader.read(args[0]);

 // output the errors XML
  XMLWriter writer = new XMLWriter( OutputFormat.createPrettyPrint() );
  writer.write( errorHandler.getErrors() );
}

Both, Xerecs and Crimson, are JaXPable parsers. Be careful while using Crimson and Xerces in same class path. Xerces will work correctly only when it is specified in class path before Crimson. At this time I recommend that you should either Xereces or Crimson.

A perfect team - Multi Schema ValidatorMSV and dom4j

Kohsuke Kawaguchi a developer from Sun created a extremly usefull tool for XML validation. Multi Schema Validator (MSV) supports following specifications:

  • Relax NG

  • Relax

  • TREX

  • XML DTDs

  • XML Schema

Currently its not clear whether XML Schema will be the next standard for validation. Relax NG has an ever more growing lobby. If you want to build a open application that is not fixed to a specific XML parser and specific type of XML validation you should use this powerfull tool. As usage of MSV is not trivial the next section shows how to use it in simpler way.

Simplified Multi-Schema Validation by using Java API for RELAX Verifiers (JARV)

The Java API for RELAX Verifiers JARV defines a set of Interfaces and provide a schemata and vendor neutral API for validation of XML documents. The above explained MSV offers a Factory that supports JARV. So you can use the JARV API on top of MSV and dom4j to validate a dom4j documents.

import org.iso_relax.verifier.Schema;
import org.iso_relax.verifier.Verifier;
import org.iso_relax.verifier.VerifierFactory;
import org.iso_relax.verifier.VerifierHandler;

import com.sun.msv.verifier.jarv.TheFactoryImpl;

import org.apache.log4j.Category;

import org.dom4j.Document;
import org.dom4j.io.SAXWriter;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;

public class Validator {

  private final static CATEGORY = Category.getInstance(Validator.class);
  private String schemaURI;
  private Document document;

  public Validator(Document document, String schemaURI) {
    this.schemaURI = schemaURI;
    this.document = document;
  }
  
  public boolean validate() throws Exception {
  
    // (1) use autodetection of schemas
    VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl();
    Schema schema = factory.compileSchema( schemaURI );
    
    // (2) configure a Vertifier
    Verifier verifier = schema.newVerifier();
        verifier.setErrorHandler(
            new ErrorHandler() {
                public void error(SAXParseException saxParseEx) {
                   CATEGORY.error( "Error during validation.", saxParseEx);
                }
                
                public void fatalError(SAXParseException saxParseEx) {
                   CATEGORY.fatal( "Fatal error during validation.", saxParseEx);
                }
                
                public void warning(SAXParseException saxParseEx) {
                   CATEGORY.warn( saxParseEx );
                }
            }
        );    
        
    // (3) starting validation by resolving the dom4j document into sax     
    VerifierHandler handler = verifier.getVerifierHandler();
    SAXWriter writer = new SAXWriter( handler );
    writer.write( document );   
    
    return handler.isValid();
  }
  
  }
  
}

The whole work in the above example is done in validate() method. Foremost the we create a Factory instance and use it to create a JAVR org.iso_relax.verifier.Schema instance. In second step we create and configure a org.iso_relax.verifier.Verifier using a org.sax.ErrorHandler. I use Apaches Log4j API to log possible errors. You can also use System.out.println() or, depending of the applications desired robustness, any other method to provide information about failures. Third and last step resolves the org.dom4j.Document instance using SAX in order to start the validation. Finally we return a boolean value that informs about success of the validation.

Using teamwork of dom4j, MSV, JAVR and good old SAX simplifies the usage of multi schemata validation while gaining the power of MSV.

XSLT defines a declarative rule-based way to transform XML tree into plain text, HTML, FO or any other text-based format. XSLT is very powerful. Ironically it does not need variables to hold data. As Michael Kay XSLTReference says: "This style of coding without assignment statements, is called Functional Programming. The earliest and most famous functional programming language was Lisp ..., while modern examples include ML and Scheme." In XSLT you define a so called template that matches a certain XPath expression. The XSLT Processor traverse the source tree using a recursive tree descent algorithm and performs the commands you defined when a specific tree branch matches the template rule.

dom4j offers an API that supports XSLT similar rule based processing. The API can be found in org.dom4j.rule package and this chapter will introduce you to this powerful feature of dom4j.

Introducing dom4j's declarative rule processing

This section will demonstrate the usage of dom4j's rule API by example. Consider we have the following XML document, but that we want to transform into another XML document containing less information.

  
    <?xml version="1.0" encoding="UTF-8" ?>
    <Songs>
     <song>
       <mp3 kbs="128" size="6128">
         <id3>
          <title>Simon</title>
          <artist>Lifehouse</artist>
          <album>No Name Face</album>
          <year>2000</year>
          <genre>Alternative Rock</genre>
          <track>6</track>     
         </id3>
       </mp3>
      </song>
      <song>
       <mp3 kbs="128" size="6359">
         <id3>
          <title>Hands Clean</title>
          <artist>Alanis Morrisette</artist>
          <album>Under Rug Swept</album>
          <year>2002</year>
          <genre>Alternative Rock</genre>
          <track>3</track>
         </id3>
       </mp3>
      </song>
      <song>
       <mp3 kbs="256" size="6460">
         <id3>
          <title>Alive</title>
          <artist>Payable On Deatch</artist>
          <album>Satellit</album>
          <year>2002</year>
          <genre>Metal</genre>
          <track/>
         </id3>
       </mp3>
       <mp3 kbs="256" size="4203">
         <id3>
          <title>Crawling In The Dark</title>
          <artist>Hoobastank</artist>
          <album>Hoobastank (Selftitled)</album>
          <year>2002</year>
          <genre>Alternative Rock</genre>
          <track/>
         </id3>
       </mp3>
     </song>
    </Songs>
  
  

A common method to transform one XML document into another is XSLT. It's quite powerful but it is very different from Java and uses paradigms different from OO. Such style sheet may look like this.

    
      <xsl:stylesheet version="1.0"
           xmlns:xsl="http://www.w3.org/1999/XSL/Transform"    
           xmlns:fo="http://www.w3.org/1999/XSL/Format"
       >    
        <xsl:output method="xml" indent="yes"/>

        <xsl:template match="/">
         <Song-Titles>
           <xsl:apply-templates/>
         </Song-Tiltes>
        </xsl:template>
        
        <xsl:template match="/Songs/song/mp3">     
          <Song>
            <xsl:apply-template/>
          </Song>
        </xsl:template>
    
        <xsl:template match="/Songs/song/mp3/title">
          <xsl:text> <xsl:value-of select="."/> </xsl:text>
        </xsl:template> 
   
      </xsl:stylesheet> 
     
   

This stylesheet filters all song titles and creates a xml wrapper for it. After applying the stylesheet with XSLT processor you will get the following xml document.

    
      <?xml version="1.0" encoding="UTF-8" ?>
      <Song-Titles>
 	<song>Simon</song>
	<song>Hands Clean</song>
        <song>Alive</song>
        <song>Crawling in the Dark</song>
      </Song-Titles>
     
   

Okay. Now it's time to present a possible solution using dom4j's rule API. As you will see this API is very compact. The Classes you have to write are neither complex nor extremely hard to understand. We want to get the same result as your former stylesheet.

  import java.io.File;

  import org.dom4j.DocumentHelper;
  import org.dom4j.Document;
  import org.dom4j.DocumentException;
  import org.dom4j.Element;
  import org.dom4j.Node;

  import org.dom4j.io.SAXReader;
  import org.dom4j.io.XMLWriter;
  import org.dom4j.io.OutputFormat;

  import org.dom4j.rule.Action;
  import org.dom4j.rule.Pattern;
  import org.dom4j.rule.Stylesheet;
  import org.dom4j.rule.Rule;

  public class SongFilter {
    
    private Document resultDoc;
    private Element songElement;
    private Element currentSongElement;
    private Stylesheet style;
    

    public SongFilter() {
        this.songElement = DocumentHelper.createElement( "song" );
    }

    
    public Document filtering(org.dom4j.Document doc) throws Exception {
        Element resultRoot = DocumentHelper.createElement( "Song-Titles" );
        this.resultDoc = DocumentHelper.createDocument( resultRoot );               
        
        Rule songElementRule = new Rule();
        songElementRule.setPattern( DocumentHelper.createPattern( "/Songs/song/mp3/id3" ) );
        songElementRule.setAction( new SongElementBuilder() );
        
        Rule titleTextNodeFilter = new Rule();
        titleTextNodeFilter.setPattern( DocumentHelper.createPattern( "/Songs/song/mp3/id3/title" ) );
        titleTextNodeFilter.setAction( new NodeTextFilter() );
        
        this.style = new Stylesheet();
        this.style.addRule( songElementRule );
        this.style.addRule( titleTextNodeFilter );
        
        style.run( doc );
        
        return this.resultDoc;
    }
    
    
    
    
    private class SongElementBuilder implements Action {
        public void run(Node node) throws Exception {
           currentSongElement = songElement.createCopy();
           resultDoc.getRootElement().add ( currentSongElement );
           
           style.applyTemplates(node);
        }
    }
    
    private class NodeTextFilter implements Action {       
        public void run(Node node) throws Exception {
          if ( currentSongElement != null )
          {
            currentSongElement.setText( node.getText() );
          }
        }        
    }
        
      
}
 

Define the root element or another container element for the filtered out information.

Create as many instances of org.dom4j.rule.Rule as needed.

Install for each rule a instance of org.dom4j.rule.Pattern and org.dom4j.rule.Action. A org.dom4j.rule.Pattern consists of a XPath Expression, which is used for Node matching.

A org.dom4j.rule.Action defines the process if a matching occured.

Create a instance of org.dom4j.rule.Stylesheet

Start the processing

If you are familiar with Java Threads you may encounter usage similarities between java.lang.Runnable and org.dom4j.rule.Action. Both act as a plugin or listener. And this Observer Pattern has a wide usage in OO and especially in Java. We implemented observers here as private inner classes. You may decide to declare them as outer classes as well. However if you do that, the design becomes more complex because you need to share instance of org.dom4j.rule.StyleSheet.

Moreover it's possible to create an anonymous inner class for org.dom4j.rule.Action interface.

Understanding dom4j's rule API

VisitorDeclartive Rule Processing
Use of Interfaces in designUse of Interfaces in design
Uncontrolled automatic recursive descent traversalRule controlled automatic recursive descent traversal
Needs knowledge of Visitor pattern to understandKnowledge of Observer/Publish-Subscriber pattern (ligua franca pattern besides Singleton) useful
Provides adapater class to simplify usage of interfaceAdapter not necessary due to interface using single method
Basic knowledge of dom4j's tree object model necessaryAdditional XPath knowlege for pattern specification necessary
Implementation is more compactMore code necessary to define the rules and action
High and easy modularityHigh modularity for controlled recursive processing, but more complex handling if you abandon inner or anonymous inner classes.

As shown above, dom4j's uses a very flexible OO-Representation of a XSLT Stylesheet. The smart handling of actions produces compact code.

The rule API is a OO representation of W3C XSLT. The API defines another way of traversing the in-memory dom4j tree. The traversal algorithm is called recursive descent and is the same as XSLT defines. Such algorithms are also used in compiler construction and described in literature.

XSLT defines a way of tree merging or filtering. If you output an eXtensible stylesheet result to another xml you merge an existing tree to another one using the instruction of the Stylesheet and if output to plain text a styling is used for filtering. First usage is addressed by this API. The second is also possible but not so easy to implement as in XSLT.

How does the rule API work? Each Stylesheet has a rule. A rule consists of an action and a pattern. Patterns are described with XPath. You start the processing of a Stylesheet on a specific source with must be a dom4j Node. Calling method style.applyTemplates(node); traverses the Node using a recursive descent algorithm - branch after branch. If a pattern matches the assigned action is activated.

If you are interested more in the way a xml document is traversed by XSLT processors I recommend Michael Kay's book XSLTReference.

XSLTReference Michael Kay

Copyright 2001 by Worx Press, Inc..

All rights reserved.

1-861-005067 Worx Press Worx Press
GoF95 Erich Gamma Richard Helm Ralph Johnson John Vlissides

Copyright 1995 by Addison Wesley Pub, Co..

All rights reserved.

0-201-633-612 Addison-Wesley
Pawlan98 Monica Pawlan

Copyright 1998 by http://developer.java.sun.com/javatips/jw-tips76.html.

All rights reserved.

JavaTip76 Dave Miller

Copyright by http://www.javaworld.com/javaworld/javatips/jw-javatip76.html.

All rights reserved.

BillVenners Bill Venners

Copyright by http://www.artima.com/designtechniques/interfaces.html.

All rights reserved.

Zvon

Copyright by http://www.zvon.org/xxl/XPathTutorial/General/examples.html.

All rights reserved.

RelaxNG

Copyright by http://www.oasis-open.org/committees/relax-ng/.

All rights reserved.

Relax

Copyright by http://www.xml.gr.jp/relax/.

All rights reserved.

TREX

Copyright by http://www.thaiopensource.com/trex/.

All rights reserved.

DTD

Copyright by http://www.w3schools.com/dtd/default.asp.

All rights reserved.

XSD

Copyright by http://www.w3.org/XML/Schema http://www.w3.org/XML/1998/06/xmlspec-report.

All rights reserved.

JARV

Copyright by http://iso-relax.sourceforge.net/JARV/.

All rights reserved.

dom4j-1.6.1/docs/status.html0000644000175000017500000016643310242117703015237 0ustar ebourgebourgdom4j - Change History
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

CVS

Fixed bug in BeanElement which prevented proper execution of the bean samples (contributed by Wonne Keysers).

STAXEventWriter now uses XMLEventConsumer instead of XMLEventWriter (contributed by Christian Niles).

Fixed bug in SAXReader that caused problems parsing files in OSX (reported by Paul Libbrecht).

Fixed bug in XMLWriter that caused whitespace to be added between successive calls of the characters(...) method (reported by Paul Libbrecht).

Improved performance of NamespaceCache in multithreaded environments (contributed by Brett Finnell).

1.5 beta 2

Added flag to OutputFormat that supresses newline after XML declaration.

Upgraded dependencies to their latest version on ibiblio.

Added method to DocumentHelper that allows user to specify encoding when parsing an xml String (contributed by Todd Wolff).

Fixed a ClassCastException bug in BeanElement.

Fixed a bug in SAXContentHandler which caused a NullPointerException in some situations.

Fixed bug which prevented an element's namespace prefix from being registered for use in xpath expressions (contributed by Todd Wolff).

Fixed bug in XMLWriter that caused duplication of the default namespace declaration (reported by Todd Wolff).

Added a bunch of patches to make the dom4j DOM classes more DOM compliant (contributed by Curt Arnold).

Fixed bug in DispatchHandler which made the handler not reusable (reported by Ricardo Leon).

Fixed bug in SAXContentHandler that caused incorrect CDATA section parsing (contributed by Todd Wolff).

Fixed bug in SAXContentHandler that caused incorrect entity handling.

Fixed bug in XMLWriter causing padding to be disabled, even if enabled in the specified outputformat (reported by Bo Gundersen).

Added initial support for STaX streams (contributed by Christian Niles).

1.5 beta 1

Fixed encoding bug in Document.asXML() and DocumentHelper.parseText().

Fixed bug in SAXReader that caused problems resolving relative URIs when parsing java.io.File Objects (reported by Kohsuke Kawaguchi).

The iterators returned by the Element.elementIterator(...) methods now support remove().

DOMWriter writes now DOM Level 2 attributes and elements (reported by Geert Dendoncker and Joury Gokel).

Use latest implementation of the Aelfred parser.

Fixed some problems with internal/external DTD declarations (reported by Bryan Thompson).

Upgraded to Jaxen 1.1 beta 2.

Ignore attribute order when comparing Elements in NodeComparator.

Fixed bug in XMLWriter where namespace declarations were duplicated.

Fixed bug in parsing a Processing Instruction (reported by Vladimir Kralik).

Added support for Stylesheet modes (reported by Mark Diggory).

Don't escape " and ' characters in attribute values if it's not necessary (contributed by Christian Niles).

Fixed some DOMNodeHelper issues (reported by Henner Kollmann).

Fixed some datatype issues (reported by Thomas Draier).

Fixed an bug where the EntityResolver was not set on the XMLReader.

Fixed multithreaded access on DefaultElement.

Fixed problem parsing XML Files (reported by Geoffrey Vlassaks).

Added xml:space attribute support based on XML Specification 1.0.

Maven build of dom4j is now nearly complete. Maven is now used for the website generation.

Fixed some bugs in BackedList (contributed by Alessandro Vernet).

1.4 Release

Added patch supplied by Dan Jacobs that fixes some entity encoding problems in XMLWriter - cheers Dan!

Patched the DOMElement replaceChild method to return the correct Node and to throw a DOMException when trying to replace a non-existing child.

Added patch to BackedList that could cause IndexOutOfBoundsExceptions to be thrown that was kindly supplied by Andy Yang - thanks Andy!

Update of Cookbook containing a chapter about rule API.

Patched SAXWriter to not pass in null System or Public IDs which can cause problems in Saxon.

Patched dom4j to work against Jaxen 1.0 RC1 or later build.

Applied patch to bug found by Tom Oehser that XPath expressions using elements or attributes whose name starts with '_' were not being handled correctly. It turns out this was a SAXPath issue.

Applied patch to bug found by Soumanjoy Das that creating a new DOMDocument then calling createElement() would generate a ClassCastException.

Applied patch supplied by James Dodd that fixes a MIME encoding issue in the embedded Aelfred parser

Applied patch to fix bug found by David Frankson. Adding attributes with null values causes problems in XSLT engines so now adding a null valued attribute is equivalent to removing the attribute. So null attribute values are silently ignored. e.g.

Element element = ...;
element.addAttribute( "foo", "123" );
...
Attribute attribute = element.attribute( "foo" );
assertTrue( attribute != null );
...
element.addAttribute( "foo", null );
attribute = element.attribute( "foo" );
assertTrue( attribute == null );

1.3 Release

Patches

Applied patch to bug found by Mike Skells that was causing XPath.matches() to return true for absolute XPaths which returned different nodes to the node provided to the XPath.

Applied patch provided by Stefan that was causing IndexOutOfBoundsException when using the evaluate() method in DefaultXPath on an empty result set. Also added a test case to org.dom4j.TestXPathBug called testStefan().

Applied patch suggested by Frank Walinsky, that XPath objects are now Serializable.

Applied patch provided by Bill Burton that fixes union pattern matching.

1.2 Release

New Swing TableModel for displaying XML

Added a new Swing TableModel for displaying XML data in a Swing user interface. It uses an XPath based model to define the rows and column values. A table definition can be specified using a simple XML format and then loaded in a small amount of code. e.g. here's an example of a table that will list the servlets used in a web.xml document

<table select="/web-app/servlet">
  <column select="servlet-name">Name</column>
  <column select="servlet-class">Class</column>
  <column select="../servlet-mapping[servlet-name=$Name]/url-pattern">Mapping</column>
</table>

Notice the use of the $Name XPath variable to access other cells on the row. Here's the pseudo code to display a table for an XML document.

Document tableDefinition = ...;
Document source = ...;
TableModel tableModel = new XMLTableModel( tableDefinition, source );
JTable table = new JTable( tableModel );

There is a sample program in samples/swing/JTableTool which will display any table definition for a given source XML document. There is an example table definition for the periodic table in xml/swing/tableForAtoms.xml.

Registering Namespace URIs for XPath

Added a new helper method to make it easier to create namespace contexts for doing namespace aware XPath expressions. The new setNamespaceURIs(Map) method on XPath makes it easier to pass in the prefixes and URIs you wish to use in an XPath expression. Here's an example of it in action

Map uris = new HashMap();
uris.put( "SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/" );
uris.put( "m", "urn:xmethodsBabelFish" );        
XPath xpath = document.createXPath( "/SOAP-ENV:Envelope/SOAP-ENV:Body/m:BabelFish" );
xpath.setNamespaceURIs( uris );        
Node element = xpath.selectSingleNode( document );

In addition DocumentFactory has a setXPathNamespaceURIs(Map) method so that common namespace URIs can be associated with a DocumentFactory so namespace prefixes can be used across many XPath expressions in an easy way. e.g.

// register prefixes with my factory
Map uris = new HashMap();
uris.put( "SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/" );
uris.put( "m", "urn:xmethodsBabelFish" );        

DocumentFactory factory = new DocumentFactory();
factory.setXPathNamespaceURIs( uris );

// now parse a document using my factory
SAXReader reader = new SAXReader();
reader.setDocumentFactory( factory );
Document doc = reader.read( "soap.xml" );

// now lets use the prefixes
Node element = doc.selectSingleNode( "/SOAP-ENV:Envelope/SOAP-ENV:Body/m:BabelFish" );

Whitespace handling

There is a new mergeAdjacentText option available on SAXReader to concatenate adjacent text nodes into a single Text node.

In addition there is a new stripWhitespaceText option to strip text which occurs between start/end tags which only consists of whitespace.

For example, parsing the following XML with the stripWhitespaceText option enabled and the mergeAdjacentText option enabled will result in a single child node of the parent element, rather than 3 (2 text nodes containing whitespace and one element).

<parent>
  <child>foo</child>
</parent>

Note that this option will not break most mixed content markup such as the following, since its only whitespace between tag start/ends that gets removed; non-whitespace strings are not trimmed.

<p>hello <b>James</b> how are you?</p>

Both these options together can improve the parsing performance by around 10-12% depending on the structure of the document. Though the whitespace layout of the XML document will be lost, so only use these modes in data-centric applications like XML messaging and SOAP.

So a typical SOAP or XML messaging developer, who may care more about performance than preserving exact whitespace layout, may use the following code to make the SAX parsing more optimal.

SAXReader reader = new SAXReader();
reader.setMergeAdjacentText( true );
reader.setStripWhitespaceText( true );
Document doc = reader.read( "soap.xml" );

Patches

Applied patch to HTMLWriter to fix bug found by Dominik Deimling that was not correctly outputting CDATA sections correctly.

Patched the setName() method on Element so that elements can be renamed. Also added a new setQName() to the Element interface so that elements can be renamed in a namespace aware manner. Thanks to Robert Lebowitz for this.

Applied fix to bug found by Manfred Lotz that XMLWriter in whitespace trimming mode would sometimes not correctly insert a space when text is seperated by newlines. The Test case testWhitespaceBug() in org.dom4j.TestXMLWriter reproduces the bug that has now been fixed.

Applied patches supplied by Stefan Graeber that enhance the datatype support to support included schemata and derived element types.

Applied patches suggested by Omer van der Horst Jansen to enable dom4j to fully work properly on JDK1.1 platforms. There were some uses of java.util.Stack which have been changed to ArrayList.

Applied patches supplied by Maarten Coene that fixes some issues with using the correct DocumentFactory when using the DOM implementation.

Updated the MSV support to comply with the latest MSV version, 1.12 (Nov 01 2001). In addition the MSVDemo.java in dom4j/src/samples/validate has been replaced by JARVDemo.java which now uses the JARV API to validate a dom4j document using the MSV implementation. This demo can validate any XML document against any DTD, XML Schema, Relax NG, Relax or Trex schema - thanks to the excellent JARV API and MSV library.

Applied patches supplied by Steen Lehmann that fixes handling of external DTD entities in SAXContentHandler and fix the XML output of the ExternalEntityDecl

Applied patch to bug found by Steen Lehmann that XPath expressions on the root element were not correctly handling namespaces correctly. The test case is demonstrated in dom4j/src/test/org/dom4j/xpath/TestSelectSingleNode.java

Added patch found by Howard Moore when using XTags that XPath string values which contained strings with entities, such as the use of &amp; in a text, would result in redundant spaces occuring, breaking URLs.

1.1 Release

New features

Added a new package, org.dom4j.dtd which contains some DTD declaration classes which are added to the DocumentType interfaces List of declarations. This is useful for finding out details of the attribute or element delcarations inside either the internal or external DTD subset of a document.

To expand internal or external DTD subsets when parsing with SAXReader use the 2 properties on SAXReader (and SAXContentHandler).

SAXReader reader = new SAXReader();
reader.setIncludeInternalDTDDeclarations( true );
reader.setIncludeExternalDTDDeclarations( true );
Document doc = reader.read( "foo.xml" );

DocumentType docType = doc.getDocType();
List internalDecls = docType.getInternalDeclarations();
List externalDecls = docType.getExternalDeclarations();

This new feature means that XML documents which use internal DTD subsets, external DTDs or a mixture of internal and external DTD subsets can now be properly round tripped.

Note that there appears to be a bug in Crimson 1.1.3 which does not properly differentiate between internal or external DTD subsets. Refer to the startDTD() method of LexicalHandler for details of how startEntity/endEntity is meant to demark external DTD subsets.

Its our intention to expand internal DTD subsets by default (so that documents can be properly round tripped by default) but require external DTD subsets to be explicitly enabled via the property on the SAXReader (or SAXContentHandler). This bug in Crimson causes all DTD declarations to appear as internal DTD subsets, which both is a performance overhead and breaks round tripping of documents which just use external DTD declarations. So until this matter is resolved both internal and external declarations are not expanded by default.

Note that the code works perfectly against Xerces.

Patches

Applied patch submitted by Yuxin Ruan which fixes some issues with XML Schema Data Type support

Followed Dennis Sosnoski's suggestion, adding a null text String to an Element now throws an IllegalArgumentException. To ensure that the IllegalArgumentException is not thrown its advisable to check for null first. For example...

Element element = ...;
String text = ...;

// might throw IllegalArgumentException
// if text == null
element.addText( text );

// safer to do this
if ( text != null ) {
  element.addText( text );
}

Fixed problem found by Kesav Kumar Kolla whereby a deserialized Document could have problems if new elements were attempted to be added. The problem was an issue with DocumentFactory not correctly deserializing itself properly.

Fixed problem found by David Hooker with Ant build file for the binary and source distribution that was not including the manifest file in the distribution.

Applied patch submitted by Lari Hotari that was causing the XMLWriter to fail when used as a SAX XMLFilter or ContentHandler to turn SAX events into XML text. Thanks Lari!

Fixed bug found by Kohsuke Kawaguchi that there was a problem in XMLWriter during its serialization of a document which redeclared the default namespace prefix. It turned out to be a bug in org.dom4j.tree.NamespaceStack where redeclarations of namespace prefixes were not being handled properly during serialization. The test cases in org.dom4j.TestXMLWriter and org.dom4j.TestNamespaces have been improved to test these features more rigorously.

Fixed bug found by Toby that was causing a security exception in applets when using a DocumentFactory.

Implemented the suggestion by Kesav Kumar, that the detach() method now returns the node (this) so that moving nodes from one part of a document to any another can now be one line of code. Here's an example of it in use.

Document doc1 = ...;
Document doc2; = ...;
Element destination = doc2.getRootElement();
Element source = doc1.selectSingleNode( "//foo[@style='bar']" );

// lets move the source to the destination
destination.add( source.detach() );

Added better checking in selectSingleNode() implementation so that XPath expressions which do not return a Node throw a meaningful exception (not ClassCastException) informing the user of why the XPath expression did not succeed.

Added patch found by Kesav Kumar that a document containing null Strings would cause a NullPointerException to be thrown if it was passed into SAXWriter (used by the JAXP - XSLT code). Now the SAXWriter will quietly ignore null Strings, as will XMLWriter.

1.0 release

New features

Added helper method setXMLFilter() to SAXReader making it easier to install SAX filters to filter or preprocess SAX events before a dom4j Document is created. Also added a new sample program called sax.FilterDemo that demonstrates how to use a SAX filter with dom4j.

Added full support for Jaxen function, namespace and variable context interfaces. This allows the XPath engine to be fully customized. e.g.

XPath xpath = document.createXPath( "//foo[@code='123']" );

// customize function, namespace and variable contexts
xpath.setFunctionContext( myFunctionContext );
xpath.setNamespaceContext( myNamespaceContext );
xpath.setVariableContext( myVariableContext );

List nodes = xpath.selectNodes( document );

Added new helper class org.dom4j.util.XMLErrorHandler which turns SAX ErrorHandler callbacks into XML that can then be output in a JAXM or SOAP message or styled via XSLT or whatever.

Added new helper method DocumentHelper.makeElement(doc, "a/b/c") which will navigate from a document or element to the given simple path, creating new elements along the way if need be. This allows elements to be found or created using a simple path expression mechansim.

Added helper method getQName(String qualifiedName) to Element so that easier element name matching can be done. Here are some examples of it in use.

// find all elements with a local name of "foo" 
// in any namespace
List list = element.elements( "foo" );

// find all elements with a local name "foo" 
// and the default namespace URI
List list = element.elements( element.getQName( "foo" ) );

// find all elements which match the local name "foo" 
// and the namespace URI mapped to the "x" prefix
List list = element.elements( element.getQName( "x:foo" ) );

Added helper method on org.dom4j.DocumentFactory called getQNames that returns a List of all the QNames that were used to parse the documents.

Added an EntityResolver property to SAXReader to make it easier to configure a specific EntityResolver.

Patches

Added patch so that patterns such as @id='123' and name()='foo' are now working properly again. Also patterns such as not(@id='123') work now too.

Patched the dynamic loading of classes to fix some ClassLoader issues found with some application servers.

Ported the data type support to work with the latest MSV library from Sun

Fixed bug spotted by Stefan Graeber that was causing a DocumentException to be thrown with Xerces when turning validation mode on.

Patched bug in QName which was using the qualified name rather than the local name along with the namespace URI to determine equality.

Added patch kindly supplied by Michal Palicka that SAXReader was passing in the wrong name for the SAX string-interning feature. Thanks Michal!

Fixed the behaviour of DocumentFactory.createXPathFilter() to use XPath filtering rather than XSLT style patterns. One of the major differences is that an XSLT pattern (used in the <xsl:template match="pattern"/> element in XSLT) works slightly differently. An element <foo> would match an XSLT pattern "foo" whereas an element <bar> could match an XPath filter "foo" if it contained a child <foo> element.

Patched the behaviour of Node.matches(String xpathExpression) so that it uses XPath filters now rather than XSLT patterns.

Patched bug in XRule implementation in org.dom4j.rule that was causing ordering problems when using stylesheets - the Rule precendence order was not being correctly used.

Backed out a previous patch added to 0.9 such that attributes with no namespace prefix are in no namespace. An attribute does not inherit the default namespace - the only way to put an attribute into a namespace is via a namespace prefix.

Patched XMLWriter to that a flush() is not required when using an OutputStream and the various sub-document write() methods are called such as write(Element), write(Attribute), write(Node), write(Namespace) etc.

Fixed bug in SAXReader that setEntityResolver() was not always behaving properly. Also the default entity resolver used to locate XML Schemas seems to work properly now.

Moved the XML Schema Data Type supporting classes in org.dom4j.schema.Schema* to org.dom4j.datatype.Datatype*. This should avoid confusion and better describe the intent of the classes, to implement Data typing, rather than schema validation. We hope to use the MSV library for all of our schema validation requirements.

0.9 release

Full support for the Jaxen XPath engine

The XPath engine in dom4j has been migrated to using Jaxen. This single XPath engine can be plugged into any model such that Jaxen will support DOM, dom4j, EXML and JDOM. Hopefully we'll get Jaxen working on Java Beans too.

In general this will mean a much better, more compliant and more bug-free XPath engine for dom4j as it will be used extensively across XML object models.

Already numerous irregularities have been fixed in the XPath support in dom4j. We have donated the dom4j XPath test harness to Jaxen so that we now have a large rigorous test harness to ensure correct XPath behaviour - this test harness is run against all 4 current XML object models to ensure consistent behaviour and valid XPath compliance.

We are also in the process of migrating over our XPath extension functions as well as adding additional XPath functions such as those defined in XSLT and XPointer.

New features

New class org.dom4j.io.XMLResult which is-a JAXP Result which uses the same org.dom4j.io.OutputFormat object to provide its formatting options to allow XML output from JAXP (such as via XSLT) to be pretty printed.

XMLWriter now implements the SAX XMLFilter interface so that it can be added to a SAX parsing filter chain to output the XML being parsed in a simple way. Many thanks to Joseph Bowbeer for his help in this area.

Added setProperty() and setFeature() methods to SAXReader to allow the easy configuration of custom parser properties via SAXReader, such as being able to specify the location of schema or DTD resources.

Added new method OutputFormat.createCompactFormat() for those wishing to output their XML in a compact format, such as in messaging systems.

Patches and bug fixes

Fixed bug in getNamespaceForPrefix() where if the prefix is null or "" and there is a default namespace defined, this method was returning a namespace instance with the incorrect URI.

Patched DOM writer so that it uses JAXP if it is available on the CLASSPATH using namespace aware mode by default.

Fixed a number of issues relating to namespaces and the redefinition of namespace prefixes. We now have a quite aggressive JUnit test harness to ensure that we handle namespace URIs correctly when prefixes are mapped and unmapped.

Applied patch from Andrew Wason for HTMLWriter to support the full HTML 4.01 DTD elements which do not require proper XML element closes. The new elements are PARAM, AREA, LINK, COL, BASE and META.

Fixed bug found by Dennis Sosnoski that SAX warnings were causing exceptions to be thrown by the SAXReader. Now warnings are silently ignored. If you want to detect warnings then an ErrorHandler should be registered with the SAXReader.

Patched bug that was also found by Jonathan Doughty for the non-standard behaviour of the FilterIterator. Also added Jonathan's JUnit test case to the distribution so that this problem should not come back.

Fixed bug that when round tripping into JAXP and back again, sometimes additional namespace attributes were appearing. Now the TestRoundTrip JUnit test case includes JAXP round tripping.

Fixed bug that attributes without a namespace prefix which are inside an element with a default namespace declaration of the form xmlns="theURI", the attribute now correctly inherits the namespace URI.

Applied patch found by Stefan Graeber that the UserDataFactory was not correctly creating UserDataAttribute instances.

Fixed bug that SAXWriter and DocumentSource were not correctly producing lexical events such as entities, comments and DOCTYPE declarations. Many thanks to Joseph Bowbeer for his help in this area.

0.8 release

New methods

hasContent()

has been added to the Node interface so that it is easy to decide if a node is a leaf node or not. This method was suggested by Dane Foster. This method returns true if the node is a Branch (i.e. an Element or Document) which contains at least one node.

getPath(Element context)
getUniquePath(Element context)

These new methods allow paths and unique paths to be created relatively. Previously both getPath() and getUniquePath() would create absolute XPath expressions. These new methods allow relative path expressions to be created by providing an ancestor Element from which to make the path expression. This method was suggested by Chris Nokleberg.

Patches and bug fixes

Fixed bug found by Chris Nokleberg when using the UserDataElement that the clone() and createCopy() methods were not correctly copying the user data object. A JUnit test case has been added that tests this fix (org.dom4j.TestUserData). If any deep copying of user data objects is required then UserDataElement now has a method getCopyOfUserData() which can be overloaded to perform a deep copy of any user data objects if required.

Minor patch for dom4j implementors wishing to create their own QName implementations. Previously the DocumentFactory class was hardwired to use QNameCache internally which was hard wired to only create QName instances. Now some factory methods have been added such that you can derive your own DocumentFactory which uses your own QNameCache which creates your own QName classes.

If JAXP can be found in the CLASSPATH then it is now used first by the SAXReader to find the correct SAX parser class. We have found that sometimes (e.g. Tomcat 4.0 beta 6) the value of the org.xml.sax.driver system property is set to a class which is not in the CLASSPATH but a valid JAXP parser is present. So now we try JAXP first, then the SAX system property then if all else fails we use the bundled Aelfred SAX parser.

Fixed XPath bug found by James Elson that the path /foo[@a and @b] or /foo[@a='1' and @b='2'] was no longer working correctly. This is now fixed and many tests of this nature have been added to the JUnit test harness.

Fixed some namespace related bugs found by Steen Lehmann. It appears that for a document of:-

<a xmlns="dummyNamespace">
  <b>
    <c>Hello</c>
  </b>
</a>

Then the path /a/b/c will not find anything - this is correct according to the XPath spec. Instead the path /*[name()='a']/*[name()='b']/*[name()='c'] is required. These changes have been applied to getPath() and getUniquePath() such that these methods now work, irrespectively of the namespaces used in a document. Finally many new test cases have been added to validate a variety of XPath expressions with various uses of namespaces.

SAXWriter now fully supports the SAX feature "http://xml.org/sax/features/namespace-prefixes". Failure to support this feature properly was causing problems when outputting a dom4j Document using JAXP - the namespace declarations often did not appear correctly.

Patched bug in XMLWriter which caused multiple duplicate namespace declarations to sometimes appear.

0.7 release

Integration with SAXPath

The SAXPath project is a Simple API for XPath parsing. Its analogous to SAX in that the API abstracts away the details of parsing XPath expressions and provides a simple event based callback interface.

Originally dom4j was using a parser generated via the Antlr tool which resulted in a considerably larger code base. Now dom4j uses SAXPath for its XPath parsing which results in faster XPath parsing and a much smaller code base.

The dom4j.jar is now about 100 Kb smaller! Also several XPath related bugs are now fixed. For example the numeric paths like '2 + count(//foo)' are now working.

Patches and bug fixes

Fixed bug found by Tobias Rademacher that XML Schema Data Type support wasn't working correctly when the XSD document used a namespace prefix. The bug was hidden by a further bug in the JUnit test case that was not correctly testing this case. Both these bugs are now fixed.

Fixed bug found by Piero de Salvia that some invalid XPath expressions were not correctly throwing exceptions. Now any attempt to use any invalid XPath expressions should result in an InvalidXPathException being thrown.

Applied patch submitted by Theodor Schwarzinger that fixes the preceding-sibling and preceding axes.

Fixed bug found my James Elson that the normalize() method was being quite agressive and removing all text nodes! New JUnit test case added to ensure this doesn't break again.

Improved the setContent() semantics on Branch (and so Element and Document) such that the parent and document relationships are correctly removed for old content and added for new content. As a helper method, the setContent() method will clone any content nodes which are already part of an existing document. So for example the following code will clone the content of a document.

    Document doc1 = ...;
    Document doc2 = DocumentHelper.createDocument();  
    doc2.setContent( doc1.content() );
Though this behaviour is much more useful when used with elements...
    Element sourceElement;
    Element destElement;

    // copy the content of sourceElemenet
    destElement.setContent( sourceElement.content() );

0.6 release

Serialization support added

Support has been added for Java Serialization so dom4j documents can be serialized over RMI or EJB calls. Note that currently Serialization is much slower (by a factor of 2-5 times) than using the textual format of XML so we recommend sending XML text over RMI rather than serialization if possible. Over time we will tune the serialization implementation to be at least as fast as using the text format (even if that means under the covers we just use the text format).

Patches and bug fixes

Fixed bug in XPath engine found by Christophe Ponsard for paths of the form /* which were not finding anything. Now we have an extensible XPath test harness (in src/test/org/dom4j/TestXPathExamples.java) which contains some test cases for these kinds of paths. We can extend these cases to test other XPath expressions easily.

Fixed bug in elementByID() method found by Thomas Nichols that was resulting in the element not being found correctly.

Fixed bug in IndexedElement reported by Kerstin Gr�nefeld that was causing a null pointer exception when using XPath on an IndexedElement.

Applied the patch supplied by Mike Skells that fix problems with the getUniquePath() method not returning properly indexed elements

Applied a fix to the problem found by Dane Foster when using dom4j with JTidy. JTidy returns null for getLocalName() so DOMReader has been patched to handle nulls returned from either getLocalName() or getName().

Fixed bug reported anonymously to the Sourceforge Site here that explicitly creating a Document from an existing Element could cause problems when using XMLWriter.

Assorted performance tunings of SAX parsing, avoiding unnecessary repeated code paths.

Tidied factory and construction of Element code such that there are no longer dependencies on the SAX Attributes class. This was originally added as a performance enhancement, but after further refactoring this is now no longer needed. This makes the process of creating new Element derivations or DocumentFactory implementations easier.

0.5 release

NodeComparator available

For those wishing to do value based comparisons of Nodes, Element, Attributes, Documents or Document fragments there is a new NodeComparator class which implements the Comparator interface from the Java Collections Framework.

New helper method DocumentHelper.parseText()

A new helper method has been added for parsing text. For example:-

    Document document = DocumentHelper.parseText(
        "<team> <author>James</author> </team>"
    );

New Branch.normalize() method

The Branch interface (and so Document and Element interfaces) has a new normalize() method that has the same semantics as the same method in the DOM API to remove empty Text nodes and merge adjacent Text nodes.

Easier document building methods

A document can now be constructed more easily now that the addXXX() methods return a reference to the Document or Element which created them. An example is shown below

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Foo {

    public Document createDocument() {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement( "root" );

        Element author1 = root.addElement( "author" )
            .addAttribute( "name", "James" )
            .addAttribute( "location", "UK" )
            .addText( "James Strachan" );
        
        Element author2 = root.addElement( "author" )
            .addAttribute( "name", "Bob" )
            .addAttribute( "location", "Canada" )
            .addText( "Bob McWhirter" );

        return document;
    }
}

Note that the addElement() method returns the new child element not the parent element.

To promote consistency, the Element.setAttributeValue() method is now deprecated and should be replaced with Element.addAttribute().

Patches and bug fixes

Applied Theo's patch for cloning of Documents correctly together with JUnit test cases to ensure this keeps working.

Applied Rob Wilson's patch that NullPointerExceptions were being thrown if a Document is output with the XMLWriter and an attribute value is null.

Fixed problem found by Nicolas Fonrose that XPath expressions using namespace prefixes were not working correcty.

Fixed problem found by Thomas Nichols whereby default namespaces with no prefix were not being processed correctly. As a result of finding this bug we now have a rigorous JUnit round trip test harness in place which highlighted a number of issues with namespaces when round tripping from dom4j to SAX to DOM to Text and back again. These issues have now been fixed and should not show up again hopefully.

Fixed some detach() bugs that were found with Attributes.

Default encoding is now "UTF-8" rather than "UTF8". Thanks to Thomas Nichols for spotting that one. Also the default line seperator when using XMLWriter is now "\n" rather than "\r\n"

If an XMLWriter is used with an OutputStream then an explicit call to flush() is no longer required after calling write(Document)

Some housekeeping was performed in the naming of some implementation classes. The old XPathXXX.java classes in the org.dom4j.tree package where XXX = Attribute, CDATA, Comment, Entity, ProcessingInstruction and Text have been renamed to DefaultXXX and the corresponding DefaultXXX has been renamed to FlyweightXXX. This makes it clearer the purpose of these implementation classes. The default implementations of the leaf nodes are mutable but cannot be shared across elements. The FlyweightXXX implementations are immutable and can be shared across nodes and documents.

0.4 release

Enhanced event notification mechanism

A new enhanced event notification mechanism has been implemented by David White. Now you can register multple ElementHandler instances with a SAXReader object before you parse a document such that the different handlers are notified when different paths are reached.

The ElementHandler interface now has both onStart() and onEnd() allowing more fine grained control over when you are called and the ability to perform actions before or after the content for an Element is populated. The methods also take a reference to a ElementPath to allow more optimised and powerful access to the path to the specified document.

Early alpha release of XML Schema Data Type support

This release contains an alpha release of XML Schema Data Type support. The main class in question is the XML Schema Data Type aware DatatypeDocumentFactory which will create an XML Schema Data Type aware XML object model.

The getData() and setData(Object) methods on Attribute and Element allow access to the concrete data types such as Dates and Numbers.

Patches and bug fixes

Applied Theo's patch for the XPath substring function that was causing the incorrect string indexes to be returned. The substring now returns the correct answer.

Applied Theo's patch for incorrectly escaping of element text.

Fixed bug in the XPath engine for absolute path expressions which now work correctly when applied to leaf nodes.

Fixed bug in the name() and local-name() functions such that the following expressions now work fine local-name(..), name(parent::*).

A variety of minor performance tuning optimisations have been made.

0.3 release

The org.dom4j.io.OutputFormat class now has a new helper method to make it easier to create pretty print formatting objects. The new method is OutputFormat.createPrettyPrint(). So to pretty print some XML (trimming all whitespace and indenting nicely) the following code should do the job...

    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter( out, format );
    writer.write( document );
    writer.close();

SAXReader.read(String url) can now accept either a URL or a file name which makes things a little easier. The logic uses the existence of a ':' in the url String to determine if it should be treated as a URL or a File name.

For more explicit control over whether documents are Files or URLs call SAXReader.read(File file) or SAXReader.read(URL url)

A new extension function, matrix-concat() was submitted by James Pereira. By default, doing concat() functions in XPath the 'string-value' is taken for each argument. So for a document:-

<root project="dom4j">
    <contributor>James Pereira</contributor>
    <contributor>Bob McWhirter</contributor>
</root;>

Then the XPath

concat( 'thanks ', /root/contributor )

would return

"thanks James Pereira"

as the /root/contributor expression matches a node set of 2 elements, but the "string-value" takes the first elements text. Whereas matrix-contact will do a cartesian product of all the arguments and then do the concatenation of each combination of nodes. So

matrix-concat( 'thanks ', /root/contributor )

will produce

"thanks James Pereira"
"thanks Bob McWhirter"

The cartesian product is done such that multiple paths can be used.

matrix-concat( 'thanks ', /root/contributor, ' for working on ', '/@project' )

will produce

"thanks James Pereira for working on dom4j"
"thanks Bob McWhirter for working on dom4j"

Fixed bug where XMLWriter.write(Object) was not correctly writing a Document instance.

Finally, a couple of small issues with the build process have been fixed. The dom4j.jar no longer contains any SAX or DOM classes (they are all in dom4j-full.jar) And the Antlr grammar files for the XPath parser are now corrrectly included in the binary distribution.

0.2 release

There following new features were added:-

  • Clean integration with XSLT via JAXP / TrAX API.
  • New SAXValidator to allow validation on prebuild Document instances
  • XMLWriter and HTMLWriter rewritten so that they work at either the SAX level or the dom4j level. API much improved and more like Reader and Writer in the JDK.
  • API modified to avoid clashes with WC3 DOM such that a dual implementation of dom4j and DOM is now possible. An early alpha release of a DOM implementation of dom4j is available.
  • New sorting method added to Node for easier selections of nodes which are sorted via an XPath expression. The following code sorts all CUSTOMER elements by their name attributes and removes duplicates:-
    Document document 
      = new SAXReader().read( new File( "customers.xml" ) );
    
    List customers 
      = document.selectNodes( "//CUSTOMER", "@name", true );
                  
  • The getText() and getStringValue() methods of Element now return the textual values of CDATA, Entity and Text nodes. The previous version only returned Text node values.
  • Refactored code and removed XPathEngine, XPathHelper and all the static newXXX() methods in DocumentFactory. Added equivalent methods to DocumentHelper and DocumentFactory.

This release also includes full XPath source code.

0.1 release

Initial release which comes complete with DOM, JAXP and SAX support and integrated XPath

To Do List

  • The internal subset does not pass through DOMReader and DOMWriter. This needs patching!
  • We should add support for Xerces XNI API via an XNIReader and XNIWriter. This would also allow dom4j users to make good use of the NekoHTML parser thats layered on top of XNI.
  • Better documentation and user guides
  • A lazy parser; implement a special Element implementation (or probably a special List) which allows the XPP (XML Pull Parser) to parse the document as it is navigated rather than all up front.
  • Build a dom4j validator based on top of Suns MSV library
  • Ensure that the optional DOM implementation passes the DOM compliance tests
  • Implement a ValidatingDocumentFactory and an EncodingDocumentFactory which can be used by developers where invalid strings may be specified allowing validation or encoding of names or text values to be done in one place for use across parsers or application code. This would avoid any performance hit by making this kind of validation the default behaviour.
  • Implement a canonical XML processor
  • Implement XML Signature
  • Implement XPointer, XLink and XInclude
  • Build a version of XMLC which uses the dom4j API rather than DOM which could also make use of XPath, XSLT and Java 2 Collections support.
  • Consider adding support for Java Generics such that typesafe Iterators can be used. For example
    Iterator<Node> iter = element.nodeIterator();
    while ( iter.hasNext() ) {
        Node node = iter.next();
    }
    
    Iterator<Element> iter2 = element.elementIterator( "foo" );
    while ( iter2.hasNext() ) {
        Element foo = iter2.next();
    }
              
  • Implement XSLT engine on top of dom4j?
  • XML Query implementation on top of dom4j?

Known problems

The following functions are not yet fully supported in the inbuilt XPath engine

  • id()
  • generate-id()
  • format-number()

The optional W3C DOM implementation of the dom4j API is not yet at full DOM compliance

Contributors

The following people have contributed to the dom4j project. Many thanks to you all!

  • James Strachan
  • Bob McWhirter
  • James Dodd
  • James Elson
  • Jakob Jenkov
  • James Pereira
  • David White
  • Tobias Rademacher
  • Rashmi Mathew
  • Jonathan Doughty
  • Joseph Bowbeer
  • Michal Palicka
  • Yuxin Ruan
  • Steen Lehmann
  • Maarten Coene
  • Stefan Graeber

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/javadoc-warnings-report.html0000644000175000017500000003565710242117700020462 0ustar ebourgebourgdom4j - JavaDoc Audit Results
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
    • Change Log
    • Changes
    • Checkstyle
    • Clover
    • Developer Activity
    • FAQs
    • File Activity
    • JavaDocs
    • JavaDoc Report
    • JavaDoc Warnings Report
    • Metrics
    • Unit Tests
    • Source Xref
    • Test Xref
    • Project License
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

JavaDoc Warnings

The following document contains JavaDoc warnings.

Summary

FilesErrors
1428

Files

FilesErrors
org/dom4j/Element.java 1
org/dom4j/bean/BeanAttribute.java 2
org/dom4j/datatype/DatatypeAttribute.java 2
org/dom4j/io/DOMWriter.java 1
org/dom4j/io/DocumentSource.java 2
org/dom4j/io/HTMLWriter.java 3
org/dom4j/io/OutputFormat.java 1
org/dom4j/io/SAXModifier.java 3
org/dom4j/io/STAXEventReader.java 6
org/dom4j/io/STAXEventWriter.java 1
org/dom4j/jaxb/JAXBReader.java 1
org/dom4j/tree/FlyweightEntity.java 1
org/dom4j/util/UserDataAttribute.java 3
org/dom4j/util/UserDataElement.java 1

org/dom4j/Element.java

ErrorLine
@link#getDocument is an unknown tag. 29

org/dom4j/bean/BeanAttribute.java

ErrorLine
Tag @link: reference not found: Node#getText() 53
Tag @link: reference not found: Node#setText(String) 57

org/dom4j/datatype/DatatypeAttribute.java

ErrorLine
Tag @link: reference not found: Node#getText() 146
Tag @link: reference not found: Node#setText(String) 150

org/dom4j/io/DOMWriter.java

ErrorLine
@linkorg.w3c.dom.Document is an unknown tag. 95

org/dom4j/io/DocumentSource.java

ErrorLine
@linkDocument is an unknown tag. 28
@linkDocument is an unknown tag. 105

org/dom4j/io/HTMLWriter.java

ErrorLine
Tag @link: missing #: "OutputFormat.isXHTML() OutputFormat.isXHTML()" 181
Tag @link: can't find OutputFormat.isXHTML() in org.dom4j.io.HTMLWriter 181
@link#setPreformattedTags(java.util.Set) is an unknown tag. 181

org/dom4j/io/OutputFormat.java

ErrorLine
@linkXMLWriter is an unknown tag. 19

org/dom4j/io/SAXModifier.java

ErrorLine
@linkElementModifier is an unknown tag. 117
@linkElementModifier is an unknown tag. 261
@linkElementModifier is an unknown tag. 284

org/dom4j/io/STAXEventReader.java

ErrorLine
@linkStartElement is an unknown tag. 298
@linkAttribute is an unknown tag. 353
@linkNamespace is an unknown tag. 380
@linkCharacters is an unknown tag. 407
@linkComment is an unknown tag. 434
@linkEntityReference is an unknown tag. 461

org/dom4j/io/STAXEventWriter.java

ErrorLine
@link#writeElement(Element) is an unknown tag. 169

org/dom4j/jaxb/JAXBReader.java

ErrorLine
@linkorg.dom4j.ElementHandler is an unknown tag. 39

org/dom4j/tree/FlyweightEntity.java

ErrorLine
@link#setText is an unknown tag. 33

org/dom4j/util/UserDataAttribute.java

ErrorLine
@link#getData is an unknown tag. 25
Tag @link: reference not found: Node#getText() 37
Tag @link: reference not found: Node#setText(String) 41

org/dom4j/util/UserDataElement.java

ErrorLine
@link#getData is an unknown tag. 26

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/maven-reports.html0000644000175000017500000001711310242117713016505 0ustar ebourgebourgdom4j - Project Reports
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
    • Change Log
    • Changes
    • Checkstyle
    • Clover
    • Developer Activity
    • FAQs
    • File Activity
    • JavaDocs
    • JavaDoc Report
    • JavaDoc Warnings Report
    • Metrics
    • Unit Tests
    • Source Xref
    • Test Xref
    • Project License
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Maven Generated Reports

This document provides an overview of the various reports that are automatically generated by Maven. Each report is briefly described below.

Overview

DocumentDescription
Change LogReport on the source control changelog.
ChangesReport on the project changes.
CheckstyleReport on coding style conventions.
CloverClover test coverage report.
Developer ActivityReport on the amount of developer activity.
FAQsFrequently Asked Questions.
File ActivityReport on file activity.
JavaDocsJavaDoc API documentation.
JavaDoc ReportReport on the generation of JavaDoc.
JavaDoc Warnings ReportFormatted report of JavaDoc warnings.
MetricsReport on source code metrics.
Unit TestsReport on the results of the unit tests.
Source XrefA set of browsable cross-referenced sources.
Test XrefA set of browsable cross-referenced test sources.
Project LicenseDisplays the primary license for the project.

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/javadoc.html0000644000175000017500000003747410242117562015330 0ustar ebourgebourgdom4j - Javadoc Report
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
    • Change Log
    • Changes
    • Checkstyle
    • Clover
    • Developer Activity
    • FAQs
    • File Activity
    • JavaDocs
    • JavaDoc Report
    • JavaDoc Warnings Report
    • Metrics
    • Unit Tests
    • Source Xref
    • Test Xref
    • Project License
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Javadoc Report

  Generating Javadoc
  Javadoc execution
  Loading source files for package org.dom4j...
  Loading source files for package org.dom4j.bean...
  Loading source files for package org.dom4j.datatype...
  Loading source files for package org.dom4j.dom...
  Loading source files for package org.dom4j.dtd...
  Loading source files for package org.dom4j.io...
  Loading source files for package org.dom4j.jaxb...
  Loading source files for package org.dom4j.rule...
  Loading source files for package org.dom4j.rule.pattern...
  Loading source files for package org.dom4j.swing...
  Loading source files for package org.dom4j.tree...
  Loading source files for package org.dom4j.util...
  Loading source files for package org.dom4j.xpath...
  Loading source files for package org.dom4j.xpp...
  Constructing Javadoc information...
  Standard Doclet version 1.4.2_02
  Generating C:\Projects\dom4j_1.x_branch\dom4j\target\docs\apidocs\constant-values.html...
  Copying file C:\Documents and Settings\Maarten\.maven\cache\maven-javadoc-plugin-1.7\plugin-resources\stylesheet.css to file C:\Projects\dom4j_1.x_branch\dom4j\target\docs\apidocs\stylesheet.css...
  Building tree for all the packages and classes...
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataAttribute.java:25: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataElement.java:26: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataElement.java:26: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataElement.java:26: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataAttribute.java:25: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataAttribute.java:25: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataElement.java:26: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataAttribute.java:25: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataAttribute.java:25: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataElement.java:26: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataElement.java:26: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataElement.java:26: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataAttribute.java:25: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\OutputFormat.java:19: warning - @linkXMLWriter is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\OutputFormat.java:19: warning - @linkXMLWriter is an unknown tag.
  Building index for all the packages and classes...
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\DocumentSource.java:28: warning - @linkDocument is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\OutputFormat.java:19: warning - @linkXMLWriter is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\DocumentSource.java:105: warning - @linkDocument is an unknown tag.
  Building index for all classes...
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataAttribute.java:25: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataElement.java:26: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\DocumentSource.java:28: warning - @linkDocument is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\OutputFormat.java:19: warning - @linkXMLWriter is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataAttribute.java:25: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataElement.java:26: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\Element.java:29: warning - @link#getDocument is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\Element.java:29: warning - @link#getDocument is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\bean\BeanAttribute.java:53: warning - Tag @link: reference not found: Node#getText()
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\bean\BeanAttribute.java:57: warning - Tag @link: reference not found: Node#setText(String)
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\datatype\DatatypeAttribute.java:146: warning - Tag @link: reference not found: Node#getText()
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\datatype\DatatypeAttribute.java:150: warning - Tag @link: reference not found: Node#setText(String)
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\DocumentSource.java:28: warning - @linkDocument is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\DocumentSource.java:28: warning - @linkDocument is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\DocumentSource.java:105: warning - @linkDocument is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\DocumentSource.java:105: warning - @linkDocument is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\DocumentSource.java:105: warning - @linkDocument is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\DOMWriter.java:95: warning - @linkorg.w3c.dom.Document is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\HTMLWriter.java:181: warning - Tag @link: missing #: "OutputFormat.isXHTML() OutputFormat.isXHTML()"
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\HTMLWriter.java:181: warning - Tag @link: can't find OutputFormat.isXHTML() in org.dom4j.io.HTMLWriter
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\HTMLWriter.java:181: warning - Tag @link: missing #: "OutputFormat.isXHTML() OutputFormat.isXHTML()"
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\HTMLWriter.java:181: warning - Tag @link: can't find OutputFormat.isXHTML() in org.dom4j.io.HTMLWriter
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\HTMLWriter.java:181: warning - @link#setPreformattedTags(java.util.Set) is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\HTMLWriter.java:181: warning - Tag @link: missing #: "OutputFormat.isXHTML() OutputFormat.isXHTML()"
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\HTMLWriter.java:181: warning - Tag @link: can't find OutputFormat.isXHTML() in org.dom4j.io.HTMLWriter
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\HTMLWriter.java:181: warning - @link#setPreformattedTags(java.util.Set) is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\OutputFormat.java:19: warning - @linkXMLWriter is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\OutputFormat.java:19: warning - @linkXMLWriter is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\SAXModifier.java:117: warning - @linkElementModifier is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\SAXModifier.java:117: warning - @linkElementModifier is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\SAXModifier.java:261: warning - @linkElementModifier is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\SAXModifier.java:261: warning - @linkElementModifier is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\SAXModifier.java:284: warning - @linkElementModifier is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\SAXModifier.java:284: warning - @linkElementModifier is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\STAXEventReader.java:298: warning - @linkStartElement is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\STAXEventReader.java:353: warning - @linkAttribute is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\STAXEventReader.java:380: warning - @linkNamespace is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\STAXEventReader.java:407: warning - @linkCharacters is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\STAXEventReader.java:434: warning - @linkComment is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\STAXEventReader.java:461: warning - @linkEntityReference is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\STAXEventWriter.java:169: warning - @link#writeElement(Element) is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\io\STAXEventWriter.java:169: warning - @link#writeElement(Element) is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\jaxb\JAXBReader.java:39: warning - @linkorg.dom4j.ElementHandler is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\jaxb\JAXBReader.java:39: warning - @linkorg.dom4j.ElementHandler is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\tree\FlyweightEntity.java:33: warning - @link#setText is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\tree\FlyweightEntity.java:33: warning - @link#setText is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataAttribute.java:25: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataAttribute.java:25: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataAttribute.java:37: warning - Tag @link: reference not found: Node#getText()
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataAttribute.java:41: warning - Tag @link: reference not found: Node#setText(String)
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataElement.java:26: warning - @link#getData is an unknown tag.
  C:\Projects\dom4j_1.x_branch\dom4j\src\java\org\dom4j\util\UserDataElement.java:26: warning - @link#getData is an unknown tag.
  Generating C:\Projects\dom4j_1.x_branch\dom4j\target\docs\apidocs\help-doc.html...
  70 warnings

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/developer-activity-report.html0000644000175000017500000001306710242117730021036 0ustar ebourgebourgdom4j - Developer Activity Analysis
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
    • Change Log
    • Changes
    • Checkstyle
    • Clover
    • Developer Activity
    • FAQs
    • File Activity
    • JavaDocs
    • JavaDoc Report
    • JavaDoc Warnings Report
    • Metrics
    • Unit Tests
    • Source Xref
    • Test Xref
    • Project License
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Activity by Developer

Timeframe: 30 days, Total Commits: 11 Total Number of Files Changed: 25

NameNumber of CommitsNumber of files changed
Maarten Coene 1125

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/checkstyle.rss0000644000175000017500000000412310242117613015700 0ustar ebourgebourg Checkstyle report http://dom4j.org Checkstyle report en-us Copyright 2004 The Apache Software Foundation File: 165 , Errors: 0 , Warnings: 7 , Infos: 0 http://dom4j.org/checkstyle-report.html

Click herefor the full Checkstyle report.

Files I W E
org/dom4j/InvalidXPathException.java 0 4 0
org/dom4j/util/PerThreadSingleton.java 0 1 0
org/dom4j/util/SimpleSingleton.java 0 1 0
org/dom4j/xpath/DefaultXPath.java 0 1 0
dom4j-1.6.1/docs/goals.html0000644000175000017500000001507610242117653015021 0ustar ebourgebourgdom4j - Design Goals
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Easy to use

We think that an XML framework for Java should be simple, easy to use and intuitive for a Java programmer. We want to take the best features from DOM and SAX and put them together into a new unified API which is optimised the for the Java platform.

Standards compliant

We want to fully support DOM and SAX together with existing Java platform standards such as the Java 2 Collections and J2EE.

Complete XPath integration

We want complete XPath support integrated into the API and for it to be very easy to use. XPath is the ideal technology for navigating around XML documents simply and easily without writing lines and lines of code.

Flexible implementations

We want to be able to support very flexible, performant and memory efficient implementations of XML documents. So we want the API to be based on Java interfaces just like the Java 2 Collections framework.

Just as no single List implementation will suffice (the JDK comes with at least 3) we believe we need a framework allowing plug and play XML document implementations. For some users, using a LinkedList performs better than an ArrayList because their usage characteristics differ. Others like to use a Vector as it is synchronized. We believe an XML model should have the same flexibility.

Handle very large documents

One of the primary goals of dom4j is to be a flexible XML framework for Java which supports most users needs whether that be fast and efficient parsing with small memory overhead, processing very large documents or using the latest XML features such as XPath, XSLT and XML Query.

We found that we often needed to move from DOM to SAX to handle very large documents or to move from SAX to DOM to handle complex documents. Our aim is for dom4j to be the only framework you really need on the Java platform and for it to be a good citizen supporting and integrating with existing standards fully.


2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/faq.html0000644000175000017500000007460310242117613014460 0ustar ebourgebourgdom4j - Frequently Asked Questions
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
    • Change Log
    • Changes
    • Checkstyle
    • Clover
    • Developer Activity
    • FAQs
    • File Activity
    • JavaDocs
    • JavaDoc Report
    • JavaDoc Warnings Report
    • Metrics
    • Unit Tests
    • Source Xref
    • Test Xref
    • Project License
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Frequently Asked Questions

General

  1. What is dom4j?
  2. What is the dom4j license?
  3. What do I need to add to my CLASSPATH?
  4. How does dom4j relate to DOM?
  5. How does dom4j relate to JDOM?
  6. How does dom4j work with DOM and SAX?

Using dom4j

  1. How can I use XSLT with dom4j?
  2. How can I pretty print my XML document?
  3. How can I parse a document from a String?
  4. How do I compare 2 nodes for equality?
  5. How does dom4j handle very large XML documents?
  6. Does dom4j support the Visitor Pattern?
  7. Can I sort the List returned by Node.selectNodes()?
  8. What features are optional in dom4j?
  9. What does the following mean 'Warning: Error occurred using JAXP to load a SAXParser. Will use Aelfred instead'
  10. What XML parser does dom4j use?
  11. How can I validate my document?
  12. How do I import dom4j into VAJ?
  13. Cannot find DTD; how can I tell dom4j where to find the DTD from a DOCTYPE?

General

General
What is dom4j?

dom4j is an Open Source XML framework for Java. dom4j allows you to read, write, navigate, create and modify XML documents. dom4j integrates with DOM and SAX and is seamlessly integrated with full XPath support.

What is the dom4j license?

We use an Apache-style open source license which is one of the least restrictive licenses around, you can use dom4j to create new products without them having to be open source.

You can find a copy of the license here.

What do I need to add to my CLASSPATH?

The dom4j.jar only contains the dom4j classes. If you want to use a SAX parser, you'll have to include the SAX classes and the SAX parser of your choice to your CLASSPATH. If you want to use XPath expressions, you also have to include the jaxen.jar to your CLASSPATH.

dom4j can use your existing XML parser and/or DOM implementation (such as Crimson or Xerces if you want it to. dom4j can also use JAXP to configure which SAX Parser to use - just add the jaxp.jar to your CLASSPATH and whichever SAX parser you wish away you go.

How does dom4j relate to DOM?

DOM is a quite large language independent API. dom4j is a simpler, lightweight API making extensive use of standard Java APIs such as the Java 2 collections API.

Remark that dom4j fully supports the DOM standard allowing both APIs to be used easily together.

How does dom4j relate to JDOM?

dom4j is a different project and different API to JDOM though they both have similar goals. They both attempt to make it easier to use XML on the Java platform. They differ in their design, API and implementation.

dom4j is based on Java interfaces so that plug and play document object model implementations are allowed and encouraged such as small, read only, quick to create implementations or bigger, highly indexed fast to naviagte implementations or implementations which read themselves lazily from a database or Java Beans etc.

dom4j uses polymorphism extensively such that all document object types implement the Node interface. Also both the Element and Document interfaces can be used polymorphically as they both extend the Branch interface.

dom4j is fully integrated with XPath support throughout the API so doing XPath expressions is as easy as

SAXReader reader = new SAXReader();
Document document = reader.read( url );
List links = document.selectNodes( "//a[@href]" );
String title = document.valueOf( "/head/title" );

dom4j will soon provide a configuration option to support the W3C DOM API natively to avoid unnecessary tree duplication when using dom4j with XSLT engines etc.

How does dom4j work with DOM and SAX?

You can create dom4j documents from XML text, SAX events or existing DOM trees or you can write dom4j documents as SAX events, DOM trees or XML text.

Using dom4j

Using dom4j
How can I use XSLT with dom4j?

dom4j integrates with XSLT using the JAXP standard (TrAX) APIs. A dom4j Document can be used as the source of XML to be styled or the source of the stylesheet. A dom4j Document can also be used as the result of a transformation.

First you'll need to use JAXP to load a Transformer.

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import org.dom4j.Document;
import org.dom4j.DocumentResult;
import org.dom4j.DocumentSource;
...

TransformerFactory factory 
  = TransformerFactory.newInstance();

Transformer transformer 
  = factory.newTransformer( new StreamSource( "foo.xsl" ) );

Now that you have a transformer its easy to style a Document into a new Document.

DocumentSource source = new DocumentSource( document );
DocumentResult result = new DocumentResult();
transformer.transform( source, result );

Document transformedDoc = result.getDocument();

If you want to transform a Document into XML text you can use JAXP as follows:-

DocumentSource source = new DocumentSource( document );
DocumentResult result = new StreamResult( new FileReader( "output.xml" ) );
transformer.transform( source, result );

For more information on JAXP and (TrAX) try Sun's JAXP site.

How can I pretty print my XML document?

You can control the format of the XML text output by XMLWriter by using the OutputFormat object. You can explicitly set the various formatting options via the properties methods of the OutputFormat object. There is also a helper method OutputFormat.createPrettyPrint() which creates the default pretty-print format.

So to pretty print some XML (trimming all whitespace and indenting nicely) the following code should do the job...

    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter( out, format );
    writer.write( document );
    writer.close();
How can I parse a document from a String?

Sometimes you have a String (or StringBuffer) which contains the XML to be parsed. This can be parsed using SAXReader and the StringReader from the JDK. For example:-

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

public class Foo {

    public Document getDocument() throws DocumentException {
        return DocumentHelper.parseText( 
            "<root> <child id='1'>James</child> </root>"
        );
    }
}
      
How do I compare 2 nodes for equality?

dom4j by default uses identity based equality for performance. It avoids having to walk entire documents or document fragments when putting nodes in collections.

To compare 2 nodes (attributes, elements, documents etc) for equality the NodeComparator can be used.

    Node node1 = ...;
    Node node2 = ...;
    NodeComparator comparator = new NodeComparator();
    if ( comparator.compare( node1, node2 ) == 0 ) {
        // nodes are equal!
    }

If you are having problems comparing documents that you think are equal but the NodeComparator decides that they are different, you might find the following useful.

In dom4j/test/src/org/dom4j/AbstractTestCase.java is-a JUnit TestCase and is an abstract base class for dom4j test cases. It contains a whole bunch of useful assertion helper methods for testing documents, nodes and fragments being equal. The nice thing is that you get useful messages telling you exactly why they are different, so its pretty easy to track down. For example.

    
public MyTest extends AbstractTestCase {
    ...
    public void testSomething() {
        Document doc1 = ...;
        Document doc2 = ...;

        assertDocumentsEqual( doc1, doc2 );
        ...

        assertNodesEqual( doc1.getRootElement(), doc2.getRootElement() );
    }
}
How does dom4j handle very large XML documents?

dom4j provides an event based model for processing XML documents. Using this event based model allows developers to prune the XML tree when parts of the document have been successfully processed avoiding having to keep the entire document in memory.

For example, imagine you need to process a very large XML file that is generated externally by some database process and looks something like the following (where N is a very large number).

<ROWSET>
    <ROW id="1">
        ...
    </ROW>
    <ROW id="2">
        ...
    </ROW>
    ...
    <ROW id="N">
        ...
    </ROW>
</ROWSET>     
      

We can process each <ROW> at a time, there is no need to keep all of them in memory at once. dom4j provides a Event Based Mode for this purpose. We can register an event handler for one or more path expressions. These handlers will then be called on the start and end of each path registered against a particular handler. When the start tag of a path is found, the onStart method of the handler registered to the path is called. When the end tag of a path if found, the onEnd method of the handler registered to that path is called.

The onStart and onEnd methods are passed an instance of an ElementPath, which can be used to retrieve the current Element for the given path. If the handler wishes to "prune" the tree being built in order to save memory use, it can simply call the detach() method of the current Element being processed in the handlers onEnd() method.

So to process each <ROW> individually we can do the following.

// enable pruning mode to call me back as each ROW is complete
SAXReader reader = new SAXReader();
reader.addHandler( "/ROWSET/ROW", 
    new ElementHandler() {
        public void onStart(ElementPath path) {
            // do nothing here...    
        }
        public void onEnd(ElementPath path) {
            // process a ROW element
            Element row = path.getCurrent();
            Element rowSet = row.getParent();
            Document document = row.getDocument();
            ...
            // prune the tree
            row.detach();
        }
    }
);

Document document = reader.read(url);

// The document will now be complete but all the ROW elements
// will have been pruned.
// We may want to do some final processing now
...
      
Does dom4j support the Visitor Pattern?

Yes. dom4j supports the visitor pattern via the Visitor interface.

Here is an example.

protected void foo(Document doc) {
  
    // lets use the Visitor Pattern to 
    // navigate the document for entities

    Visitor visitor = new VisitorSupport() {
        public void visit(Entity entity) {
            System.out.println( 
                "Entity name: " + entity.getName() 
                + " text: " + entity.getText() 
            );
        }
    };

    doc.accept( visitor );
}
      
Can I sort the List returned by Node.selectNodes()?

Yes. The selectNodes() is a really useful feature to allow nodes to be selected from any object in the dom4j object model via an XPath expression. The List that is returned can be sorted by specifying another XPath expression to use as the sorting comparator.

For example the following code parses an XML play and finds all the SPEAKER elements sorted in name order.

SAXReader reader = new SAXReader();
Document document = reader.read( new File( "xml/much_ado.xml" ) );
List speakers = document.selectNodes( "//SPEAKER", "." );
      

In the above example the name of the SPEAKER is defined by the XPath expression "." as the name is stored in the text of the SPEAKER element. If the name was defined by an attribute called "name" then the XPath expression "@name" should be used for sorting.

You may wish to remove duplicates while sorting such that (for example) the distinct list of SPEAKER elements is returned, sorted by name. To do this add an extra parameter to the selectNodes() method call.

List distinctSpeakers = document.selectNodes( "//SPEAKER", ".", true );
      
What features are optional in dom4j?

In dom4j being able to navigate up a tree towards the parent and to be able to change a tree are optional features. These features are optional so that an implementation can create memory efficient read only document models which conserve memory by sharing imutable objects (such as interning Atttributes).

There are some helper methods to determine if optional features are implemented. Here is some example code demonstrating their use.

protected void foo(Node node) {
  
    // can we do upward navigation?
    if ( ! node.supportsParent() ) {
        throw new UnsupportedOperationException(
          "Cannot navigate upwards to parent"
        );
    }
    Element parent = node.getParent();

    System.out.println( "Node: " + node 
        + " has parent: " + parent 
    );

    if ( parent != null ) {

        // can I modify the parent?
        if ( parent.isReadOnly() ) {
            throw new UnsupportedOperationException(
              "Cannot modify parent as it is read only"
            );
        }

        parent.setAttributeValue( "bar", "modified" );
    }
}
      
What does the following mean 'Warning: Error occurred using JAXP to load a SAXParser. Will use Aelfred instead'

If dom4j detects JAXP on the classpath it tries to use it to load a SAX parser. If it can't load the SAX parser via JAXP it then tries to use the org.xml.sax.driver system property to denote the SAX parser to use. If none of the above work dom4j outputs a warning and continues, using its own internal Aelfred2 parser instead.

The following warning is a result of JAXP being in the classpath but either an old JAXP1.0 version was found (rather than JAXP 1.1) or there is no JAXP configured parser (such as crimson.jar or xerces.jar) on the classpath.

Warning: Error occurred using JAXP to load a SAXParser. Will use Aelfred instead

So the warning generally indicates an incomplete JAXP classpath and is nothing to worry excessively about. If you'd like to see the full verbose reason why the load of a JAXP parser failed then you can try setting the system property org.dom4j.verbose=true. e.g.

java -Dorg.dom4j.verbose=true MyApp

And you should see a verbose list of why the load of a SAX parser via JAXP failed.

To avoid this warning happening either remove the jaxp.jar from your classpath or add a JAXP 1.1. jaxp.jar together with a JAXP 1.1 parser such as crimson.jar or xerces.jar to your classpath.

What XML parser does dom4j use?

dom4j works with any SAX parser via JAXP. So putting a recent distribution of crimson.jar or xerces.jar on the CLASSPATH will allow Crimson or Xerces's parser to be used.

If no SAX parser is on the classpath via JAXP or the SAX org.xml.sax.driver system property then the embedded Aelfred distribution will be used instead. Note that the embedded Aelfred distribution is a non validating parser, though it is quite fast

How can I validate my document?

If a recent version of crimson.jar or xerces.jar is on the CLASSPATH then dom4j will use that as the SAX parser via JAXP. If none of these are on the CLASSPATH then a bundled version of Aelfred is used, which does not validate.

So to perform DTD validation when parsing put crimson.jar or xerces.jar on the CLASSPATH. If you wish to validate against an XML Schema then try xerces.jar. Then use the following code.

// turn validation on
SAXReader reader = new SAXReader(true);
Document document = reader.read( "foo.xml" );

Note: if you want to validate against an XML Schema with xerces, you need to enable the XML Schema validation with the "setFeature" method. For more information about xerces features visit the xerces website. Below is a code sample to enable XML Schema validation.

// turn validation on
SAXReader reader = new SAXReader(true);
// request XML Schema validation
reader.setFeature("http://apache.org/xml/features/validation/schema", true);
Document document = reader.read( "foo.xml" );

An alternative approach is to use Sun's MSV library for validation, which allows you to use DTD, XML Schema, Relax NG, Relax or TREX as the schema languages. There's an example in the daily build at dom4j/src/samples/validate/JARVDemo.java

If you are validating an existing dom4j document then we recommend you try MSV as it avoids turning the document into text and then parsing it again - MSV can work purely off of SAX events generated from the dom4j document.

Using this approach your code will actually be based on the JARV API which allows alternative validation mechanisms to be plugged into your code.

How do I import dom4j into VAJ?

VisualAge for Java checks all dependencies in a JAR and displays warnings if there are any unresolved links. To avoid any warnings the following steps should be followed (thanks to Jan Haluza for this).

  1. Uninstall all the packages having anything in common with the xml (com.ibm.xml* , org.w3c.dom ..) (these packages contains older definitions DOM ver. 1 ...
  2. Install the following jars
    dom4j.jar
    xalan.jar
    PullParser.jar  
    relaxng.jar
    msv.jar
    isorelax.jar
    xsdlib.jar
    crimson.jar
    
Cannot find DTD; how can I tell dom4j where to find the DTD from a DOCTYPE?

A common way around this is to implement a SAX EntityResolver to load the DTD from somewhere else. e.g. you could include the DTD in your JAR with your java code and load it from there.

EntityResolver resolver = new EntityResolver() {
    public InputSource resolveEntity(String publicId, String systemId) {
        if ( publicId.equals( "-//Acme//DTD Foo 1.2//EN" ) ) {
            InputStream in = getClass().getResourceAsStream(
                "com/acme/foo.dtd"
            );
            return new InputSource( in );
        }
        return null;
    }
};

SAXReader reader = new SAXReader();
reader.setEntityResolver( resolver );
Document doc = reader.parse( "foo.xml" );

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/jdepend-report.html0000644000175000017500000022125110242117700016621 0ustar ebourgebourgdom4j - JDepend Source Code Analysis
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
    • Change Log
    • Changes
    • Checkstyle
    • Clover
    • Developer Activity
    • FAQs
    • File Activity
    • JavaDocs
    • JavaDoc Report
    • JavaDoc Warnings Report
    • Metrics
    • Unit Tests
    • Source Xref
    • Test Xref
    • Project License
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Metric Results

[ summary] [ packages] [ cycles] [ explanations]

The following document contains the results of a JDependmetric analysis. The various metrics are defined at the bottom of this document.

Summary

[ summary] [ packages] [ cycles] [ explanations]

Package TC AC CC AC EC A I D
org.dom4j 2618812100,6945%15%
org.dom4j.bean 505080100%0%
org.dom4j.datatype 7070110100%0%
org.dom4j.dom 1501517088%12%
org.dom4j.dtd 40411050%50%
org.dom4j.io 361354210,0384%13%
org.dom4j.jaxb 10370110,3100%30%
org.dom4j.rule 927560,2255%23%
org.dom4j.rule.pattern 20213075%25%
org.dom4j.swing 808070100%0%
org.dom4j.tree 491336790,2756%17%
org.dom4j.util 14212380,1473%13%
org.dom4j.xpath 40419090%10%
org.dom4j.xpp 10115083%17%

Packages

[ summary] [ packages] [ cycles] [ explanations]

org.dom4j

Afferent CouplingsEfferent CouplingsAbstractnessInstabilityDistance
121069%45%15%
Abstract ClassesConcrete ClassesUsed by PackagesUses Packages
  • Attribute
  • Branch
  • CDATA
  • CharacterData
  • Comment
  • Document
  • DocumentType
  • Element
  • ElementHandler
  • ElementPath
  • Entity
  • Node
  • NodeFilter
  • ProcessingInstruction
  • Text
  • Visitor
  • VisitorSupport
  • XPath
  • DocumentException
  • DocumentFactory
  • DocumentHelper
  • IllegalAddException
  • InvalidXPathException
  • Namespace
  • QName
  • XPathException
  • org.dom4j.bean
  • org.dom4j.datatype
  • org.dom4j.dom
  • org.dom4j.io
  • org.dom4j.jaxb
  • org.dom4j.rule
  • org.dom4j.rule.pattern
  • org.dom4j.swing
  • org.dom4j.tree
  • org.dom4j.util
  • org.dom4j.xpath
  • org.dom4j.xpp
  • java.io
  • java.lang
  • java.util
  • org.dom4j.io
  • org.dom4j.rule
  • org.dom4j.tree
  • org.dom4j.util
  • org.dom4j.xpath
  • org.jaxen
  • org.xml.sax

org.dom4j.bean

Afferent CouplingsEfferent CouplingsAbstractnessInstabilityDistance
080%100%0%
Abstract ClassesConcrete ClassesUsed by PackagesUses Packages
None
  • BeanAttribute
  • BeanAttributeList
  • BeanDocumentFactory
  • BeanElement
  • BeanMetaData
None
  • java.beans
  • java.io
  • java.lang
  • java.lang.reflect
  • java.util
  • org.dom4j
  • org.dom4j.tree
  • org.xml.sax

org.dom4j.datatype

Afferent CouplingsEfferent CouplingsAbstractnessInstabilityDistance
0110%100%0%
Abstract ClassesConcrete ClassesUsed by PackagesUses Packages
None
  • DatatypeAttribute
  • DatatypeDocumentFactory
  • DatatypeElement
  • DatatypeElementFactory
  • InvalidSchemaException
  • NamedTypeResolver
  • SchemaParser
None
  • com.sun.msv.datatype
  • com.sun.msv.datatype.xsd
  • java.io
  • java.lang
  • java.util
  • org.dom4j
  • org.dom4j.io
  • org.dom4j.tree
  • org.dom4j.util
  • org.relaxng.datatype
  • org.xml.sax

org.dom4j.dom

Afferent CouplingsEfferent CouplingsAbstractnessInstabilityDistance
170%88%12%
Abstract ClassesConcrete ClassesUsed by PackagesUses Packages
None
  • DOMAttribute
  • DOMAttributeNodeMap
  • DOMCDATA
  • DOMComment
  • DOMDocument
  • DOMDocumentFactory
  • DOMDocumentType
  • DOMElement
  • DOMEntityReference
  • DOMNamespace
  • DOMNodeHelper
  • DOMNodeHelper$1
  • DOMNodeHelper$EmptyNodeList
  • DOMProcessingInstruction
  • DOMText
  • org.dom4j.jaxb
  • java.io
  • java.lang
  • java.util
  • org.dom4j
  • org.dom4j.tree
  • org.dom4j.util
  • org.w3c.dom

org.dom4j.dtd

Afferent CouplingsEfferent CouplingsAbstractnessInstabilityDistance
110%50%50%
Abstract ClassesConcrete ClassesUsed by PackagesUses Packages
None
  • AttributeDecl
  • ElementDecl
  • ExternalEntityDecl
  • InternalEntityDecl
  • org.dom4j.io
  • java.lang

org.dom4j.io

Afferent CouplingsEfferent CouplingsAbstractnessInstabilityDistance
4213%84%13%
Abstract ClassesConcrete ClassesUsed by PackagesUses Packages
  • ElementModifier
  • DOMReader
  • DOMWriter
  • DispatchHandler
  • DocumentInputSource
  • DocumentInputSource$1
  • DocumentResult
  • DocumentSource
  • ElementStack
  • HTMLWriter
  • HTMLWriter$FormatState
  • JAXPHelper
  • OutputFormat
  • PruningDispatchHandler
  • PruningElementStack
  • SAXContentHandler
  • SAXEventRecorder
  • SAXEventRecorder$SAXEvent
  • SAXHelper
  • SAXModifier
  • SAXModifyContentHandler
  • SAXModifyElementHandler
  • SAXModifyException
  • SAXModifyReader
  • SAXReader
  • SAXReader$SAXEntityResolver
  • SAXValidator
  • SAXWriter
  • STAXEventReader
  • STAXEventWriter
  • STAXEventWriter$AttributeIterator
  • STAXEventWriter$NamespaceIterator
  • XMLResult
  • XMLWriter
  • XPP3Reader
  • XPPReader
  • org.dom4j
  • org.dom4j.datatype
  • org.dom4j.jaxb
  • org.dom4j.tree
  • java.io
  • java.lang
  • java.lang.reflect
  • java.net
  • java.util
  • javax.xml.namespace
  • javax.xml.parsers
  • javax.xml.stream
  • javax.xml.stream.events
  • javax.xml.stream.util
  • javax.xml.transform.sax
  • org.dom4j
  • org.dom4j.dtd
  • org.dom4j.tree
  • org.dom4j.xpp
  • org.gjt.xpp
  • org.w3c.dom
  • org.xml.sax
  • org.xml.sax.ext
  • org.xml.sax.helpers
  • org.xmlpull.v1

org.dom4j.jaxb

Afferent CouplingsEfferent CouplingsAbstractnessInstabilityDistance
01130%100%30%
Abstract ClassesConcrete ClassesUsed by PackagesUses Packages
  • JAXBObjectHandler
  • JAXBObjectModifier
  • JAXBSupport
  • JAXBModifier
  • JAXBModifier$JAXBElementModifier
  • JAXBReader
  • JAXBReader$PruningElementHandler
  • JAXBReader$UnmarshalElementHandler
  • JAXBRuntimeException
  • JAXBWriter
None
  • java.io
  • java.lang
  • java.net
  • java.nio.charset
  • java.util
  • javax.xml.bind
  • javax.xml.transform.stream
  • org.dom4j
  • org.dom4j.dom
  • org.dom4j.io
  • org.xml.sax

org.dom4j.rule

Afferent CouplingsEfferent CouplingsAbstractnessInstabilityDistance
5622%55%23%
Abstract ClassesConcrete ClassesUsed by PackagesUses Packages
  • Action
  • Pattern
  • Mode
  • NullAction
  • Rule
  • RuleManager
  • RuleManager$1
  • RuleSet
  • Stylesheet
  • org.dom4j
  • org.dom4j.rule.pattern
  • org.dom4j.tree
  • org.dom4j.util
  • org.dom4j.xpath
  • java.io
  • java.lang
  • java.util
  • org.dom4j
  • org.dom4j.rule.pattern
  • org.jaxen

org.dom4j.rule.pattern

Afferent CouplingsEfferent CouplingsAbstractnessInstabilityDistance
130%75%25%
Abstract ClassesConcrete ClassesUsed by PackagesUses Packages
None
  • DefaultPattern
  • NodeTypePattern
  • org.dom4j.rule
  • java.lang
  • org.dom4j
  • org.dom4j.rule

org.dom4j.swing

Afferent CouplingsEfferent CouplingsAbstractnessInstabilityDistance
070%100%0%
Abstract ClassesConcrete ClassesUsed by PackagesUses Packages
None
  • BranchTreeNode
  • BranchTreeNode$1
  • DocumentTreeModel
  • LeafTreeNode
  • LeafTreeNode$1
  • XMLTableColumnDefinition
  • XMLTableDefinition
  • XMLTableModel
None
  • java.io
  • java.lang
  • java.util
  • javax.swing.table
  • javax.swing.tree
  • org.dom4j
  • org.jaxen

org.dom4j.tree

Afferent CouplingsEfferent CouplingsAbstractnessInstabilityDistance
7927%56%17%
Abstract ClassesConcrete ClassesUsed by PackagesUses Packages
  • AbstractAttribute
  • AbstractBranch
  • AbstractCDATA
  • AbstractCharacterData
  • AbstractComment
  • AbstractDocument
  • AbstractDocumentType
  • AbstractElement
  • AbstractEntity
  • AbstractNode
  • AbstractProcessingInstruction
  • AbstractText
  • FilterIterator
  • BackedList
  • BaseElement
  • ConcurrentReaderHashMap
  • ConcurrentReaderHashMap$1
  • ConcurrentReaderHashMap$BarrierLock
  • ConcurrentReaderHashMap$Entry
  • ConcurrentReaderHashMap$EntrySet
  • ConcurrentReaderHashMap$HashIterator
  • ConcurrentReaderHashMap$KeyIterator
  • ConcurrentReaderHashMap$KeySet
  • ConcurrentReaderHashMap$ValueIterator
  • ConcurrentReaderHashMap$Values
  • ContentListFacade
  • DefaultAttribute
  • DefaultCDATA
  • DefaultComment
  • DefaultDocument
  • DefaultDocumentType
  • DefaultElement
  • DefaultEntity
  • DefaultNamespace
  • DefaultProcessingInstruction
  • DefaultText
  • ElementIterator
  • ElementNameIterator
  • ElementQNameIterator
  • FlyweightAttribute
  • FlyweightCDATA
  • FlyweightComment
  • FlyweightEntity
  • FlyweightProcessingInstruction
  • FlyweightText
  • NamespaceCache
  • NamespaceStack
  • QNameCache
  • SingleIterator
  • org.dom4j
  • org.dom4j.bean
  • org.dom4j.datatype
  • org.dom4j.dom
  • org.dom4j.io
  • org.dom4j.util
  • org.dom4j.xpp
  • java.io
  • java.lang
  • java.lang.ref
  • java.lang.reflect
  • java.util
  • org.dom4j
  • org.dom4j.io
  • org.dom4j.rule
  • org.xml.sax

org.dom4j.util

Afferent CouplingsEfferent CouplingsAbstractnessInstabilityDistance
3814%73%13%
Abstract ClassesConcrete ClassesUsed by PackagesUses Packages
  • ProxyDocumentFactory
  • SingletonStrategy
  • AttributeHelper
  • IndexedDocumentFactory
  • IndexedElement
  • NodeComparator
  • NonLazyDocumentFactory
  • NonLazyElement
  • PerThreadSingleton
  • SimpleSingleton
  • UserDataAttribute
  • UserDataDocumentFactory
  • UserDataElement
  • XMLErrorHandler
  • org.dom4j
  • org.dom4j.datatype
  • org.dom4j.dom
  • java.lang
  • java.lang.ref
  • java.util
  • org.dom4j
  • org.dom4j.rule
  • org.dom4j.tree
  • org.jaxen
  • org.xml.sax

org.dom4j.xpath

Afferent CouplingsEfferent CouplingsAbstractnessInstabilityDistance
190%90%10%
Abstract ClassesConcrete ClassesUsed by PackagesUses Packages
None
  • DefaultNamespaceContext
  • DefaultXPath
  • DefaultXPath$1
  • XPathPattern
  • org.dom4j
  • java.io
  • java.lang
  • java.util
  • org.dom4j
  • org.dom4j.rule
  • org.jaxen
  • org.jaxen.dom4j
  • org.jaxen.pattern
  • org.jaxen.saxpath

org.dom4j.xpp

Afferent CouplingsEfferent CouplingsAbstractnessInstabilityDistance
150%83%17%
Abstract ClassesConcrete ClassesUsed by PackagesUses Packages
None
  • ProxyXmlStartTag
  • org.dom4j.io
  • java.lang
  • java.util
  • org.dom4j
  • org.dom4j.tree
  • org.gjt.xpp

Cycles

[ summary] [ packages] [ cycles] [ explanations]

PackageCyclic Dependencies
org.dom4j
  • org.dom4j.util
  • org.dom4j
org.dom4j.bean
  • org.dom4j
  • org.dom4j.util
  • org.dom4j
org.dom4j.datatype
  • org.dom4j
  • org.dom4j.util
  • org.dom4j
org.dom4j.dom
  • org.dom4j
  • org.dom4j.util
  • org.dom4j
org.dom4j.io
  • org.dom4j
  • org.dom4j.util
  • org.dom4j
org.dom4j.jaxb
  • org.dom4j
  • org.dom4j.util
  • org.dom4j
org.dom4j.rule
  • org.dom4j
  • org.dom4j.util
  • org.dom4j
org.dom4j.rule.pattern
  • org.dom4j
  • org.dom4j.util
  • org.dom4j
org.dom4j.swing
  • org.dom4j
  • org.dom4j.util
  • org.dom4j
org.dom4j.tree
  • org.dom4j
  • org.dom4j.util
  • org.dom4j
org.dom4j.util
  • org.dom4j
  • org.dom4j.util
org.dom4j.xpath
  • org.dom4j
  • org.dom4j.util
  • org.dom4j
org.dom4j.xpp
  • org.dom4j
  • org.dom4j.util
  • org.dom4j

Explanations

[ summary] [ packages] [ cycles] [ explanations]

The following explanations are for quick reference and are lifted directly from the original JDepend documentation.

TermDescription
Number of ClassesThe number of concrete and abstract classes (and interfaces) in the package is an indicator of the extensibility of the package.
Afferent CouplingsThe number of other packages that depend upon classes within the package is an indicator of the package's responsibility.
Efferent CouplingsThe number of other packages that the classes in the package depend upon is an indicator of the package's independence.
AbstractnessThe ratio of the number of abstract classes (and interfaces) in the analyzed package to the total number of classes in the analyzed package. The range for this metric is 0 to 1, with A=0 indicating a completely concrete package and A=1 indicating a completely abstract package.
InstabilityThe ratio of efferent coupling (Ce) to total coupling (Ce / (Ce + Ca)). This metric is an indicator of the package's resilience to change. The range for this metric is 0 to 1, with I=0 indicating a completely stable package and I=1 indicating a completely instable package.
DistanceThe perpendicular distance of a package from the idealized line A + I = 1. This metric is an indicator of the package's balance between abstractness and stability. A package squarely on the main sequence is optimally balanced with respect to its abstractness and stability. Ideal packages are either completely abstract and stable (x=0, y=1) or completely concrete and instable (x=1, y=0). The range for this metric is 0 to 1, with D=0 indicating a package that is coincident with the main sequence and D=1 indicating a package that is as far from the main sequence as possible.
CyclesPackages participating in a package dependency cycle are in a deadly embrace with respect to reusability and their release cycle. Package dependency cycles can be easily identified by reviewing the textual reports of dependency cycles. Once these dependency cycles have been identified with JDepend, they can be broken by employing various object-oriented techniques.

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/compare.html0000644000175000017500000001627610242117705015343 0ustar ebourgebourgdom4j - XML Object Model Comparisons
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Comparison

This page attempts to survey the landscape of available XML object models and compare and contrast their features. The information in this table is correct to the best of our knowledge and we will try and keep this information as up to date as possible. If you think there's anything wrong, please let us know here.

FeatureWC3 DOMDOM4J 1.5JDOM 1.0XOM 1.O
Open SourceYesYesYesYes
Based on Java InterfacesYesYesNoNo
Supports Java 2 CollectionsNoYesYesNo
Can use any SAX parser and XMLFilterYes (usually)YesYesYes
Convert to and from DOM treesYesYesYesYes
Implements DOM interfacesYesYes (optional)NoNo
Integrated XPath API supportNoYesNoNo
Bundled XPath implementationNoYesOptionalNo
Support for JAXP/TrAX for XSLT integrationYesYesYesYes
Capable of processing a continuous XML streamsDon't knowYesNoYes
Capable of processing massive documentsDon't knowYesNoYes
XML Schema Data Type supportNoYesNoDon't know
XInclude supportDon't knowNoNoYes
Canonical XML supportDon't knowNoNoYes

Performance

Dennis Sosnoski has published an interesting article on IBM's developerWorks which compares the performance of a variety of XML document models for the Java platform including dom4j. You can find the very interesting results here.

Also you might find these new Performance Benchmarks interesting comparing dom4j and Jaxen against Xerces and Xalan.


2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/clover/0000755000175000017500000000000012133227266014312 5ustar ebourgebourgdom4j-1.6.1/docs/clover/style.css0000644000175000017500000001053110242117631016155 0ustar ebourgebourgBODY { FONT-FAMILY: verdana, arial, sans-serif; background-color: #ffffff; } TABLE { FONT-SIZE: 9px } .navBar { Font-weight: normal; Font-size: 12px; } TD.itemList { Font-weight: normal; Font-size: 12px; FONT-FAMILY: arial, sans-serif } DIV.navBar { padding-top:4px; } DIV.navBarLink { Font-weight: normal; Font-size: 10px; padding-top:4px; } FONT.navBarCurrent { padding: 2px; font-weight: bold; color: #FFFFFF; background-color:#00008B; } TD.reportHeader { BACKGROUND: #eff7ff; PADDING: 5px; FONT-WEIGHT: bold; FONT-SIZE: 12px; BORDER: #dcdcdc 1px solid;} .titleText { FONT-WEIGHT: bold; FONT-SIZE: 12px; } TD.titleText { BACKGROUND: #eff7ff; PADDING-left: 5px; } TD.headerStats { BORDER-LEFT: #dcdcdc 1px solid; } TD.chart { padding: 4px; BORDER: #dcdcdc 1px solid; } TD.chartHeader { padding: 4px; BORDER: #dcdcdc 1px solid; BACKGROUND: #eff7ff; FONT-WEIGHT: bold; FONT-SIZE: 12px; } SPAN.subtitle { FONT-SIZE: 9px; font-weight: normal; } TD.graphHeaderLeft { BACKGROUND: #eff7ff; BORDER: #dcdcdc 1px solid; } TD.graphHeader { BACKGROUND: #eff7ff; BORDER-BOTTOM: #dcdcdc 1px solid; BORDER-TOP: #dcdcdc 1px solid;BORDER-RIGHT: #dcdcdc 1px solid; } TD.graphItem { BACKGROUND: #ffffff; BORDER-BOTTOM: #dcdcdc 1px solid; BORDER-LEFT: #dcdcdc 1px solid; BORDER-RIGHT: #dcdcdc 1px solid; PADDING-LEFT: 15px; PADDING-RIGHT: 15px; FONT-WEIGHT: bold; FONT-SIZE: 12px; } TD.graphPercent { BACKGROUND: #ffffff; BORDER-BOTTOM: #dcdcdc 1px solid; BORDER-RIGHT: #dcdcdc 1px solid; } TD.graphBarLeft { BACKGROUND: #ffffff; BORDER-BOTTOM: #dcdcdc 1px solid; } TD.graphBar { BACKGROUND: #ffffff; BORDER-BOTTOM: #dcdcdc 1px solid; BORDER-RIGHT: #dcdcdc 1px solid; WIDTH: 50%; } TD.hspacer { BORDER-BOTTOM:#dcdcdc 1px solid; BORDER-TOP:#dcdcdc 1px solid; } TD.mover { BORDER:#dcdcdc 1px solid; } TABLE.barGraph { WIDTH: 100%; } TD.empty { FONT-SIZE: 2px; BACKGROUND: #c0c0c0; BORDER:#9c9c9c 1px solid; } TD.fullcover { FONT-SIZE: 2px; BACKGROUND: #00df00; BORDER:#9c9c9c 1px solid; } TD.covered { FONT-SIZE: 2px; BACKGROUND: #00df00; BORDER-LEFT:#9c9c9c 1px solid;BORDER-TOP:#9c9c9c 1px solid;BORDER-BOTTOM:#9c9c9c 1px solid; } TD.uncovered { FONT-SIZE: 2px; BACKGROUND: #df0000; BORDER:#9c9c9c 1px solid; } TD.tabText { PADDING-RIGHT: 12px; } DIV.timestamp { FONT-SIZE: 9px; font-weight: normal; padding-left: 1px; } SPAN.srcFile { FONT-SIZE: 9px } TABLE.srcView { FONT-SIZE: 12px; BORDER-LEFT:#dcdcdc 1px solid;BORDER-RIGHT:#dcdcdc 1px solid; BORDER-BOTTOM:#dcdcdc 1px solid; } TD.lineCount { BACKGROUND: #F0F0F0; BORDER-RIGHT:#dcdcdc 1px solid; PADDING-RIGHT: 3px; } TD.lineCountHilight { BACKGROUND: #C8C8F0; BORDER-RIGHT:#dcdcdc 1px solid; PADDING-RIGHT: 3px; } SPAN.Hilight { BACKGROUND: #C8C8F0; } TD.coverageCount { BACKGROUND: #F0F0F0; BORDER-RIGHT:#dcdcdc 1px solid; PADDING-RIGHT: 3px; } TD.coverageCountHilight { BACKGROUND: #F0C8C8; BORDER-RIGHT:#dcdcdc 1px solid; PADDING-RIGHT: 3px; } TD.srcLineClassStart { WIDTH: 100%; BORDER-TOP:#dcdcdc 1px solid; FONT-WEIGHT: bold; } .srcCell { background: #ffffff; padding-right: 10px; margin-top: 0px; margin-bottom: 0px; font-family: Courier New, Monospace; } .srcLine { display: inline; white-space: pre; padding-left: 10px; } .srcLineHilight { background: #F0C8C8; display: inline; white-space: pre; padding-left: 10px; } TD.lineWarning { BACKGROUND: #FFFFA0; BORDER-RIGHT:#dcdcdc 1px solid; PADDING-RIGHT: 3px; } .keyword { color: #2020BF; } .string { color: #BC8F8F; } .javadoc { color: #6060FF; font-style: normal; } .comment { color: #B22222; font-style: italic; } .warning { border: solid 1px #000000; color: #000000; margin-top: 10px; margin-bottom: 10px; font-family: verdana, arial, sans-serif; font-size: 12pt; width: 80%; } .warning .title { background-color: #ffff60; padding: 5px; font-weight: bold; text-align: left; } .warning .message { background-color: #ffffe0; color: #000000; padding-left: 30px; padding-top: 10px; padding-bottom: 10px; padding-right: 30px; text-align: left; } TD.footer { BORDER-TOP:#dcdcdc 1px solid; FONT-SIZE: 9px } dom4j-1.6.1/docs/clover/pkgs-summary.html0000644000175000017500000003601210242117702017631 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
project stats: LOC: 42.863   Methods: 2.481
NCLOC: 17.854   Classes: 183
Files: 166   Packages: 14
 
  Conditionals Statements Methods TOTAL
Project 43,8% 47,1% 41% 45,2%
coverage coverage
 
 Packages Conditionals Statements Methods TOTAL
org.dom4j.jaxb 0% 0% 0% 0%
coverage
org.dom4j.xpp 0% 0% 0% 0%
coverage
org.dom4j.dom 11,1% 13,7% 11,6% 12,7%
coverage coverage
org.dom4j.util 29,3% 34,4% 26,9% 31,8%
coverage coverage
org.dom4j.swing 39,5% 40,2% 34,4% 38,4%
coverage coverage
org.dom4j.rule.pattern - 41,7% 41,7% 41,7%
coverage coverage
org.dom4j.io 46,3% 47,8% 44,3% 46,9%
coverage coverage
org.dom4j.bean 42,9% 52% 41,4% 48%
coverage coverage
org.dom4j.rule 41,3% 52,7% 59,2% 50,4%
coverage coverage
org.dom4j.tree 47% 54,6% 54,7% 52,6%
coverage coverage
org.dom4j.datatype 58,3% 65,7% 69,6% 64,5%
coverage coverage
org.dom4j.xpath 60% 67,7% 72,7% 67,1%
coverage coverage
org.dom4j 69,6% 72,1% 61,7% 69%
coverage coverage
org.dom4j.dtd 83,3% 79,6% 56,8% 74,8%
coverage coverage
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/all-pkgs.html0000644000175000017500000000557410242117635016722 0ustar ebourgebourg dom4j - 1.6.1 dom4j - 1.6.1
Clover coverage report

Overview
All Classes

All Packages
org.dom4j (69%)
org.dom4j.bean (48%)
org.dom4j.datatype (64,5%)
org.dom4j.dom (12,7%)
org.dom4j.dtd (74,8%)
org.dom4j.io (46,9%)
org.dom4j.jaxb (0%)
org.dom4j.rule (50,4%)
org.dom4j.rule.pattern (41,7%)
org.dom4j.swing (38,4%)
org.dom4j.tree (52,6%)
org.dom4j.util (31,8%)
org.dom4j.xpath (67,1%)
org.dom4j.xpp (0%)
dom4j-1.6.1/docs/clover/img/0000755000175000017500000000000012133227266015066 5ustar ebourgebourgdom4j-1.6.1/docs/clover/img/logo.gif0000644000175000017500000000132510242117701016505 0ustar ebourgebourgGIF89a n^{CliбR)w?(Nֱrt%bʎPNk8ҕnHrĝ~}}fW9!b1P2z\׽s=Ć{fͫRs JWT㣦݅lF+•lX/ʵޥ<3vOB\Uf3xD_\̙ۙtsC9yBPȤu,bZ)^1iƋ죶tkB޽se6ϔ{#~o L/Uq?^\TCw)!!v,((Q^(+^Bd 23::ffB B66dQJi!hh J(jeeaAg& bamI4͒z4QB-f8CȋD ;dom4j-1.6.1/docs/clover/img/trans.gif0000644000175000017500000000005310242117755016702 0ustar ebourgebourgGIF89a!,L;dom4j-1.6.1/docs/clover/index.html0000644000175000017500000000142410242117741016303 0ustar ebourgebourg dom4j - 1.6.1 This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. <BR> Link to <A HREF="pkgs-summary.html">Non-frame version.</A> dom4j-1.6.1/docs/clover/org/0000755000175000017500000000000010242117543015074 5ustar ebourgebourgdom4j-1.6.1/docs/clover/org/dom4j/0000755000175000017500000000000012133227266016116 5ustar ebourgebourgdom4j-1.6.1/docs/clover/org/dom4j/pkg-classes.html0000644000175000017500000000373410242117740021221 0ustar ebourgebourg dom4j - 1.6.1 org.dom4j
Classes
DocumentException (7,7%)
DocumentFactory (80,9%)
DocumentHelper (72,6%)
IllegalAddException (66,7%)
InvalidXPathException (33,3%)
Namespace (84,9%)
QName (73,4%)
VisitorSupport (0%)
XPathException (27,3%)
dom4j-1.6.1/docs/clover/org/dom4j/ElementPath.html0000644000175000017500000007337510242117750021224 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 111   Methods: 0
NCLOC: 9   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
ElementPath.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    /**
 11    * This interface is used by {@link ElementHandler}instances to retrieve
 12    * information about the current path hierarchy they are to process. It's
 13    * primary use is to retrieve the current {@link Element}being processed.
 14    *
 15    * @author <a href="mailto:dwhite@equipecom.com">Dave White </a>
 16    * @version $Revision: 1.6 $
 17    */
 18    public interface ElementPath {
 19    /**
 20    * DOCUMENT ME!
 21    *
 22    * @return the number of elements in the path
 23    */
 24    int size();
 25   
 26    /**
 27    * DOCUMENT ME!
 28    *
 29    * @param depth
 30    * DOCUMENT ME!
 31    *
 32    * @return the element at the specified depth index, 0 = root element
 33    */
 34    Element getElement(int depth);
 35   
 36    /**
 37    * DOCUMENT ME!
 38    *
 39    * @return the path as a string
 40    */
 41    String getPath();
 42   
 43    /**
 44    * DOCUMENT ME!
 45    *
 46    * @return the current element
 47    */
 48    Element getCurrent();
 49   
 50    /**
 51    * Adds the <code>ElementHandler</code> to be called when the specified
 52    * path is encounted. The path can be either an absolute path (i.e. prefixed
 53    * with "/") or a relative path (i.e. assummed to be a child of the current
 54    * path as retrieved by <b>getPath </b>.
 55    *
 56    * @param path
 57    * is the path to be handled
 58    * @param handler
 59    * is the <code>ElementHandler</code> to be called by the event
 60    * based processor.
 61    */
 62    void addHandler(String path, ElementHandler handler);
 63   
 64    /**
 65    * Removes the <code>ElementHandler</code> from the event based processor,
 66    * for the specified path. The path can be either an absolute path (i.e.
 67    * prefixed with "/") or a relative path (i.e. assummed to be a child of the
 68    * current path as retrieved by <b>getPath </b>.
 69    *
 70    * @param path
 71    * is the path to remove the <code>ElementHandler</code> for.
 72    */
 73    void removeHandler(String path);
 74    }
 75   
 76    /*
 77    * Redistribution and use of this software and associated documentation
 78    * ("Software"), with or without modification, are permitted provided that the
 79    * following conditions are met:
 80    *
 81    * 1. Redistributions of source code must retain copyright statements and
 82    * notices. Redistributions must also contain a copy of this document.
 83    *
 84    * 2. Redistributions in binary form must reproduce the above copyright notice,
 85    * this list of conditions and the following disclaimer in the documentation
 86    * and/or other materials provided with the distribution.
 87    *
 88    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 89    * from this Software without prior written permission of MetaStuff, Ltd. For
 90    * written permission, please contact dom4j-info@metastuff.com.
 91    *
 92    * 4. Products derived from this Software may not be called "DOM4J" nor may
 93    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 94    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 95    *
 96    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 97    *
 98    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 99    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 100    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 101    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 102    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 103    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 104    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 105    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 106    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 107    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 108    * POSSIBILITY OF SUCH DAMAGE.
 109    *
 110    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 111    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/bean/0000755000175000017500000000000012133227266017023 5ustar ebourgebourgdom4j-1.6.1/docs/clover/org/dom4j/bean/pkg-classes.html0000644000175000017500000000261710242117606022126 0ustar ebourgebourg dom4j - 1.6.1 org.dom4j.bean
Classes
BeanAttribute (27,8%)
BeanAttributeList (31,9%)
BeanDocumentFactory (28,1%)
BeanElement (63,3%)
BeanMetaData (66,7%)
dom4j-1.6.1/docs/clover/org/dom4j/bean/pkg-summary.html0000644000175000017500000002021710242117741022162 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
package stats: LOC: 814   Methods: 58
NCLOC: 363   Classes: 5
Files: 5  
 
 Package Conditionals Statements Methods TOTAL
org.dom4j.bean 42,9% 52% 41,4% 48%
coverage coverage
 
 Classes Conditionals Statements Methods TOTAL
BeanAttribute 0% 33,3% 28,6% 27,8%
coverage coverage
BeanDocumentFactory 16,7% 26,3% 42,9% 28,1%
coverage coverage
BeanAttributeList 25% 35,7% 27,8% 31,9%
coverage coverage
BeanElement 70% 64,7% 56,2% 63,3%
coverage coverage
BeanMetaData 58,3% 72,7% 50% 66,7%
coverage coverage
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/bean/BeanElement.html0000644000175000017500000015227210242117546022077 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 194   Methods: 16
NCLOC: 93   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
BeanElement.java 70% 64,7% 56,2% 63,3%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.bean;
 9   
 10    import java.util.List;
 11   
 12    import org.dom4j.Attribute;
 13    import org.dom4j.DocumentFactory;
 14    import org.dom4j.Element;
 15    import org.dom4j.Namespace;
 16    import org.dom4j.QName;
 17    import org.dom4j.tree.DefaultElement;
 18    import org.dom4j.tree.NamespaceStack;
 19   
 20    import org.xml.sax.Attributes;
 21   
 22    /**
 23    * <p>
 24    * <code>BeanElement</code> uses a Java Bean to store its attributes.
 25    * </p>
 26    *
 27    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 28    * @version $Revision: 1.15 $
 29    */
 30    public class BeanElement extends DefaultElement {
 31    /** The <code>DocumentFactory</code> instance used by default */
 32    private static final DocumentFactory DOCUMENT_FACTORY = BeanDocumentFactory
 33    .getInstance();
 34   
 35    /** The JavaBean which defines my attributes */
 36    private Object bean;
 37   
 38  0 public BeanElement(String name, Object bean) {
 39  0 this(DOCUMENT_FACTORY.createQName(name), bean);
 40    }
 41   
 42  0 public BeanElement(String name, Namespace namespace, Object bean) {
 43  0 this(DOCUMENT_FACTORY.createQName(name, namespace), bean);
 44    }
 45   
 46  0 public BeanElement(QName qname, Object bean) {
 47  0 super(qname);
 48  0 this.bean = bean;
 49    }
 50   
 51  3 public BeanElement(QName qname) {
 52  3 super(qname);
 53    }
 54   
 55    /**
 56    * DOCUMENT ME!
 57    *
 58    * @return the JavaBean associated with this element
 59    */
 60  4 public Object getData() {
 61  4 return bean;
 62    }
 63   
 64  2 public void setData(Object data) {
 65  2 this.bean = data;
 66   
 67    // force the attributeList to be lazily
 68    // created next time an attribute related
 69    // method is called again.
 70  2 setAttributeList(null);
 71    }
 72   
 73  2 public Attribute attribute(String name) {
 74  2 return getBeanAttributeList().attribute(name);
 75    }
 76   
 77  0 public Attribute attribute(QName qname) {
 78  0 return getBeanAttributeList().attribute(qname);
 79    }
 80   
 81  2 public Element addAttribute(String name, String value) {
 82  2 Attribute attribute = attribute(name);
 83   
 84  2 if (attribute != null) {
 85  2 attribute.setValue(value);
 86    }
 87   
 88  2 return this;
 89    }
 90   
 91  0 public Element addAttribute(QName qName, String value) {
 92  0 Attribute attribute = attribute(qName);
 93   
 94  0 if (attribute != null) {
 95  0 attribute.setValue(value);
 96    }
 97   
 98  0 return this;
 99    }
 100   
 101  0 public void setAttributes(List attributes) {
 102  0 throw new UnsupportedOperationException("Not implemented yet.");
 103    }
 104   
 105    // Method overridden from AbstractElement
 106  3 public void setAttributes(Attributes attributes,
 107    NamespaceStack namespaceStack, boolean noNamespaceAttributes) {
 108  3 String className = attributes.getValue("class");
 109   
 110  3 if (className != null) {
 111  2 try {
 112  2 Class beanClass = Class.forName(className, true,
 113    BeanElement.class.getClassLoader());
 114  2 this.setData(beanClass.newInstance());
 115   
 116  2 for (int i = 0; i < attributes.getLength(); i++) {
 117  4 String attributeName = attributes.getLocalName(i);
 118   
 119  4 if (!"class".equalsIgnoreCase(attributeName)) {
 120  2 addAttribute(attributeName, attributes.getValue(i));
 121    }
 122    }
 123    } catch (Exception ex) {
 124    // What to do here?
 125  0 ((BeanDocumentFactory) this.getDocumentFactory())
 126    .handleException(ex);
 127    }
 128    } else {
 129  1 super.setAttributes(attributes, namespaceStack,
 130    noNamespaceAttributes);
 131    }
 132    }
 133   
 134    // Implementation methods
 135    // -------------------------------------------------------------------------
 136  5 protected DocumentFactory getDocumentFactory() {
 137  5 return DOCUMENT_FACTORY;
 138    }
 139   
 140  2 protected BeanAttributeList getBeanAttributeList() {
 141  2 return (BeanAttributeList) attributeList();
 142    }
 143   
 144    /**
 145    * A Factory Method pattern which lazily creates a List implementation used
 146    * to store content
 147    *
 148    * @return DOCUMENT ME!
 149    */
 150  2 protected List createAttributeList() {
 151  2 return new BeanAttributeList(this);
 152    }
 153   
 154  0 protected List createAttributeList(int size) {
 155  0 return new BeanAttributeList(this);
 156    }
 157    }
 158   
 159    /*
 160    * Redistribution and use of this software and associated documentation
 161    * ("Software"), with or without modification, are permitted provided that the
 162    * following conditions are met:
 163    *
 164    * 1. Redistributions of source code must retain copyright statements and
 165    * notices. Redistributions must also contain a copy of this document.
 166    *
 167    * 2. Redistributions in binary form must reproduce the above copyright notice,
 168    * this list of conditions and the following disclaimer in the documentation
 169    * and/or other materials provided with the distribution.
 170    *
 171    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 172    * from this Software without prior written permission of MetaStuff, Ltd. For
 173    * written permission, please contact dom4j-info@metastuff.com.
 174    *
 175    * 4. Products derived from this Software may not be called "DOM4J" nor may
 176    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 177    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 178    *
 179    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 180    *
 181    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 182    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 183    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 184    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 185    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 186    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 187    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 188    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 189    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 190    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 191    * POSSIBILITY OF SUCH DAMAGE.
 192    *
 193    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 194    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/bean/BeanMetaData.html0000644000175000017500000015764110242117754022174 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 204   Methods: 10
NCLOC: 96   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
BeanMetaData.java 58,3% 72,7% 50% 66,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.bean;
 9   
 10    import java.beans.BeanInfo;
 11    import java.beans.IntrospectionException;
 12    import java.beans.Introspector;
 13    import java.beans.PropertyDescriptor;
 14    import java.lang.reflect.Method;
 15    import java.util.HashMap;
 16    import java.util.Map;
 17   
 18    import org.dom4j.DocumentFactory;
 19    import org.dom4j.QName;
 20   
 21    /**
 22    * <p>
 23    * <code>BeanMetaData</code> contains metadata about a bean class.
 24    * </p>
 25    *
 26    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 27    * @version $Revision: 1.10 $
 28    */
 29    public class BeanMetaData {
 30    /** Empty arguments for reflection calls */
 31    protected static final Object[] NULL_ARGS = {};
 32   
 33    /** Singleton cache */
 34    private static Map singletonCache = new HashMap();
 35   
 36    private static final DocumentFactory DOCUMENT_FACTORY = BeanDocumentFactory
 37    .getInstance();
 38   
 39    /** The class of the bean */
 40    private Class beanClass;
 41   
 42    /** Property descriptors for the bean */
 43    private PropertyDescriptor[] propertyDescriptors;
 44   
 45    /** QNames for the attributes */
 46    private QName[] qNames;
 47   
 48    /** Read methods used for getting properties */
 49    private Method[] readMethods;
 50   
 51    /** Write methods used for setting properties */
 52    private Method[] writeMethods;
 53   
 54    /** Index of names and QNames to indices */
 55    private Map nameMap = new HashMap();
 56   
 57  1 public BeanMetaData(Class beanClass) {
 58  1 this.beanClass = beanClass;
 59   
 60  1 if (beanClass != null) {
 61  1 try {
 62  1 BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
 63  1 propertyDescriptors = beanInfo.getPropertyDescriptors();
 64    } catch (IntrospectionException e) {
 65  0 handleException(e);
 66    }
 67    }
 68   
 69  1 if (propertyDescriptors == null) {
 70  0 propertyDescriptors = new PropertyDescriptor[0];
 71    }
 72   
 73  1 int size = propertyDescriptors.length;
 74  1 qNames = new QName[size];
 75  1 readMethods = new Method[size];
 76  1 writeMethods = new Method[size];
 77   
 78  1 for (int i = 0; i < size; i++) {
 79  59 PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
 80  59 String name = propertyDescriptor.getName();
 81  59 QName qName = DOCUMENT_FACTORY.createQName(name);
 82  59 qNames[i] = qName;
 83  59 readMethods[i] = propertyDescriptor.getReadMethod();
 84  59 writeMethods[i] = propertyDescriptor.getWriteMethod();
 85   
 86  59 Integer index = new Integer(i);
 87  59 nameMap.put(name, index);
 88  59 nameMap.put(qName, index);
 89    }
 90    }
 91   
 92    /**
 93    * Static helper method to find and cache meta data objects for bean types
 94    *
 95    * @param beanClass
 96    * DOCUMENT ME!
 97    *
 98    * @return DOCUMENT ME!
 99    */
 100  2 public static BeanMetaData get(Class beanClass) {
 101  2 BeanMetaData answer = (BeanMetaData) singletonCache.get(beanClass);
 102   
 103  2 if (answer == null) {
 104  1 answer = new BeanMetaData(beanClass);
 105  1 singletonCache.put(beanClass, answer);
 106    }
 107   
 108  2 return answer;
 109    }
 110   
 111    /**
 112    * DOCUMENT ME!
 113    *
 114    * @return the number of attribtutes for this bean type
 115    */
 116  2 public int attributeCount() {
 117  2 return propertyDescriptors.length;
 118    }
 119   
 120  0 public BeanAttributeList createAttributeList(BeanElement parent) {
 121  0 return new BeanAttributeList(parent, this);
 122    }
 123   
 124  0 public QName getQName(int index) {
 125  0 return qNames[index];
 126    }
 127   
 128  2 public int getIndex(String name) {
 129  2 Integer index = (Integer) nameMap.get(name);
 130   
 131  2 return (index != null) ? index.intValue() : (-1);
 132    }
 133   
 134  0 public int getIndex(QName qName) {
 135  0 Integer index = (Integer) nameMap.get(qName);
 136   
 137  0 return (index != null) ? index.intValue() : (-1);
 138    }
 139   
 140  0 public Object getData(int index, Object bean) {
 141  0 try {
 142  0 Method method = readMethods[index];
 143   
 144  0 return method.invoke(bean, NULL_ARGS);
 145    } catch (Exception e) {
 146  0 handleException(e);
 147   
 148  0 return null;
 149    }
 150    }
 151   
 152  2 public void setData(int index, Object bean, Object data) {
 153  2 try {
 154  2 Method method = writeMethods[index];
 155  2 Object[] args = {data};
 156  2 method.invoke(bean, args);
 157    } catch (Exception e) {
 158  0 handleException(e);
 159    }
 160    }
 161   
 162    // Implementation methods
 163    // -------------------------------------------------------------------------
 164  0 protected void handleException(Exception e) {
 165    // ignore introspection exceptions
 166    }
 167    }
 168   
 169    /*
 170    * Redistribution and use of this software and associated documentation
 171    * ("Software"), with or without modification, are permitted provided that the
 172    * following conditions are met:
 173    *
 174    * 1. Redistributions of source code must retain copyright statements and
 175    * notices. Redistributions must also contain a copy of this document.
 176    *
 177    * 2. Redistributions in binary form must reproduce the above copyright notice,
 178    * this list of conditions and the following disclaimer in the documentation
 179    * and/or other materials provided with the distribution.
 180    *
 181    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 182    * from this Software without prior written permission of MetaStuff, Ltd. For
 183    * written permission, please contact dom4j-info@metastuff.com.
 184    *
 185    * 4. Products derived from this Software may not be called "DOM4J" nor may
 186    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 187    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 188    *
 189    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 190    *
 191    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 192    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 193    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 194    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 195    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 196    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 197    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 198    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 199    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 200    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 201    * POSSIBILITY OF SUCH DAMAGE.
 202    *
 203    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 204    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/bean/BeanDocumentFactory.html0000644000175000017500000011307410242117637023612 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 134   Methods: 7
NCLOC: 51   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
BeanDocumentFactory.java 16,7% 26,3% 42,9% 28,1%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.bean;
 9   
 10    import org.dom4j.Attribute;
 11    import org.dom4j.DocumentFactory;
 12    import org.dom4j.Element;
 13    import org.dom4j.QName;
 14    import org.dom4j.tree.DefaultAttribute;
 15   
 16    import org.xml.sax.Attributes;
 17   
 18    /**
 19    * <p>
 20    * <code>BeanDocumentFactory</code> is a factory of DOM4J objects which may be
 21    * BeanElements which are backed by JavaBeans and their properties.
 22    * </p>
 23    *
 24    * <p>
 25    * The tree built allows full XPath expressions from anywhere on the tree.
 26    * </p>
 27    *
 28    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 29    * @version $Revision: 1.14 $
 30    */
 31    public class BeanDocumentFactory extends DocumentFactory {
 32    /** The Singleton instance */
 33    private static BeanDocumentFactory singleton = new BeanDocumentFactory();
 34   
 35    /**
 36    * <p>
 37    * Access to the singleton instance of this factory.
 38    * </p>
 39    *
 40    * @return the default singleon instance
 41    */
 42  3 public static DocumentFactory getInstance() {
 43  3 return singleton;
 44    }
 45   
 46    // Factory methods
 47  3 public Element createElement(QName qname) {
 48  3 Object bean = createBean(qname);
 49   
 50  3 if (bean == null) {
 51  3 return new BeanElement(qname);
 52    } else {
 53  0 return new BeanElement(qname, bean);
 54    }
 55    }
 56   
 57  0 public Element createElement(QName qname, Attributes attributes) {
 58  0 Object bean = createBean(qname, attributes);
 59   
 60  0 if (bean == null) {
 61  0 return new BeanElement(qname);
 62    } else {
 63  0 return new BeanElement(qname, bean);
 64    }
 65    }
 66   
 67  0 public Attribute createAttribute(Element owner, QName qname, String value) {
 68  0 return new DefaultAttribute(qname, value);
 69    }
 70   
 71    // Implementation methods
 72  3 protected Object createBean(QName qname) {
 73  3 return null;
 74    }
 75   
 76  0 protected Object createBean(QName qname, Attributes attributes) {
 77  0 String value = attributes.getValue("class");
 78   
 79  0 if (value != null) {
 80  0 try {
 81  0 Class beanClass = Class.forName(value, true,
 82    BeanDocumentFactory.class.getClassLoader());
 83   
 84  0 return beanClass.newInstance();
 85    } catch (Exception e) {
 86  0 handleException(e);
 87    }
 88    }
 89   
 90  0 return null;
 91    }
 92   
 93  0 protected void handleException(Exception e) {
 94    // ignore introspection exceptions
 95  0 System.out.println("#### Warning: couldn't create bean: " + e);
 96    }
 97    }
 98   
 99    /*
 100    * Redistribution and use of this software and associated documentation
 101    * ("Software"), with or without modification, are permitted provided that the
 102    * following conditions are met:
 103    *
 104    * 1. Redistributions of source code must retain copyright statements and
 105    * notices. Redistributions must also contain a copy of this document.
 106    *
 107    * 2. Redistributions in binary form must reproduce the above copyright notice,
 108    * this list of conditions and the following disclaimer in the documentation
 109    * and/or other materials provided with the distribution.
 110    *
 111    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 112    * from this Software without prior written permission of MetaStuff, Ltd. For
 113    * written permission, please contact dom4j-info@metastuff.com.
 114    *
 115    * 4. Products derived from this Software may not be called "DOM4J" nor may
 116    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 117    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 118    *
 119    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 120    *
 121    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 122    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 123    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 124    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 125    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 126    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 127    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 128    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 129    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 130    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 131    * POSSIBILITY OF SUCH DAMAGE.
 132    *
 133    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 134    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/bean/BeanAttribute.html0000644000175000017500000006740710242117710022447 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 97   Methods: 7
NCLOC: 31   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
BeanAttribute.java 0% 33,3% 28,6% 27,8%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.bean;
 9   
 10    import org.dom4j.Element;
 11    import org.dom4j.QName;
 12    import org.dom4j.tree.AbstractAttribute;
 13   
 14    /**
 15    * <p>
 16    * <code>BeanAttribute</code> represents a mutable XML attribute which is
 17    * backed by a property of the JavaBean of its parent element.
 18    * </p>
 19    *
 20    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 21    * @version $Revision: 1.7 $
 22    */
 23    public class BeanAttribute extends AbstractAttribute {
 24    /** The list of Bean attributes */
 25    private final BeanAttributeList beanList;
 26   
 27    /** The index in the Bean attribute list */
 28    private final int index;
 29   
 30  2 public BeanAttribute(BeanAttributeList beanList, int index) {
 31  2 this.beanList = beanList;
 32  2 this.index = index;
 33    }
 34   
 35  0 public QName getQName() {
 36  0 return beanList.getQName(index);
 37    }
 38   
 39  0 public Element getParent() {
 40  0 return beanList.getParent();
 41    }
 42   
 43  0 public String getValue() {
 44  0 Object data = getData();
 45   
 46  0 return (data != null) ? data.toString() : null;
 47    }
 48   
 49  2 public void setValue(String data) {
 50  2 beanList.setData(index, data);
 51    }
 52   
 53  0 public Object getData() {
 54  0 return beanList.getData(index);
 55    }
 56   
 57  0 public void setData(Object data) {
 58  0 beanList.setData(index, data);
 59    }
 60    }
 61   
 62    /*
 63    * Redistribution and use of this software and associated documentation
 64    * ("Software"), with or without modification, are permitted provided that the
 65    * following conditions are met:
 66    *
 67    * 1. Redistributions of source code must retain copyright statements and
 68    * notices. Redistributions must also contain a copy of this document.
 69    *
 70    * 2. Redistributions in binary form must reproduce the above copyright notice,
 71    * this list of conditions and the following disclaimer in the documentation
 72    * and/or other materials provided with the distribution.
 73    *
 74    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 75    * from this Software without prior written permission of MetaStuff, Ltd. For
 76    * written permission, please contact dom4j-info@metastuff.com.
 77    *
 78    * 4. Products derived from this Software may not be called "DOM4J" nor may
 79    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 80    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 81    *
 82    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 83    *
 84    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 85    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 86    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 87    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 88    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 89    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 90    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 91    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 92    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 93    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 94    * POSSIBILITY OF SUCH DAMAGE.
 95    *
 96    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 97    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/bean/BeanAttributeList.html0000644000175000017500000015067410242117553023307 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 185   Methods: 18
NCLOC: 92   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
BeanAttributeList.java 25% 35,7% 27,8% 31,9%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.bean;
 9   
 10    import java.util.AbstractList;
 11   
 12    import org.dom4j.Attribute;
 13    import org.dom4j.QName;
 14   
 15    /**
 16    * <p>
 17    * <code>BeanAttributeList</code> implements a list of Attributes which are
 18    * the properties of a JavaBean.
 19    * </p>
 20    *
 21    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 22    * @version $Revision: 1.9 $
 23    */
 24    public class BeanAttributeList extends AbstractList {
 25    /** The BeanElement that this */
 26    private BeanElement parent;
 27   
 28    /** The BeanElement that this */
 29    private BeanMetaData beanMetaData;
 30   
 31    /** The attributes */
 32    private BeanAttribute[] attributes;
 33   
 34  0 public BeanAttributeList(BeanElement parent, BeanMetaData beanMetaData) {
 35  0 this.parent = parent;
 36  0 this.beanMetaData = beanMetaData;
 37  0 this.attributes = new BeanAttribute[beanMetaData.attributeCount()];
 38    }
 39   
 40  2 public BeanAttributeList(BeanElement parent) {
 41  2 this.parent = parent;
 42   
 43  2 Object data = parent.getData();
 44  2 Class beanClass = (data != null) ? data.getClass() : null;
 45  2 this.beanMetaData = BeanMetaData.get(beanClass);
 46  2 this.attributes = new BeanAttribute[beanMetaData.attributeCount()];
 47    }
 48   
 49  2 public Attribute attribute(String name) {
 50  2 int index = beanMetaData.getIndex(name);
 51   
 52  2 return attribute(index);
 53    }
 54   
 55  0 public Attribute attribute(QName qname) {
 56  0 int index = beanMetaData.getIndex(qname);
 57   
 58  0 return attribute(index);
 59    }
 60   
 61  2 public BeanAttribute attribute(int index) {
 62  2 if ((index >= 0) && (index <= attributes.length)) {
 63  2 BeanAttribute attribute = attributes[index];
 64   
 65  2 if (attribute == null) {
 66  2 attribute = createAttribute(parent, index);
 67  2 attributes[index] = attribute;
 68    }
 69   
 70  2 return attribute;
 71    }
 72   
 73  0 return null;
 74    }
 75   
 76  0 public BeanElement getParent() {
 77  0 return parent;
 78    }
 79   
 80  0 public QName getQName(int index) {
 81  0 return beanMetaData.getQName(index);
 82    }
 83   
 84  0 public Object getData(int index) {
 85  0 return beanMetaData.getData(index, parent.getData());
 86    }
 87   
 88  2 public void setData(int index, Object data) {
 89  2 beanMetaData.setData(index, parent.getData(), data);
 90    }
 91   
 92    // List interface
 93    // -------------------------------------------------------------------------
 94  0 public int size() {
 95  0 return attributes.length;
 96    }
 97   
 98  0 public Object get(int index) {
 99  0 BeanAttribute attribute = attributes[index];
 100   
 101  0 if (attribute == null) {
 102  0 attribute = createAttribute(parent, index);
 103  0 attributes[index] = attribute;
 104    }
 105   
 106  0 return attribute;
 107    }
 108   
 109  0 public boolean add(Object object) {
 110  0 throw new UnsupportedOperationException("add(Object) unsupported");
 111    }
 112   
 113  0 public void add(int index, Object object) {
 114  0 throw new UnsupportedOperationException("add(int,Object) unsupported");
 115    }
 116   
 117  0 public Object set(int index, Object object) {
 118  0 throw new UnsupportedOperationException("set(int,Object) unsupported");
 119    }
 120   
 121  0 public boolean remove(Object object) {
 122  0 return false;
 123    }
 124   
 125  0 public Object remove(int index) {
 126  0 BeanAttribute attribute = (BeanAttribute) get(index);
 127  0 Object oldValue = attribute.getValue();
 128  0 attribute.setValue(null);
 129   
 130  0 return oldValue;
 131    }
 132   
 133  0 public void clear() {
 134  0 for (int i = 0, size = attributes.length; i < size; i++) {
 135  0 BeanAttribute attribute = attributes[i];
 136   
 137  0 if (attribute != null) {
 138  0 attribute.setValue(null);
 139    }
 140    }
 141    }
 142   
 143    // Implementation methods
 144    // -------------------------------------------------------------------------
 145  2 protected BeanAttribute createAttribute(BeanElement element, int index) {
 146  2 return new BeanAttribute(this, index);
 147    }
 148    }
 149   
 150    /*
 151    * Redistribution and use of this software and associated documentation
 152    * ("Software"), with or without modification, are permitted provided that the
 153    * following conditions are met:
 154    *
 155    * 1. Redistributions of source code must retain copyright statements and
 156    * notices. Redistributions must also contain a copy of this document.
 157    *
 158    * 2. Redistributions in binary form must reproduce the above copyright notice,
 159    * this list of conditions and the following disclaimer in the documentation
 160    * and/or other materials provided with the distribution.
 161    *
 162    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 163    * from this Software without prior written permission of MetaStuff, Ltd. For
 164    * written permission, please contact dom4j-info@metastuff.com.
 165    *
 166    * 4. Products derived from this Software may not be called "DOM4J" nor may
 167    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 168    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 169    *
 170    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 171    *
 172    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 173    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 174    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 175    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 176    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 177    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 178    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 179    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 180    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 181    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 182    * POSSIBILITY OF SUCH DAMAGE.
 183    *
 184    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 185    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/QName.html0000644000175000017500000024233510242117572020013 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 295   Methods: 21
NCLOC: 154   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
QName.java 61,8% 76,8% 81% 73,4%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    import java.io.IOException;
 11    import java.io.ObjectInputStream;
 12    import java.io.ObjectOutputStream;
 13    import java.io.Serializable;
 14   
 15    import org.dom4j.tree.QNameCache;
 16    import org.dom4j.util.SingletonStrategy;
 17   
 18    /**
 19    * <p>
 20    * <code>QName</code> represents a qualified name value of an XML element or
 21    * attribute. It consists of a local name and a {@link Namespace}instance. This
 22    * object is immutable.
 23    * </p>
 24    *
 25    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 26    */
 27    public class QName implements Serializable {
 28    /** The Singleton instance */
 29    private static SingletonStrategy singleton = null;
 30   
 31    static {
 32  90 try {
 33  90 String defaultSingletonClass = "org.dom4j.util.SimpleSingleton";
 34  90 Class clazz = null;
 35  90 try {
 36  90 String singletonClass = defaultSingletonClass;
 37  90 singletonClass = System.getProperty(
 38    "org.dom4j.QName.singleton.strategy", singletonClass);
 39  90 clazz = Class.forName(singletonClass);
 40    } catch (Exception exc1) {
 41  0 try {
 42  0 String singletonClass = defaultSingletonClass;
 43  0 clazz = Class.forName(singletonClass);
 44    } catch (Exception exc2) {
 45    }
 46    }
 47  90 singleton = (SingletonStrategy) clazz.newInstance();
 48  90 singleton.setSingletonClassName(QNameCache.class.getName());
 49    } catch (Exception exc3) {
 50    }
 51    }
 52   
 53    /** The local name of the element or attribute */
 54    private String name;
 55   
 56    /** The qualified name of the element or attribute */
 57    private String qualifiedName;
 58   
 59    /** The Namespace of this element or attribute */
 60    private transient Namespace namespace;
 61   
 62    /** A cached version of the hashcode for efficiency */
 63    private int hashCode;
 64   
 65    /** The document factory used for this QName if specified or null */
 66    private DocumentFactory documentFactory;
 67   
 68  1065 public QName(String name) {
 69  1065 this(name, Namespace.NO_NAMESPACE);
 70    }
 71   
 72  2660 public QName(String name, Namespace namespace) {
 73  2660 this.name = (name == null) ? "" : name;
 74  2660 this.namespace = (namespace == null) ? Namespace.NO_NAMESPACE
 75    : namespace;
 76    }
 77   
 78  0 public QName(String name, Namespace namespace, String qualifiedName) {
 79  0 this.name = (name == null) ? "" : name;
 80  0 this.qualifiedName = qualifiedName;
 81  0 this.namespace = (namespace == null) ? Namespace.NO_NAMESPACE
 82    : namespace;
 83    }
 84   
 85  13995 public static QName get(String name) {
 86  13995 return getCache().get(name);
 87    }
 88   
 89  578 public static QName get(String name, Namespace namespace) {
 90  578 return getCache().get(name, namespace);
 91    }
 92   
 93  14057 public static QName get(String name, String prefix, String uri) {
 94  14057 if (((prefix == null) || (prefix.length() == 0)) && (uri == null)) {
 95  13994 return QName.get(name);
 96  63 } else if ((prefix == null) || (prefix.length() == 0)) {
 97  0 return getCache().get(name, Namespace.get(uri));
 98  63 } else if (uri == null) {
 99  0 return QName.get(name);
 100    } else {
 101  63 return getCache().get(name, Namespace.get(prefix, uri));
 102    }
 103    }
 104   
 105  0 public static QName get(String qualifiedName, String uri) {
 106  0 if (uri == null) {
 107  0 return getCache().get(qualifiedName);
 108    } else {
 109  0 return getCache().get(qualifiedName, uri);
 110    }
 111    }
 112   
 113  0 public static QName get(String localName, Namespace namespace,
 114    String qualifiedName) {
 115  0 return getCache().get(localName, namespace, qualifiedName);
 116    }
 117   
 118    /**
 119    * DOCUMENT ME!
 120    *
 121    * @return the local name
 122    */
 123  125131 public String getName() {
 124  125131 return name;
 125    }
 126   
 127    /**
 128    * DOCUMENT ME!
 129    *
 130    * @return the qualified name in the format <code>prefix:localName</code>
 131    */
 132  363324 public String getQualifiedName() {
 133  363324 if (qualifiedName == null) {
 134  559 String prefix = getNamespacePrefix();
 135   
 136  559 if ((prefix != null) && (prefix.length() > 0)) {
 137  78 qualifiedName = prefix + ":" + name;
 138    } else {
 139  481 qualifiedName = name;
 140    }
 141    }
 142   
 143  363324 return qualifiedName;
 144    }
 145   
 146    /**
 147    * DOCUMENT ME!
 148    *
 149    * @return the namespace of this QName
 150    */
 151  124797 public Namespace getNamespace() {
 152  124797 return namespace;
 153    }
 154   
 155    /**
 156    * DOCUMENT ME!
 157    *
 158    * @return the namespace URI of this QName
 159    */
 160  24364 public String getNamespacePrefix() {
 161  24364 if (namespace == null) {
 162  0 return "";
 163    }
 164   
 165  24364 return namespace.getPrefix();
 166    }
 167   
 168    /**
 169    * DOCUMENT ME!
 170    *
 171    * @return the namespace URI of this QName
 172    */
 173  328407 public String getNamespaceURI() {
 174  328407 if (namespace == null) {
 175  0 return "";
 176    }
 177   
 178  328407 return namespace.getURI();
 179    }
 180   
 181    /**
 182    * DOCUMENT ME!
 183    *
 184    * @return the hash code based on the qualified name and the URI of the
 185    * namespace.
 186    */
 187  67848 public int hashCode() {
 188  67848 if (hashCode == 0) {
 189  1117 hashCode = getName().hashCode() ^ getNamespaceURI().hashCode();
 190   
 191  1117 if (hashCode == 0) {
 192  0 hashCode = 0xbabe;
 193    }
 194    }
 195   
 196  67848 return hashCode;
 197    }
 198   
 199  48780 public boolean equals(Object object) {
 200  48780 if (this == object) {
 201  17036 return true;
 202  31744 } else if (object instanceof QName) {
 203  31685 QName that = (QName) object;
 204   
 205    // we cache hash codes so this should be quick
 206  31685 if (hashCode() == that.hashCode()) {
 207  6838 return getName().equals(that.getName())
 208    && getNamespaceURI().equals(that.getNamespaceURI());
 209    }
 210    }
 211   
 212  24906 return false;
 213    }
 214   
 215  0 public String toString() {
 216  0 return super.toString() + " [name: " + getName() + " namespace: \""
 217    + getNamespace() + "\"]";
 218    }
 219   
 220    /**
 221    * DOCUMENT ME!
 222    *
 223    * @return the factory that should be used for Elements of this QName
 224    */
 225  231609 public DocumentFactory getDocumentFactory() {
 226  231609 return documentFactory;
 227    }
 228   
 229  3065 public void setDocumentFactory(DocumentFactory documentFactory) {
 230  3065 this.documentFactory = documentFactory;
 231    }
 232   
 233  65 private void writeObject(ObjectOutputStream out) throws IOException {
 234    // We use writeObject() and not writeUTF() to minimize space
 235    // This allows for writing pointers to already written strings
 236  65 out.writeObject(namespace.getPrefix());
 237  65 out.writeObject(namespace.getURI());
 238   
 239  65 out.defaultWriteObject();
 240    }
 241   
 242  65 private void readObject(ObjectInputStream in) throws IOException,
 243    ClassNotFoundException {
 244  65 String prefix = (String) in.readObject();
 245  65 String uri = (String) in.readObject();
 246   
 247  65 in.defaultReadObject();
 248   
 249  65 namespace = Namespace.get(prefix, uri);
 250    }
 251   
 252  14636 private static QNameCache getCache() {
 253  14636 QNameCache cache = (QNameCache) singleton.instance();
 254  14636 return cache;
 255    }
 256    }
 257   
 258   
 259   
 260    /*
 261    * Redistribution and use of this software and associated documentation
 262    * ("Software"), with or without modification, are permitted provided that the
 263    * following conditions are met:
 264    *
 265    * 1. Redistributions of source code must retain copyright statements and
 266    * notices. Redistributions must also contain a copy of this document.
 267    *
 268    * 2. Redistributions in binary form must reproduce the above copyright notice,
 269    * this list of conditions and the following disclaimer in the documentation
 270    * and/or other materials provided with the distribution.
 271    *
 272    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 273    * from this Software without prior written permission of MetaStuff, Ltd. For
 274    * written permission, please contact dom4j-info@metastuff.com.
 275    *
 276    * 4. Products derived from this Software may not be called "DOM4J" nor may
 277    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 278    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 279    *
 280    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 281    *
 282    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 283    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 284    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 285    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 286    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 287    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 288    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 289    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 290    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 291    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 292    * POSSIBILITY OF SUCH DAMAGE.
 293    *
 294    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 295    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/DocumentException.html0000644000175000017500000010516610242117667022454 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 120   Methods: 9
NCLOC: 52   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DocumentException.java 0% 9,1% 11,1% 7,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    import java.io.PrintStream;
 11    import java.io.PrintWriter;
 12   
 13    /**
 14    * <p>
 15    * <code>DocumentException</code> is a nested Exception which may be thrown
 16    * during the processing of a DOM4J document.
 17    * </p>
 18    *
 19    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 20    * @version $Revision: 1.7 $
 21    */
 22    public class DocumentException extends Exception {
 23    /** A wrapped <code>Throwable</code> */
 24    private Throwable nestedException;
 25   
 26  0 public DocumentException() {
 27  0 super("Error occurred in DOM4J application.");
 28    }
 29   
 30  0 public DocumentException(String message) {
 31  0 super(message);
 32    }
 33   
 34  0 public DocumentException(Throwable nestedException) {
 35  0 super(nestedException.getMessage());
 36  0 this.nestedException = nestedException;
 37    }
 38   
 39  1 public DocumentException(String message, Throwable nestedException) {
 40  1 super(message);
 41  1 this.nestedException = nestedException;
 42    }
 43   
 44  0 public Throwable getNestedException() {
 45  0 return nestedException;
 46    }
 47   
 48  0 public String getMessage() {
 49  0 if (nestedException != null) {
 50  0 return super.getMessage() + " Nested exception: "
 51    + nestedException.getMessage();
 52    } else {
 53  0 return super.getMessage();
 54    }
 55    }
 56   
 57  0 public void printStackTrace() {
 58  0 super.printStackTrace();
 59   
 60  0 if (nestedException != null) {
 61  0 System.err.print("Nested exception: ");
 62  0 nestedException.printStackTrace();
 63    }
 64    }
 65   
 66  0 public void printStackTrace(PrintStream out) {
 67  0 super.printStackTrace(out);
 68   
 69  0 if (nestedException != null) {
 70  0 out.println("Nested exception: ");
 71  0 nestedException.printStackTrace(out);
 72    }
 73    }
 74   
 75  0 public void printStackTrace(PrintWriter writer) {
 76  0 super.printStackTrace(writer);
 77   
 78  0 if (nestedException != null) {
 79  0 writer.println("Nested exception: ");
 80  0 nestedException.printStackTrace(writer);
 81    }
 82    }
 83    }
 84   
 85    /*
 86    * Redistribution and use of this software and associated documentation
 87    * ("Software"), with or without modification, are permitted provided that the
 88    * following conditions are met:
 89    *
 90    * 1. Redistributions of source code must retain copyright statements and
 91    * notices. Redistributions must also contain a copy of this document.
 92    *
 93    * 2. Redistributions in binary form must reproduce the above copyright notice,
 94    * this list of conditions and the following disclaimer in the documentation
 95    * and/or other materials provided with the distribution.
 96    *
 97    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 98    * from this Software without prior written permission of MetaStuff, Ltd. For
 99    * written permission, please contact dom4j-info@metastuff.com.
 100    *
 101    * 4. Products derived from this Software may not be called "DOM4J" nor may
 102    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 103    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 104    *
 105    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 106    *
 107    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 108    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 109    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 110    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 111    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 112    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 113    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 114    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 115    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 116    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 117    * POSSIBILITY OF SUCH DAMAGE.
 118    *
 119    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 120    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/IllegalAddException.html0000644000175000017500000005252510242117742022652 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 71   Methods: 3
NCLOC: 16   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
IllegalAddException.java - 66,7% 66,7% 66,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    /**
 11    * <p>
 12    * <code>IllegalAddException</code> is thrown when a node is added incorrectly
 13    * to an <code>{@link Element}</code>
 14    * </p>
 15    *
 16    * @version $Revision: 1.6 $
 17    */
 18    public class IllegalAddException extends IllegalArgumentException {
 19  0 public IllegalAddException(String reason) {
 20  0 super(reason);
 21    }
 22   
 23  2 public IllegalAddException(Element parent, Node node, String reason) {
 24  2 super("The node \"" + node.toString()
 25    + "\" could not be added to the element \""
 26    + parent.getQualifiedName() + "\" because: " + reason);
 27    }
 28   
 29  1 public IllegalAddException(Branch parent, Node node, String reason) {
 30  1 super("The node \"" + node.toString()
 31    + "\" could not be added to the branch \"" + parent.getName()
 32    + "\" because: " + reason);
 33    }
 34    }
 35   
 36    /*
 37    * Redistribution and use of this software and associated documentation
 38    * ("Software"), with or without modification, are permitted provided that the
 39    * following conditions are met:
 40    *
 41    * 1. Redistributions of source code must retain copyright statements and
 42    * notices. Redistributions must also contain a copy of this document.
 43    *
 44    * 2. Redistributions in binary form must reproduce the above copyright notice,
 45    * this list of conditions and the following disclaimer in the documentation
 46    * and/or other materials provided with the distribution.
 47    *
 48    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 49    * from this Software without prior written permission of MetaStuff, Ltd. For
 50    * written permission, please contact dom4j-info@metastuff.com.
 51    *
 52    * 4. Products derived from this Software may not be called "DOM4J" nor may
 53    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 54    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 55    *
 56    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 57    *
 58    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 59    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 60    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 61    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 62    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 63    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 64    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 65    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 66    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 67    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 68    * POSSIBILITY OF SUCH DAMAGE.
 69    *
 70    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 71    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/NodeFilter.html0000644000175000017500000005043410242117705021040 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 70   Methods: 0
NCLOC: 4   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
NodeFilter.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    /**
 11    * <p>
 12    * <code>NodeFilter</code> defines the behavior for a filter or predicate
 13    * which acts on a DOM4J Node. Instances can be generated from an {@link
 14    * DocumentFactory}.
 15    * </p>
 16    *
 17    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 18    * @version $Revision: 1.7 $
 19    */
 20    public interface NodeFilter {
 21    /**
 22    * <p>
 23    * <code>matches</code> returns true if the given node matches the filter
 24    * condition.
 25    * </p>
 26    *
 27    * @param node
 28    * DOCUMENT ME!
 29    *
 30    * @return true if this filter matches the given node
 31    */
 32    boolean matches(Node node);
 33    }
 34   
 35    /*
 36    * Redistribution and use of this software and associated documentation
 37    * ("Software"), with or without modification, are permitted provided that the
 38    * following conditions are met:
 39    *
 40    * 1. Redistributions of source code must retain copyright statements and
 41    * notices. Redistributions must also contain a copy of this document.
 42    *
 43    * 2. Redistributions in binary form must reproduce the above copyright notice,
 44    * this list of conditions and the following disclaimer in the documentation
 45    * and/or other materials provided with the distribution.
 46    *
 47    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 48    * from this Software without prior written permission of MetaStuff, Ltd. For
 49    * written permission, please contact dom4j-info@metastuff.com.
 50    *
 51    * 4. Products derived from this Software may not be called "DOM4J" nor may
 52    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 53    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 54    *
 55    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 56    *
 57    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 58    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 59    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 60    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 61    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 62    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 63    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 64    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 65    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 66    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 67    * POSSIBILITY OF SUCH DAMAGE.
 68    *
 69    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 70    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/0000755000175000017500000000000012133227266017055 5ustar ebourgebourgdom4j-1.6.1/docs/clover/org/dom4j/tree/pkg-classes.html0000644000175000017500000001752510242117721022162 0ustar ebourgebourg dom4j - 1.6.1 org.dom4j.tree
Classes
AbstractAttribute (66,7%)
AbstractBranch (66,7%)
AbstractCDATA (89,5%)
AbstractCharacterData (23,1%)
AbstractComment (21,7%)
AbstractDocument (62,4%)
AbstractDocumentType (50%)
AbstractElement (45,9%)
AbstractEntity (12%)
AbstractNode (67,9%)
AbstractProcessingInstruction (49,5%)
AbstractText (63,6%)
BackedList (47,9%)
BaseElement (18,9%)
ConcurrentReaderHashMap (35%)
ConcurrentReaderHashMap.Entry (17,9%)
ConcurrentReaderHashMap.EntrySet (0%)
ConcurrentReaderHashMap.HashIterator (0%)
ConcurrentReaderHashMap.KeyIterator (0%)
ConcurrentReaderHashMap.KeySet (0%)
ConcurrentReaderHashMap.ValueIterator (0%)
ConcurrentReaderHashMap.Values (0%)
ContentListFacade (27,6%)
DefaultAttribute (50%)
DefaultCDATA (26,7%)
DefaultComment (53,3%)
DefaultDocument (49,5%)
DefaultDocumentType (75%)
DefaultElement (65,5%)
DefaultEntity (21,1%)
DefaultNamespace (90,6%)
DefaultProcessingInstruction (24%)
DefaultText (80%)
ElementIterator (0%)
ElementNameIterator (0%)
ElementQNameIterator (0%)
FilterIterator (0%)
FlyweightAttribute (46,7%)
FlyweightCDATA (66,7%)
FlyweightComment (66,7%)
FlyweightEntity (16,7%)
FlyweightProcessingInstruction (57,7%)
FlyweightText (66,7%)
NamespaceCache (85,9%)
NamespaceStack (84,9%)
QNameCache (78%)
SingleIterator (81,8%)
dom4j-1.6.1/docs/clover/org/dom4j/tree/DefaultDocument.html0000644000175000017500000031266210242117716023035 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 369   Methods: 29
NCLOC: 229   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DefaultDocument.java 30,8% 52,2% 72,4% 49,5%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.util.Collections;
 11    import java.util.Iterator;
 12    import java.util.List;
 13   
 14    import org.dom4j.Document;
 15    import org.dom4j.DocumentFactory;
 16    import org.dom4j.DocumentType;
 17    import org.dom4j.Element;
 18    import org.dom4j.IllegalAddException;
 19    import org.dom4j.Node;
 20    import org.dom4j.ProcessingInstruction;
 21   
 22    import org.xml.sax.EntityResolver;
 23   
 24    /**
 25    * <p>
 26    * <code>DefaultDocument</code> is the default DOM4J default implementation of
 27    * an XML document.
 28    * </p>
 29    *
 30    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 31    * @version $Revision: 1.34 $
 32    */
 33    public class DefaultDocument extends AbstractDocument {
 34    protected static final List EMPTY_LIST = Collections.EMPTY_LIST;
 35   
 36    protected static final Iterator EMPTY_ITERATOR = EMPTY_LIST.iterator();
 37   
 38    /** The name of the document */
 39    private String name;
 40   
 41    /** The root element of this document */
 42    private Element rootElement;
 43   
 44    /**
 45    * Store the contents of the document as a lazily created <code>List</code>
 46    */
 47    private List content;
 48   
 49    /** The document type for this document */
 50    private DocumentType docType;
 51   
 52    /** The document factory used by default */
 53    private DocumentFactory documentFactory = DocumentFactory.getInstance();
 54   
 55    /** The resolver of URIs */
 56    private transient EntityResolver entityResolver;
 57   
 58  6280 public DefaultDocument() {
 59    }
 60   
 61  2 public DefaultDocument(String name) {
 62  2 this.name = name;
 63    }
 64   
 65  1 public DefaultDocument(Element rootElement) {
 66  1 this.rootElement = rootElement;
 67    }
 68   
 69  0 public DefaultDocument(DocumentType docType) {
 70  0 this.docType = docType;
 71    }
 72   
 73  0 public DefaultDocument(Element rootElement, DocumentType docType) {
 74  0 this.rootElement = rootElement;
 75  0 this.docType = docType;
 76    }
 77   
 78  0 public DefaultDocument(String name, Element rootElement,
 79    DocumentType docType) {
 80  0 this.name = name;
 81  0 this.rootElement = rootElement;
 82  0 this.docType = docType;
 83    }
 84   
 85  213 public String getName() {
 86  213 return name;
 87    }
 88   
 89  5846 public void setName(String name) {
 90  5846 this.name = name;
 91    }
 92   
 93  12696 public Element getRootElement() {
 94  12696 return rootElement;
 95    }
 96   
 97  399 public DocumentType getDocType() {
 98  399 return docType;
 99    }
 100   
 101  11 public void setDocType(DocumentType docType) {
 102  11 this.docType = docType;
 103    }
 104   
 105  11 public Document addDocType(String docTypeName, String publicId,
 106    String systemId) {
 107  11 setDocType(getDocumentFactory().createDocType(docTypeName, publicId,
 108    systemId));
 109   
 110  11 return this;
 111    }
 112   
 113  5563 public String getXMLEncoding() {
 114  5563 return encoding;
 115    }
 116   
 117  2 public EntityResolver getEntityResolver() {
 118  2 return entityResolver;
 119    }
 120   
 121  5814 public void setEntityResolver(EntityResolver entityResolver) {
 122  5814 this.entityResolver = entityResolver;
 123    }
 124   
 125  9 public Object clone() {
 126  9 DefaultDocument document = (DefaultDocument) super.clone();
 127  9 document.rootElement = null;
 128  9 document.content = null;
 129  9 document.appendContent(this);
 130   
 131  9 return document;
 132    }
 133   
 134  0 public List processingInstructions() {
 135  0 List source = contentList();
 136  0 List answer = createResultList();
 137  0 int size = source.size();
 138   
 139  0 for (int i = 0; i < size; i++) {
 140  0 Object object = source.get(i);
 141   
 142  0 if (object instanceof ProcessingInstruction) {
 143  0 answer.add(object);
 144    }
 145    }
 146   
 147  0 return answer;
 148    }
 149   
 150  0 public List processingInstructions(String target) {
 151  0 List source = contentList();
 152  0 List answer = createResultList();
 153  0 int size = source.size();
 154   
 155  0 for (int i = 0; i < size; i++) {
 156  0 Object object = source.get(i);
 157   
 158  0 if (object instanceof ProcessingInstruction) {
 159  0 ProcessingInstruction pi = (ProcessingInstruction) object;
 160   
 161  0 if (target.equals(pi.getName())) {
 162  0 answer.add(pi);
 163    }
 164    }
 165    }
 166   
 167  0 return answer;
 168    }
 169   
 170  0 public ProcessingInstruction processingInstruction(String target) {
 171  0 List source = contentList();
 172  0 int size = source.size();
 173   
 174  0 for (int i = 0; i < size; i++) {
 175  0 Object object = source.get(i);
 176   
 177  0 if (object instanceof ProcessingInstruction) {
 178  0 ProcessingInstruction pi = (ProcessingInstruction) object;
 179   
 180  0 if (target.equals(pi.getName())) {
 181  0 return pi;
 182    }
 183    }
 184    }
 185   
 186  0 return null;
 187    }
 188   
 189  0 public boolean removeProcessingInstruction(String target) {
 190  0 List source = contentList();
 191   
 192  0 for (Iterator iter = source.iterator(); iter.hasNext();) {
 193  0 Object object = iter.next();
 194   
 195  0 if (object instanceof ProcessingInstruction) {
 196  0 ProcessingInstruction pi = (ProcessingInstruction) object;
 197   
 198  0 if (target.equals(pi.getName())) {
 199  0 iter.remove();
 200   
 201  0 return true;
 202    }
 203    }
 204    }
 205   
 206  0 return false;
 207    }
 208   
 209  1 public void setContent(List content) {
 210  1 rootElement = null;
 211  1 contentRemoved();
 212   
 213  1 if (content instanceof ContentListFacade) {
 214  1 content = ((ContentListFacade) content).getBackingList();
 215    }
 216   
 217  1 if (content == null) {
 218  0 this.content = null;
 219    } else {
 220  1 int size = content.size();
 221  1 List newContent = createContentList(size);
 222   
 223  1 for (int i = 0; i < size; i++) {
 224  1 Object object = content.get(i);
 225   
 226  1 if (object instanceof Node) {
 227  1 Node node = (Node) object;
 228  1 Document doc = node.getDocument();
 229   
 230  1 if ((doc != null) && (doc != this)) {
 231  1 node = (Node) node.clone();
 232    }
 233   
 234  1 if (node instanceof Element) {
 235  1 if (rootElement == null) {
 236  1 rootElement = (Element) node;
 237    } else {
 238  0 throw new IllegalAddException(
 239    "A document may only "
 240    + "contain one root " + "element: "
 241    + content);
 242    }
 243    }
 244   
 245  1 newContent.add(node);
 246  1 childAdded(node);
 247    }
 248    }
 249   
 250  1 this.content = newContent;
 251    }
 252    }
 253   
 254  5 public void clearContent() {
 255  5 contentRemoved();
 256  5 content = null;
 257  5 rootElement = null;
 258    }
 259   
 260  6286 public void setDocumentFactory(DocumentFactory documentFactory) {
 261  6286 this.documentFactory = documentFactory;
 262    }
 263   
 264    // Implementation methods
 265    // -------------------------------------------------------------------------
 266  7474 protected List contentList() {
 267  7474 if (content == null) {
 268  6296 content = createContentList();
 269   
 270  6296 if (rootElement != null) {
 271  1 content.add(rootElement);
 272    }
 273    }
 274   
 275  7474 return content;
 276    }
 277   
 278  6340 protected void addNode(Node node) {
 279  6340 if (node != null) {
 280  6340 Document document = node.getDocument();
 281   
 282  6340 if ((document != null) && (document != this)) {
 283    // XXX: could clone here
 284  0 String message = "The Node already has an existing document: "
 285    + document;
 286  0 throw new IllegalAddException(this, node, message);
 287    }
 288   
 289  6340 contentList().add(node);
 290  6340 childAdded(node);
 291    }
 292    }
 293   
 294  0 protected void addNode(int index, Node node) {
 295  0 if (node != null) {
 296  0 Document document = node.getDocument();
 297   
 298  0 if ((document != null) && (document != this)) {
 299    // XXX: could clone here
 300  0 String message = "The Node already has an existing document: "
 301    + document;
 302  0 throw new IllegalAddException(this, node, message);
 303    }
 304   
 305  0 contentList().add(index, node);
 306  0 childAdded(node);
 307    }
 308    }
 309   
 310  2 protected boolean removeNode(Node node) {
 311  2 if (node == rootElement) {
 312  2 rootElement = null;
 313    }
 314   
 315  2 if (contentList().remove(node)) {
 316  2 childRemoved(node);
 317   
 318  2 return true;
 319    }
 320   
 321  0 return false;
 322    }
 323   
 324  6291 protected void rootElementAdded(Element element) {
 325  6291 this.rootElement = element;
 326  6291 element.setDocument(this);
 327    }
 328   
 329  6797 protected DocumentFactory getDocumentFactory() {
 330  6797 return documentFactory;
 331    }
 332    }
 333   
 334    /*
 335    * Redistribution and use of this software and associated documentation
 336    * ("Software"), with or without modification, are permitted provided that the
 337    * following conditions are met:
 338    *
 339    * 1. Redistributions of source code must retain copyright statements and
 340    * notices. Redistributions must also contain a copy of this document.
 341    *
 342    * 2. Redistributions in binary form must reproduce the above copyright notice,
 343    * this list of conditions and the following disclaimer in the documentation
 344    * and/or other materials provided with the distribution.
 345    *
 346    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 347    * from this Software without prior written permission of MetaStuff, Ltd. For
 348    * written permission, please contact dom4j-info@metastuff.com.
 349    *
 350    * 4. Products derived from this Software may not be called "DOM4J" nor may
 351    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 352    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 353    *
 354    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 355    *
 356    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 357    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 358    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 359    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 360    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 361    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 362    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 363    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 364    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 365    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 366    * POSSIBILITY OF SUCH DAMAGE.
 367    *
 368    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 369    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/AbstractAttribute.html0000644000175000017500000015327110242117630023373 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 191   Methods: 19
NCLOC: 104   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
AbstractAttribute.java 60% 71,7% 57,9% 66,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.io.IOException;
 11    import java.io.Writer;
 12   
 13    import org.dom4j.Attribute;
 14    import org.dom4j.Element;
 15    import org.dom4j.Namespace;
 16    import org.dom4j.Node;
 17    import org.dom4j.Visitor;
 18   
 19    /**
 20    * <p>
 21    * <code>AbstractNamespace</code> is an abstract base class for tree
 22    * implementors to use for implementation inheritence.
 23    * </p>
 24    *
 25    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 26    * @version $Revision: 1.21 $
 27    */
 28    public abstract class AbstractAttribute extends AbstractNode implements
 29    Attribute {
 30  15 public short getNodeType() {
 31  15 return ATTRIBUTE_NODE;
 32    }
 33   
 34  0 public void setNamespace(Namespace namespace) {
 35  0 String msg = "This Attribute is read only and cannot be changed";
 36  0 throw new UnsupportedOperationException(msg);
 37    }
 38   
 39  305 public String getText() {
 40  305 return getValue();
 41    }
 42   
 43  0 public void setText(String text) {
 44  0 setValue(text);
 45    }
 46   
 47  0 public void setValue(String value) {
 48  0 String msg = "This Attribute is read only and cannot be changed";
 49  0 throw new UnsupportedOperationException(msg);
 50    }
 51   
 52  0 public Object getData() {
 53  0 return getValue();
 54    }
 55   
 56  0 public void setData(Object data) {
 57  0 setValue((data == null) ? null : data.toString());
 58    }
 59   
 60  52550 public String toString() {
 61  52550 return super.toString() + " [Attribute: name " + getQualifiedName()
 62    + " value \"" + getValue() + "\"]";
 63    }
 64   
 65  9 public String asXML() {
 66  9 return getQualifiedName() + "=\"" + getValue() + "\"";
 67    }
 68   
 69  0 public void write(Writer writer) throws IOException {
 70  0 writer.write(getQualifiedName());
 71  0 writer.write("=\"");
 72  0 writer.write(getValue());
 73  0 writer.write("\"");
 74    }
 75   
 76  0 public void accept(Visitor visitor) {
 77  0 visitor.visit(this);
 78    }
 79   
 80    // QName methods
 81  4320 public Namespace getNamespace() {
 82  4320 return getQName().getNamespace();
 83    }
 84   
 85  10975 public String getName() {
 86  10975 return getQName().getName();
 87    }
 88   
 89  15 public String getNamespacePrefix() {
 90  15 return getQName().getNamespacePrefix();
 91    }
 92   
 93  5153 public String getNamespaceURI() {
 94  5153 return getQName().getNamespaceURI();
 95    }
 96   
 97  61936 public String getQualifiedName() {
 98  61936 return getQName().getQualifiedName();
 99    }
 100   
 101  5 public String getPath(Element context) {
 102  5 StringBuffer result = new StringBuffer();
 103   
 104  5 Element parent = getParent();
 105   
 106  5 if ((parent != null) && (parent != context)) {
 107  5 result.append(parent.getPath(context));
 108  5 result.append("/");
 109    }
 110   
 111  5 result.append("@");
 112   
 113  5 String uri = getNamespaceURI();
 114  5 String prefix = getNamespacePrefix();
 115   
 116  5 if ((uri == null) || (uri.length() == 0) || (prefix == null)
 117    || (prefix.length() == 0)) {
 118  4 result.append(getName());
 119    } else {
 120  1 result.append(getQualifiedName());
 121    }
 122   
 123  5 return result.toString();
 124    }
 125   
 126  5 public String getUniquePath(Element context) {
 127  5 StringBuffer result = new StringBuffer();
 128   
 129  5 Element parent = getParent();
 130   
 131  5 if ((parent != null) && (parent != context)) {
 132  5 result.append(parent.getUniquePath(context));
 133  5 result.append("/");
 134    }
 135   
 136  5 result.append("@");
 137   
 138  5 String uri = getNamespaceURI();
 139  5 String prefix = getNamespacePrefix();
 140   
 141  5 if ((uri == null) || (uri.length() == 0) || (prefix == null)
 142    || (prefix.length() == 0)) {
 143  4 result.append(getName());
 144    } else {
 145  1 result.append(getQualifiedName());
 146    }
 147   
 148  5 return result.toString();
 149    }
 150   
 151  0 protected Node createXPathResult(Element parent) {
 152  0 return new DefaultAttribute(parent, getQName(), getValue());
 153    }
 154    }
 155   
 156    /*
 157    * Redistribution and use of this software and associated documentation
 158    * ("Software"), with or without modification, are permitted provided that the
 159    * following conditions are met:
 160    *
 161    * 1. Redistributions of source code must retain copyright statements and
 162    * notices. Redistributions must also contain a copy of this document.
 163    *
 164    * 2. Redistributions in binary form must reproduce the above copyright notice,
 165    * this list of conditions and the following disclaimer in the documentation
 166    * and/or other materials provided with the distribution.
 167    *
 168    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 169    * from this Software without prior written permission of MetaStuff, Ltd. For
 170    * written permission, please contact dom4j-info@metastuff.com.
 171    *
 172    * 4. Products derived from this Software may not be called "DOM4J" nor may
 173    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 174    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 175    *
 176    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 177    *
 178    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 179    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 180    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 181    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 182    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 183    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 184    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 185    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 186    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 187    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 188    * POSSIBILITY OF SUCH DAMAGE.
 189    *
 190    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 191    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/ElementNameIterator.html0000644000175000017500000006245410242117701023651 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 89   Methods: 2
NCLOC: 17   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
ElementNameIterator.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.util.Iterator;
 11   
 12    import org.dom4j.Element;
 13   
 14    /**
 15    * <p>
 16    * <code>ElementNameIterator</code> is a filtering {@link Iterator}which
 17    * filters out objects which do not implement the {@link Element}interface and
 18    * are not of the correct element name.
 19    * </p>
 20    *
 21    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 22    * @version $Revision: 1.11 $
 23    *
 24    * @deprecated THIS CLASS WILL BE REMOVED IN dom4j-1.6 !!
 25    */
 26    public class ElementNameIterator extends FilterIterator {
 27    private String name;
 28   
 29  0 public ElementNameIterator(Iterator proxy, String name) {
 30  0 super(proxy);
 31  0 this.name = name;
 32    }
 33   
 34    /**
 35    * DOCUMENT ME!
 36    *
 37    * @param object
 38    * DOCUMENT ME!
 39    *
 40    * @return true if the given element implements the {@link Element}
 41    * interface
 42    */
 43  0 protected boolean matches(Object object) {
 44  0 if (object instanceof Element) {
 45  0 Element element = (Element) object;
 46   
 47  0 return name.equals(element.getName());
 48    }
 49   
 50  0 return false;
 51    }
 52    }
 53   
 54    /*
 55    * Redistribution and use of this software and associated documentation
 56    * ("Software"), with or without modification, are permitted provided that the
 57    * following conditions are met:
 58    *
 59    * 1. Redistributions of source code must retain copyright statements and
 60    * notices. Redistributions must also contain a copy of this document.
 61    *
 62    * 2. Redistributions in binary form must reproduce the above copyright notice,
 63    * this list of conditions and the following disclaimer in the documentation
 64    * and/or other materials provided with the distribution.
 65    *
 66    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 67    * from this Software without prior written permission of MetaStuff, Ltd. For
 68    * written permission, please contact dom4j-info@metastuff.com.
 69    *
 70    * 4. Products derived from this Software may not be called "DOM4J" nor may
 71    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 72    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 73    *
 74    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 75    *
 76    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 77    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 78    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 79    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 80    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 81    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 82    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 83    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 84    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 85    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 86    * POSSIBILITY OF SUCH DAMAGE.
 87    *
 88    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 89    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/BaseElement.html0000644000175000017500000015004110242117552022123 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 189   Methods: 17
NCLOC: 93   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
BaseElement.java 10% 21,6% 23,5% 18,9%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.util.List;
 11   
 12    import org.dom4j.Branch;
 13    import org.dom4j.Document;
 14    import org.dom4j.Element;
 15    import org.dom4j.Namespace;
 16    import org.dom4j.QName;
 17   
 18    /**
 19    * <p>
 20    * <code>BaseElement</code> is a useful base class for implemementation
 21    * inheritence of an XML element.
 22    * </p>
 23    *
 24    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 25    * @version $Revision: 1.9 $
 26    */
 27    public class BaseElement extends AbstractElement {
 28    /** The <code>QName</code> for this element */
 29    private QName qname;
 30   
 31    /**
 32    * Stores the parent branch of this node which is either a Document if this
 33    * element is the root element in a document, or another Element if it is a
 34    * child of the root document, or null if it has not been added to a
 35    * document yet.
 36    */
 37    private Branch parentBranch;
 38   
 39    /** List of content nodes. */
 40    protected List content;
 41   
 42    /** list of attributes */
 43    protected List attributes;
 44   
 45  1 public BaseElement(String name) {
 46  1 this.qname = getDocumentFactory().createQName(name);
 47    }
 48   
 49  0 public BaseElement(QName qname) {
 50  0 this.qname = qname;
 51    }
 52   
 53  0 public BaseElement(String name, Namespace namespace) {
 54  0 this.qname = getDocumentFactory().createQName(name, namespace);
 55    }
 56   
 57  0 public Element getParent() {
 58  0 Element result = null;
 59   
 60  0 if (parentBranch instanceof Element) {
 61  0 result = (Element) parentBranch;
 62    }
 63   
 64  0 return result;
 65    }
 66   
 67  0 public void setParent(Element parent) {
 68  0 if (parentBranch instanceof Element || (parent != null)) {
 69  0 parentBranch = parent;
 70    }
 71    }
 72   
 73  0 public Document getDocument() {
 74  0 if (parentBranch instanceof Document) {
 75  0 return (Document) parentBranch;
 76  0 } else if (parentBranch instanceof Element) {
 77  0 Element parent = (Element) parentBranch;
 78   
 79  0 return parent.getDocument();
 80    }
 81   
 82  0 return null;
 83    }
 84   
 85  0 public void setDocument(Document document) {
 86  0 if (parentBranch instanceof Document || (document != null)) {
 87  0 parentBranch = document;
 88    }
 89    }
 90   
 91  0 public boolean supportsParent() {
 92  0 return true;
 93    }
 94   
 95  3 public QName getQName() {
 96  3 return qname;
 97    }
 98   
 99  0 public void setQName(QName name) {
 100  0 this.qname = name;
 101    }
 102   
 103  0 public void clearContent() {
 104  0 contentList().clear();
 105    }
 106   
 107  0 public void setContent(List content) {
 108  0 this.content = content;
 109   
 110  0 if (content instanceof ContentListFacade) {
 111  0 this.content = ((ContentListFacade) content).getBackingList();
 112    }
 113    }
 114   
 115  0 public void setAttributes(List attributes) {
 116  0 this.attributes = attributes;
 117   
 118  0 if (attributes instanceof ContentListFacade) {
 119  0 this.attributes = ((ContentListFacade) attributes).getBackingList();
 120    }
 121    }
 122   
 123    // Implementation methods
 124    // -------------------------------------------------------------------------
 125  1 protected List contentList() {
 126  1 if (content == null) {
 127  1 content = createContentList();
 128    }
 129   
 130  1 return content;
 131    }
 132   
 133  1 protected List attributeList() {
 134  1 if (attributes == null) {
 135  1 attributes = createAttributeList();
 136    }
 137   
 138  1 return attributes;
 139    }
 140   
 141  0 protected List attributeList(int size) {
 142  0 if (attributes == null) {
 143  0 attributes = createAttributeList(size);
 144    }
 145   
 146  0 return attributes;
 147    }
 148   
 149  0 protected void setAttributeList(List attributeList) {
 150  0 this.attributes = attributeList;
 151    }
 152    }
 153   
 154    /*
 155    * Redistribution and use of this software and associated documentation
 156    * ("Software"), with or without modification, are permitted provided that the
 157    * following conditions are met:
 158    *
 159    * 1. Redistributions of source code must retain copyright statements and
 160    * notices. Redistributions must also contain a copy of this document.
 161    *
 162    * 2. Redistributions in binary form must reproduce the above copyright notice,
 163    * this list of conditions and the following disclaimer in the documentation
 164    * and/or other materials provided with the distribution.
 165    *
 166    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 167    * from this Software without prior written permission of MetaStuff, Ltd. For
 168    * written permission, please contact dom4j-info@metastuff.com.
 169    *
 170    * 4. Products derived from this Software may not be called "DOM4J" nor may
 171    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 172    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 173    *
 174    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 175    *
 176    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 177    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 178    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 179    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 180    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 181    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 182    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 183    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 184    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 185    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 186    * POSSIBILITY OF SUCH DAMAGE.
 187    *
 188    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 189    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/AbstractBranch.html0000644000175000017500000041053410242117712022624 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 493   Methods: 35
NCLOC: 250   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
AbstractBranch.java 65% 65,2% 74,3% 66,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.util.ArrayList;
 11    import java.util.Iterator;
 12    import java.util.List;
 13    import java.util.StringTokenizer;
 14   
 15    import org.dom4j.Branch;
 16    import org.dom4j.Comment;
 17    import org.dom4j.Element;
 18    import org.dom4j.IllegalAddException;
 19    import org.dom4j.Namespace;
 20    import org.dom4j.Node;
 21    import org.dom4j.ProcessingInstruction;
 22    import org.dom4j.QName;
 23   
 24    /**
 25    * <p>
 26    * <code>AbstractBranch</code> is an abstract base class for tree implementors
 27    * to use for implementation inheritence.
 28    * </p>
 29    *
 30    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 31    * @version $Revision: 1.44 $
 32    */
 33    public abstract class AbstractBranch extends AbstractNode implements Branch {
 34    protected static final int DEFAULT_CONTENT_LIST_SIZE = 5;
 35   
 36  102292 public AbstractBranch() {
 37    }
 38   
 39  138 public boolean isReadOnly() {
 40  138 return false;
 41    }
 42   
 43  0 public boolean hasContent() {
 44  0 return nodeCount() > 0;
 45    }
 46   
 47  4891 public List content() {
 48  4891 List backingList = contentList();
 49   
 50  4891 return new ContentListFacade(this, backingList);
 51    }
 52   
 53  80 public String getText() {
 54  80 List content = contentList();
 55   
 56  80 if (content != null) {
 57  80 int size = content.size();
 58   
 59  80 if (size >= 1) {
 60  80 Object first = content.get(0);
 61  80 String firstText = getContentAsText(first);
 62   
 63  80 if (size == 1) {
 64    // optimised to avoid StringBuffer creation
 65  68 return firstText;
 66    } else {
 67  12 StringBuffer buffer = new StringBuffer(firstText);
 68   
 69  12 for (int i = 1; i < size; i++) {
 70  29 Object node = content.get(i);
 71  29 buffer.append(getContentAsText(node));
 72    }
 73   
 74  12 return buffer.toString();
 75    }
 76    }
 77    }
 78   
 79  0 return "";
 80    }
 81   
 82    /**
 83    * DOCUMENT ME!
 84    *
 85    * @param content
 86    * DOCUMENT ME!
 87    *
 88    * @return the text value of the given content object as text which returns
 89    * the text value of CDATA, Entity or Text nodes
 90    */
 91  202 protected String getContentAsText(Object content) {
 92  202 if (content instanceof Node) {
 93  202 Node node = (Node) content;
 94   
 95  202 switch (node.getNodeType()) {
 96  2 case CDATA_SECTION_NODE:
 97   
 98    // case ENTITY_NODE:
 99  0 case ENTITY_REFERENCE_NODE:
 100  195 case TEXT_NODE:
 101  197 return node.getText();
 102   
 103  5 default:
 104  5 break;
 105    }
 106  0 } else if (content instanceof String) {
 107  0 return (String) content;
 108    }
 109   
 110  5 return "";
 111    }
 112   
 113    /**
 114    * DOCUMENT ME!
 115    *
 116    * @param content
 117    * DOCUMENT ME!
 118    *
 119    * @return the XPath defined string-value of the given content object
 120    */
 121  13 protected String getContentAsStringValue(Object content) {
 122  13 if (content instanceof Node) {
 123  13 Node node = (Node) content;
 124   
 125  13 switch (node.getNodeType()) {
 126  0 case CDATA_SECTION_NODE:
 127   
 128    // case ENTITY_NODE:
 129  0 case ENTITY_REFERENCE_NODE:
 130  11 case TEXT_NODE:
 131  2 case ELEMENT_NODE:
 132  13 return node.getStringValue();
 133   
 134  0 default:
 135  0 break;
 136    }
 137  0 } else if (content instanceof String) {
 138  0 return (String) content;
 139    }
 140   
 141  0 return "";
 142    }
 143   
 144  77 public String getTextTrim() {
 145  77 String text = getText();
 146   
 147  77 StringBuffer textContent = new StringBuffer();
 148  77 StringTokenizer tokenizer = new StringTokenizer(text);
 149   
 150  77 while (tokenizer.hasMoreTokens()) {
 151  99 String str = tokenizer.nextToken();
 152  99 textContent.append(str);
 153   
 154  99 if (tokenizer.hasMoreTokens()) {
 155  23 textContent.append(" "); // separator
 156    }
 157    }
 158   
 159  77 return textContent.toString();
 160    }
 161   
 162  0 public void setProcessingInstructions(List listOfPIs) {
 163  0 for (Iterator iter = listOfPIs.iterator(); iter.hasNext();) {
 164  0 ProcessingInstruction pi = (ProcessingInstruction) iter.next();
 165  0 addNode(pi);
 166    }
 167    }
 168   
 169  0 public Element addElement(String name) {
 170  0 Element node = getDocumentFactory().createElement(name);
 171  0 add(node);
 172   
 173  0 return node;
 174    }
 175   
 176  2 public Element addElement(String qualifiedName, String namespaceURI) {
 177  2 Element node = getDocumentFactory().createElement(qualifiedName,
 178    namespaceURI);
 179  2 add(node);
 180   
 181  2 return node;
 182    }
 183   
 184  86007 public Element addElement(QName qname) {
 185  86007 Element node = getDocumentFactory().createElement(qname);
 186  86007 add(node);
 187   
 188  86007 return node;
 189    }
 190   
 191  0 public Element addElement(String name, String prefix, String uri) {
 192  0 Namespace namespace = Namespace.get(prefix, uri);
 193  0 QName qName = getDocumentFactory().createQName(name, namespace);
 194   
 195  0 return addElement(qName);
 196    }
 197   
 198    // polymorphic node methods
 199  14 public void add(Node node) {
 200  14 switch (node.getNodeType()) {
 201  14 case ELEMENT_NODE:
 202  14 add((Element) node);
 203   
 204  14 break;
 205   
 206  0 case COMMENT_NODE:
 207  0 add((Comment) node);
 208   
 209  0 break;
 210   
 211  0 case PROCESSING_INSTRUCTION_NODE:
 212  0 add((ProcessingInstruction) node);
 213   
 214  0 break;
 215   
 216  0 default:
 217  0 invalidNodeTypeAddException(node);
 218    }
 219    }
 220   
 221  2 public boolean remove(Node node) {
 222  2 switch (node.getNodeType()) {
 223  2 case ELEMENT_NODE:
 224  2 return remove((Element) node);
 225   
 226  0 case COMMENT_NODE:
 227  0 return remove((Comment) node);
 228   
 229  0 case PROCESSING_INSTRUCTION_NODE:
 230  0 return remove((ProcessingInstruction) node);
 231   
 232  0 default:
 233  0 invalidNodeTypeAddException(node);
 234   
 235  0 return false;
 236    }
 237    }
 238   
 239    // typesafe versions using node classes
 240  24 public void add(Comment comment) {
 241  24 addNode(comment);
 242    }
 243   
 244  6291 public void add(Element element) {
 245  6291 addNode(element);
 246    }
 247   
 248  25 public void add(ProcessingInstruction pi) {
 249  25 addNode(pi);
 250    }
 251   
 252  0 public boolean remove(Comment comment) {
 253  0 return removeNode(comment);
 254    }
 255   
 256  2 public boolean remove(Element element) {
 257  2 return removeNode(element);
 258    }
 259   
 260  0 public boolean remove(ProcessingInstruction pi) {
 261  0 return removeNode(pi);
 262    }
 263   
 264  13 public Element elementByID(String elementID) {
 265  13 for (int i = 0, size = nodeCount(); i < size; i++) {
 266  31 Node node = node(i);
 267   
 268  31 if (node instanceof Element) {
 269  12 Element element = (Element) node;
 270  12 String id = elementID(element);
 271   
 272  12 if ((id != null) && id.equals(elementID)) {
 273  1 return element;
 274    } else {
 275  11 element = element.elementByID(elementID);
 276   
 277  11 if (element != null) {
 278  2 return element;
 279    }
 280    }
 281    }
 282    }
 283   
 284  10 return null;
 285    }
 286   
 287  143 public void appendContent(Branch branch) {
 288  143 for (int i = 0, size = branch.nodeCount(); i < size; i++) {
 289  330 Node node = branch.node(i);
 290  330 add((Node) node.clone());
 291    }
 292    }
 293   
 294  435 public Node node(int index) {
 295  435 Object object = contentList().get(index);
 296   
 297  435 if (object instanceof Node) {
 298  435 return (Node) object;
 299    }
 300   
 301  0 if (object instanceof String) {
 302  0 return getDocumentFactory().createText(object.toString());
 303    }
 304   
 305  0 return null;
 306    }
 307   
 308  360 public int nodeCount() {
 309  360 return contentList().size();
 310    }
 311   
 312  0 public int indexOf(Node node) {
 313  0 return contentList().indexOf(node);
 314    }
 315   
 316  313 public Iterator nodeIterator() {
 317  313 return contentList().iterator();
 318    }
 319   
 320    // Implementation methods
 321   
 322    /**
 323    * DOCUMENT ME!
 324    *
 325    * @param element
 326    * DOCUMENT ME!
 327    *
 328    * @return the ID of the given <code>Element</code>
 329    */
 330  12 protected String elementID(Element element) {
 331    // XXX: there will be other ways of finding the ID
 332    // XXX: should probably have an IDResolver or something
 333  12 return element.attributeValue("ID");
 334    }
 335   
 336    /**
 337    * DOCUMENT ME!
 338    *
 339    * @return the internal List used to manage the content
 340    */
 341    protected abstract List contentList();
 342   
 343    /**
 344    * A Factory Method pattern which creates a List implementation used to
 345    * store content
 346    *
 347    * @return DOCUMENT ME!
 348    */
 349  57260 protected List createContentList() {
 350  57260 return new ArrayList(DEFAULT_CONTENT_LIST_SIZE);
 351    }
 352   
 353    /**
 354    * A Factory Method pattern which creates a List implementation used to
 355    * store content
 356    *
 357    * @param size
 358    * DOCUMENT ME!
 359    *
 360    * @return DOCUMENT ME!
 361    */
 362  3 protected List createContentList(int size) {
 363  3 return new ArrayList(size);
 364    }
 365   
 366    /**
 367    * A Factory Method pattern which creates a BackedList implementation used
 368    * to store results of a filtered content query.
 369    *
 370    * @return DOCUMENT ME!
 371    */
 372  24169 protected BackedList createResultList() {
 373  24169 return new BackedList(this, contentList());
 374    }
 375   
 376    /**
 377    * A Factory Method pattern which creates a BackedList implementation which
 378    * contains a single result
 379    *
 380    * @param result
 381    * DOCUMENT ME!
 382    *
 383    * @return DOCUMENT ME!
 384    */
 385  0 protected List createSingleResultList(Object result) {
 386  0 BackedList list = new BackedList(this, contentList(), 1);
 387  0 list.addLocal(result);
 388   
 389  0 return list;
 390    }
 391   
 392    /**
 393    * A Factory Method pattern which creates an empty a BackedList
 394    * implementation
 395    *
 396    * @return DOCUMENT ME!
 397    */
 398  2 protected List createEmptyList() {
 399  2 return new BackedList(this, contentList(), 0);
 400    }
 401   
 402    protected abstract void addNode(Node node);
 403   
 404    protected abstract void addNode(int index, Node node);
 405   
 406    protected abstract boolean removeNode(Node node);
 407   
 408    /**
 409    * Called when a new child node has been added to me to allow any parent
 410    * relationships to be created or events to be fired.
 411    *
 412    * @param node
 413    * DOCUMENT ME!
 414    */
 415    protected abstract void childAdded(Node node);
 416   
 417    /**
 418    * Called when a child node has been removed to allow any parent
 419    * relationships to be deleted or events to be fired.
 420    *
 421    * @param node
 422    * DOCUMENT ME!
 423    */
 424    protected abstract void childRemoved(Node node);
 425   
 426    /**
 427    * Called when the given List content has been removed so each node should
 428    * have its parent and document relationships cleared
 429    */
 430  8 protected void contentRemoved() {
 431  8 List content = contentList();
 432   
 433  8 for (int i = 0, size = content.size(); i < size; i++) {
 434  8 Object object = content.get(i);
 435   
 436  8 if (object instanceof Node) {
 437  8 childRemoved((Node) object);
 438    }
 439    }
 440    }
 441   
 442    /**
 443    * Called when an invalid node has been added. Throws an {@link
 444    * IllegalAddException}.
 445    *
 446    * @param node
 447    * DOCUMENT ME!
 448    *
 449    * @throws IllegalAddException
 450    * DOCUMENT ME!
 451    */
 452  0 protected void invalidNodeTypeAddException(Node node) {
 453  0 throw new IllegalAddException("Invalid node type. Cannot add node: "
 454    + node + " to this branch: " + this);
 455    }
 456    }
 457   
 458    /*
 459    * Redistribution and use of this software and associated documentation
 460    * ("Software"), with or without modification, are permitted provided that the
 461    * following conditions are met:
 462    *
 463    * 1. Redistributions of source code must retain copyright statements and
 464    * notices. Redistributions must also contain a copy of this document.
 465    *
 466    * 2. Redistributions in binary form must reproduce the above copyright notice,
 467    * this list of conditions and the following disclaimer in the documentation
 468    * and/or other materials provided with the distribution.
 469    *
 470    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 471    * from this Software without prior written permission of MetaStuff, Ltd. For
 472    * written permission, please contact dom4j-info@metastuff.com.
 473    *
 474    * 4. Products derived from this Software may not be called "DOM4J" nor may
 475    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 476    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 477    *
 478    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 479    *
 480    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 481    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 482    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 483    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 484    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 485    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 486    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 487    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 488    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 489    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 490    * POSSIBILITY OF SUCH DAMAGE.
 491    *
 492    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 493    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/FlyweightCDATA.html0000644000175000017500000006100510242117721022435 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 86   Methods: 3
NCLOC: 16   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
FlyweightCDATA.java - 66,7% 66,7% 66,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import org.dom4j.CDATA;
 11    import org.dom4j.Element;
 12    import org.dom4j.Node;
 13   
 14    /**
 15    * <p>
 16    * <code>FlyweightCDATA</code> is a Flyweight pattern implementation of a
 17    * singly linked, read-only XML CDATA.
 18    * </p>
 19    *
 20    * <p>
 21    * This node could be shared across documents and elements though it does not
 22    * support the parent relationship.
 23    * </p>
 24    *
 25    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 26    * @version $Revision: 1.8 $
 27    */
 28    public class FlyweightCDATA extends AbstractCDATA implements CDATA {
 29    /** Text of the <code>CDATA</code> node */
 30    protected String text;
 31   
 32    /**
 33    * DOCUMENT ME!
 34    *
 35    * @param text
 36    * is the CDATA text
 37    */
 38  105 public FlyweightCDATA(String text) {
 39  105 this.text = text;
 40    }
 41   
 42  627 public String getText() {
 43  627 return text;
 44    }
 45   
 46  0 protected Node createXPathResult(Element parent) {
 47  0 return new DefaultCDATA(parent, getText());
 48    }
 49    }
 50   
 51    /*
 52    * Redistribution and use of this software and associated documentation
 53    * ("Software"), with or without modification, are permitted provided that the
 54    * following conditions are met:
 55    *
 56    * 1. Redistributions of source code must retain copyright statements and
 57    * notices. Redistributions must also contain a copy of this document.
 58    *
 59    * 2. Redistributions in binary form must reproduce the above copyright notice,
 60    * this list of conditions and the following disclaimer in the documentation
 61    * and/or other materials provided with the distribution.
 62    *
 63    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 64    * from this Software without prior written permission of MetaStuff, Ltd. For
 65    * written permission, please contact dom4j-info@metastuff.com.
 66    *
 67    * 4. Products derived from this Software may not be called "DOM4J" nor may
 68    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 69    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 70    *
 71    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 72    *
 73    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 74    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 75    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 76    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 77    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 78    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 79    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 80    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 81    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 82    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 83    * POSSIBILITY OF SUCH DAMAGE.
 84    *
 85    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 86    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/ElementQNameIterator.html0000644000175000017500000006311710242117610023766 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 90   Methods: 2
NCLOC: 18   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
ElementQNameIterator.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.util.Iterator;
 11   
 12    import org.dom4j.Element;
 13    import org.dom4j.QName;
 14   
 15    /**
 16    * <p>
 17    * <code>ElementQNameIterator</code> is a filtering {@link Iterator}which
 18    * filters out objects which do not implement the {@link Element}interface and
 19    * are not of the correct fully qualified element name.
 20    * </p>
 21    *
 22    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 23    * @version $Revision: 1.7 $
 24    *
 25    * @deprecated THIS CLASS WILL BE REMOVED IN dom4j-1.6 !!
 26    */
 27    public class ElementQNameIterator extends FilterIterator {
 28    private QName qName;
 29   
 30  0 public ElementQNameIterator(Iterator proxy, QName qName) {
 31  0 super(proxy);
 32  0 this.qName = qName;
 33    }
 34   
 35    /**
 36    * DOCUMENT ME!
 37    *
 38    * @param object
 39    * DOCUMENT ME!
 40    *
 41    * @return true if the given element implements the {@link Element}
 42    * interface and matches the given {@link QName}
 43    */
 44  0 protected boolean matches(Object object) {
 45  0 if (object instanceof Element) {
 46  0 Element element = (Element) object;
 47   
 48  0 return qName.equals(element.getQName());
 49    }
 50   
 51  0 return false;
 52    }
 53    }
 54   
 55    /*
 56    * Redistribution and use of this software and associated documentation
 57    * ("Software"), with or without modification, are permitted provided that the
 58    * following conditions are met:
 59    *
 60    * 1. Redistributions of source code must retain copyright statements and
 61    * notices. Redistributions must also contain a copy of this document.
 62    *
 63    * 2. Redistributions in binary form must reproduce the above copyright notice,
 64    * this list of conditions and the following disclaimer in the documentation
 65    * and/or other materials provided with the distribution.
 66    *
 67    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 68    * from this Software without prior written permission of MetaStuff, Ltd. For
 69    * written permission, please contact dom4j-info@metastuff.com.
 70    *
 71    * 4. Products derived from this Software may not be called "DOM4J" nor may
 72    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 73    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 74    *
 75    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 76    *
 77    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 78    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 79    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 80    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 81    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 82    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 83    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 84    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 85    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 86    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 87    * POSSIBILITY OF SUCH DAMAGE.
 88    *
 89    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 90    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/FlyweightEntity.html0000644000175000017500000011670610242117737023115 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 147   Methods: 7
NCLOC: 33   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
FlyweightEntity.java 0% 22,2% 14,3% 16,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import org.dom4j.Element;
 11    import org.dom4j.Node;
 12   
 13    /**
 14    * <p>
 15    * <code>FlyweightEntity</code> is a Flyweight pattern implementation of a
 16    * singly linked, read-only XML entity.
 17    * </p>
 18    *
 19    * <p>
 20    * This node could be shared across documents and elements though it does not
 21    * support the parent relationship.
 22    * </p>
 23    *
 24    * <p>
 25    * Often this node needs to be created and then the text content added later
 26    * (for example in SAX) so this implementation allows a call to {@link#setText}
 27    * providing the entity has no text already.
 28    * </p>
 29    *
 30    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 31    * @version $Revision: 1.6 $
 32    */
 33    public class FlyweightEntity extends AbstractEntity {
 34    /** The name of the <code>Entity</code> */
 35    protected String name;
 36   
 37    /** The text of the <code>Entity</code> */
 38    protected String text;
 39   
 40    /**
 41    * A default constructor for implementors to use.
 42    */
 43  0 protected FlyweightEntity() {
 44    }
 45   
 46    /**
 47    * Creates the <code>Entity</code> with the specified name
 48    *
 49    * @param name
 50    * is the name of the entity
 51    */
 52  0 public FlyweightEntity(String name) {
 53  0 this.name = name;
 54    }
 55   
 56    /**
 57    * Creates the <code>Entity</code> with the specified name and text.
 58    *
 59    * @param name
 60    * is the name of the entity
 61    * @param text
 62    * is the text of the entity
 63    */
 64  4 public FlyweightEntity(String name, String text) {
 65  4 this.name = name;
 66  4 this.text = text;
 67    }
 68   
 69    /**
 70    * DOCUMENT ME!
 71    *
 72    * @return the name of the entity
 73    */
 74  0 public String getName() {
 75  0 return name;
 76    }
 77   
 78    /**
 79    * DOCUMENT ME!
 80    *
 81    * @return the text of the entity
 82    */
 83  0 public String getText() {
 84  0 return text;
 85    }
 86   
 87    /**
 88    * sets the value of the entity if it is not defined yet otherwise an
 89    * <code>UnsupportedOperationException</code> is thrown as this class is
 90    * read only.
 91    *
 92    * @param text
 93    * DOCUMENT ME!
 94    *
 95    * @throws UnsupportedOperationException
 96    * DOCUMENT ME!
 97    */
 98  0 public void setText(String text) {
 99  0 if (this.text != null) {
 100  0 this.text = text;
 101    } else {
 102  0 throw new UnsupportedOperationException(
 103    "This Entity is read-only. " + "It cannot be modified");
 104    }
 105    }
 106   
 107  0 protected Node createXPathResult(Element parent) {
 108  0 return new DefaultEntity(parent, getName(), getText());
 109    }
 110    }
 111   
 112    /*
 113    * Redistribution and use of this software and associated documentation
 114    * ("Software"), with or without modification, are permitted provided that the
 115    * following conditions are met:
 116    *
 117    * 1. Redistributions of source code must retain copyright statements and
 118    * notices. Redistributions must also contain a copy of this document.
 119    *
 120    * 2. Redistributions in binary form must reproduce the above copyright notice,
 121    * this list of conditions and the following disclaimer in the documentation
 122    * and/or other materials provided with the distribution.
 123    *
 124    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 125    * from this Software without prior written permission of MetaStuff, Ltd. For
 126    * written permission, please contact dom4j-info@metastuff.com.
 127    *
 128    * 4. Products derived from this Software may not be called "DOM4J" nor may
 129    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 130    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 131    *
 132    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 133    *
 134    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 135    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 136    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 137    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 138    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 139    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 140    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 141    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 142    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 143    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 144    * POSSIBILITY OF SUCH DAMAGE.
 145    *
 146    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 147    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/DefaultElement.html0000644000175000017500000111135010242117735022641 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 1.055   Methods: 49
NCLOC: 727   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DefaultElement.java 59,8% 68,3% 75,5% 65,5%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.util.ArrayList;
 11    import java.util.Iterator;
 12    import java.util.List;
 13   
 14    import org.dom4j.Attribute;
 15    import org.dom4j.Branch;
 16    import org.dom4j.Document;
 17    import org.dom4j.DocumentFactory;
 18    import org.dom4j.Element;
 19    import org.dom4j.IllegalAddException;
 20    import org.dom4j.Namespace;
 21    import org.dom4j.Node;
 22    import org.dom4j.ProcessingInstruction;
 23    import org.dom4j.QName;
 24   
 25    /**
 26    * <p>
 27    * <code>DefaultElement</code> is the default DOM4J default implementation of
 28    * an XML element.
 29    * </p>
 30    *
 31    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 32    * @version $Revision: 1.59 $
 33    */
 34    public class DefaultElement extends AbstractElement {
 35    /** The <code>DocumentFactory</code> instance used by default */
 36    private static final transient DocumentFactory DOCUMENT_FACTORY =
 37    DocumentFactory.getInstance();
 38   
 39    /** The <code>QName</code> for this element */
 40    private QName qname;
 41   
 42    /**
 43    * Stores the parent branch of this node which is either a Document if this
 44    * element is the root element in a document, or another Element if it is a
 45    * child of the root document, or null if it has not been added to a
 46    * document yet.
 47    */
 48    private Branch parentBranch;
 49   
 50    /**
 51    * Stores null for no content, a Node for a single content node or a List
 52    * for multiple content nodes. The List will be lazily constructed when
 53    * required.
 54    */
 55    private Object content;
 56   
 57    /** Lazily constructes list of attributes */
 58    private Object attributes;
 59   
 60  1 public DefaultElement(String name) {
 61  1 this.qname = DOCUMENT_FACTORY.createQName(name);
 62    }
 63   
 64  96007 public DefaultElement(QName qname) {
 65  96007 this.qname = qname;
 66    }
 67   
 68  0 public DefaultElement(QName qname, int attributeCount) {
 69  0 this.qname = qname;
 70   
 71  0 if (attributeCount > 1) {
 72  0 this.attributes = new ArrayList(attributeCount);
 73    }
 74    }
 75   
 76  0 public DefaultElement(String name, Namespace namespace) {
 77  0 this.qname = DOCUMENT_FACTORY.createQName(name, namespace);
 78    }
 79   
 80  131539 public Element getParent() {
 81  131539 Element result = null;
 82   
 83  131539 if (parentBranch instanceof Element) {
 84  35288 result = (Element) parentBranch;
 85    }
 86   
 87  131539 return result;
 88    }
 89   
 90  94507 public void setParent(Element parent) {
 91  94507 if (parentBranch instanceof Element || (parent != null)) {
 92  92978 parentBranch = parent;
 93    }
 94    }
 95   
 96  13010 public Document getDocument() {
 97  13010 if (parentBranch instanceof Document) {
 98  6597 return (Document) parentBranch;
 99  6413 } else if (parentBranch instanceof Element) {
 100  117 Element parent = (Element) parentBranch;
 101   
 102  117 return parent.getDocument();
 103    }
 104   
 105  6296 return null;
 106    }
 107   
 108  15752 public void setDocument(Document document) {
 109  15752 if (parentBranch instanceof Document || (document != null)) {
 110  12600 parentBranch = document;
 111    }
 112    }
 113   
 114  10 public boolean supportsParent() {
 115  10 return true;
 116    }
 117   
 118  619575 public QName getQName() {
 119  619575 return qname;
 120    }
 121   
 122  1502 public void setQName(QName name) {
 123  1502 this.qname = name;
 124    }
 125   
 126  183 public String getText() {
 127  183 final Object contentShadow = content;
 128   
 129  183 if (contentShadow instanceof List) {
 130  80 return super.getText();
 131    } else {
 132  103 if (contentShadow != null) {
 133  93 return getContentAsText(contentShadow);
 134    } else {
 135  10 return "";
 136    }
 137    }
 138    }
 139   
 140  8 public String getStringValue() {
 141  8 final Object contentShadow = content;
 142   
 143  8 if (contentShadow instanceof List) {
 144  6 List list = (List) contentShadow;
 145   
 146  6 int size = list.size();
 147   
 148  6 if (size > 0) {
 149  6 if (size == 1) {
 150    // optimised to avoid StringBuffer creation
 151  4 return getContentAsStringValue(list.get(0));
 152    } else {
 153  2 StringBuffer buffer = new StringBuffer();
 154   
 155  2 for (int i = 0; i < size; i++) {
 156  9 Object node = list.get(i);
 157   
 158  9 String string = getContentAsStringValue(node);
 159   
 160  9 if (string.length() > 0) {
 161  7 if (USE_STRINGVALUE_SEPARATOR) {
 162  0 if (buffer.length() > 0) {
 163  0 buffer.append(' ');
 164    }
 165    }
 166   
 167  7 buffer.append(string);
 168    }
 169    }
 170   
 171  2 return buffer.toString();
 172    }
 173    }
 174    } else {
 175  2 if (contentShadow != null) {
 176  0 return getContentAsStringValue(contentShadow);
 177    }
 178    }
 179   
 180  2 return "";
 181    }
 182   
 183  129 public Object clone() {
 184  129 DefaultElement answer = (DefaultElement) super.clone();
 185   
 186  129 if (answer != this) {
 187  129 answer.content = null;
 188   
 189  129 answer.attributes = null;
 190   
 191  129 answer.appendAttributes(this);
 192   
 193  129 answer.appendContent(this);
 194    }
 195   
 196  129 return answer;
 197    }
 198   
 199  8764 public Namespace getNamespaceForPrefix(String prefix) {
 200  8764 if (prefix == null) {
 201  9 prefix = "";
 202    }
 203   
 204  8764 if (prefix.equals(getNamespacePrefix())) {
 205  3721 return getNamespace();
 206  5043 } else if (prefix.equals("xml")) {
 207  0 return Namespace.XML_NAMESPACE;
 208    } else {
 209  5043 final Object contentShadow = content;
 210   
 211  5043 if (contentShadow instanceof List) {
 212  5040 List list = (List) contentShadow;
 213   
 214  5040 int size = list.size();
 215   
 216  5040 for (int i = 0; i < size; i++) {
 217  5100 Object object = list.get(i);
 218   
 219  5100 if (object instanceof Namespace) {
 220  5055 Namespace namespace = (Namespace) object;
 221   
 222  5055 if (prefix.equals(namespace.getPrefix())) {
 223  5023 return namespace;
 224    }
 225    }
 226    }
 227  3 } else if (contentShadow instanceof Namespace) {
 228  0 Namespace namespace = (Namespace) contentShadow;
 229   
 230  0 if (prefix.equals(namespace.getPrefix())) {
 231  0 return namespace;
 232    }
 233    }
 234    }
 235   
 236  20 Element parent = getParent();
 237   
 238  20 if (parent != null) {
 239  19 Namespace answer = parent.getNamespaceForPrefix(prefix);
 240   
 241  19 if (answer != null) {
 242  19 return answer;
 243    }
 244    }
 245   
 246  1 if ((prefix == null) || (prefix.length() <= 0)) {
 247  0 return Namespace.NO_NAMESPACE;
 248    }
 249   
 250  1 return null;
 251    }
 252   
 253  9 public Namespace getNamespaceForURI(String uri) {
 254  9 if ((uri == null) || (uri.length() <= 0)) {
 255  0 return Namespace.NO_NAMESPACE;
 256  9 } else if (uri.equals(getNamespaceURI())) {
 257  0 return getNamespace();
 258    } else {
 259  9 final Object contentShadow = content;
 260   
 261  9 if (contentShadow instanceof List) {
 262  9 List list = (List) contentShadow;
 263   
 264  9 int size = list.size();
 265   
 266  9 for (int i = 0; i < size; i++) {
 267  21 Object object = list.get(i);
 268   
 269  21 if (object instanceof Namespace) {
 270  12 Namespace namespace = (Namespace) object;
 271   
 272  12 if (uri.equals(namespace.getURI())) {
 273  6 return namespace;
 274    }
 275    }
 276    }
 277  0 } else if (contentShadow instanceof Namespace) {
 278  0 Namespace namespace = (Namespace) contentShadow;
 279   
 280  0 if (uri.equals(namespace.getURI())) {
 281  0 return namespace;
 282    }
 283    }
 284   
 285  3 Element parent = getParent();
 286   
 287  3 if (parent != null) {
 288  3 return parent.getNamespaceForURI(uri);
 289    }
 290   
 291  0 return null;
 292    }
 293    }
 294   
 295  9903 public List declaredNamespaces() {
 296  9903 BackedList answer = createResultList();
 297   
 298    // if (getNamespaceURI().length() > 0) {
 299    //
 300    // answer.addLocal(getNamespace());
 301    //
 302    // }
 303  9903 final Object contentShadow = content;
 304   
 305  9903 if (contentShadow instanceof List) {
 306  9903 List list = (List) contentShadow;
 307   
 308  9903 int size = list.size();
 309   
 310  9903 for (int i = 0; i < size; i++) {
 311  31929 Object object = list.get(i);
 312   
 313  31929 if (object instanceof Namespace) {
 314  821 answer.addLocal(object);
 315    }
 316    }
 317    } else {
 318  0 if (contentShadow instanceof Namespace) {
 319  0 answer.addLocal(contentShadow);
 320    }
 321    }
 322   
 323  9903 return answer;
 324    }
 325   
 326  15 public List additionalNamespaces() {
 327  15 final Object contentShadow = content;
 328   
 329  15 if (contentShadow instanceof List) {
 330  13 List list = (List) contentShadow;
 331   
 332  13 int size = list.size();
 333   
 334  13 BackedList answer = createResultList();
 335   
 336  13 for (int i = 0; i < size; i++) {
 337  89 Object object = list.get(i);
 338   
 339  89 if (object instanceof Namespace) {
 340  25 Namespace namespace = (Namespace) object;
 341   
 342  25 if (!namespace.equals(getNamespace())) {
 343  13 answer.addLocal(namespace);
 344    }
 345    }
 346    }
 347   
 348  13 return answer;
 349    } else {
 350  2 if (contentShadow instanceof Namespace) {
 351  1 Namespace namespace = (Namespace) contentShadow;
 352   
 353  1 if (namespace.equals(getNamespace())) {
 354  1 return createEmptyList();
 355    }
 356   
 357  0 return createSingleResultList(namespace);
 358    } else {
 359  1 return createEmptyList();
 360    }
 361    }
 362    }
 363   
 364  0 public List additionalNamespaces(String defaultNamespaceURI) {
 365  0 final Object contentShadow = content;
 366   
 367  0 if (contentShadow instanceof List) {
 368  0 List list = (List) contentShadow;
 369   
 370  0 BackedList answer = createResultList();
 371   
 372  0 int size = list.size();
 373   
 374  0 for (int i = 0; i < size; i++) {
 375  0 Object object = list.get(i);
 376   
 377  0 if (object instanceof Namespace) {
 378  0 Namespace namespace = (Namespace) object;
 379   
 380  0 if (!defaultNamespaceURI.equals(namespace.getURI())) {
 381  0 answer.addLocal(namespace);
 382    }
 383    }
 384    }
 385   
 386  0 return answer;
 387    } else {
 388  0 if (contentShadow instanceof Namespace) {
 389  0 Namespace namespace = (Namespace) contentShadow;
 390   
 391  0 if (!defaultNamespaceURI.equals(namespace.getURI())) {
 392  0 return createSingleResultList(namespace);
 393    }
 394    }
 395    }
 396   
 397  0 return createEmptyList();
 398    }
 399   
 400    // Processing instruction API
 401  0 public List processingInstructions() {
 402  0 final Object contentShadow = content;
 403   
 404  0 if (contentShadow instanceof List) {
 405  0 List list = (List) contentShadow;
 406   
 407  0 BackedList answer = createResultList();
 408   
 409  0 int size = list.size();
 410   
 411  0 for (int i = 0; i < size; i++) {
 412  0 Object object = list.get(i);
 413   
 414  0 if (object instanceof ProcessingInstruction) {
 415  0 answer.addLocal(object);
 416    }
 417    }
 418   
 419  0 return answer;
 420    } else {
 421  0 if (contentShadow instanceof ProcessingInstruction) {
 422  0 return createSingleResultList(contentShadow);
 423    }
 424   
 425  0 return createEmptyList();
 426    }
 427    }
 428   
 429  0 public List processingInstructions(String target) {
 430  0 final Object shadow = content;
 431   
 432  0 if (shadow instanceof List) {
 433  0 List list = (List) shadow;
 434   
 435  0 BackedList answer = createResultList();
 436   
 437  0 int size = list.size();
 438   
 439  0 for (int i = 0; i < size; i++) {
 440  0 Object object = list.get(i);
 441   
 442  0 if (object instanceof ProcessingInstruction) {
 443  0 ProcessingInstruction pi = (ProcessingInstruction) object;
 444   
 445  0 if (target.equals(pi.getName())) {
 446  0 answer.addLocal(pi);
 447    }
 448    }
 449    }
 450   
 451  0 return answer;
 452    } else {
 453  0 if (shadow instanceof ProcessingInstruction) {
 454  0 ProcessingInstruction pi = (ProcessingInstruction) shadow;
 455   
 456  0 if (target.equals(pi.getName())) {
 457  0 return createSingleResultList(pi);
 458    }
 459    }
 460   
 461  0 return createEmptyList();
 462    }
 463    }
 464   
 465  0 public ProcessingInstruction processingInstruction(String target) {
 466  0 final Object shadow = content;
 467   
 468  0 if (shadow instanceof List) {
 469  0 List list = (List) shadow;
 470   
 471  0 int size = list.size();
 472   
 473  0 for (int i = 0; i < size; i++) {
 474  0 Object object = list.get(i);
 475   
 476  0 if (object instanceof ProcessingInstruction) {
 477  0 ProcessingInstruction pi = (ProcessingInstruction) object;
 478   
 479  0 if (target.equals(pi.getName())) {
 480  0 return pi;
 481    }
 482    }
 483    }
 484    } else {
 485  0 if (shadow instanceof ProcessingInstruction) {
 486  0 ProcessingInstruction pi = (ProcessingInstruction) shadow;
 487   
 488  0 if (target.equals(pi.getName())) {
 489  0 return pi;
 490    }
 491    }
 492    }
 493   
 494  0 return null;
 495    }
 496   
 497  0 public boolean removeProcessingInstruction(String target) {
 498  0 final Object shadow = content;
 499   
 500  0 if (shadow instanceof List) {
 501  0 List list = (List) shadow;
 502   
 503  0 for (Iterator iter = list.iterator(); iter.hasNext();) {
 504  0 Object object = iter.next();
 505   
 506  0 if (object instanceof ProcessingInstruction) {
 507  0 ProcessingInstruction pi = (ProcessingInstruction) object;
 508   
 509  0 if (target.equals(pi.getName())) {
 510  0 iter.remove();
 511   
 512  0 return true;
 513    }
 514    }
 515    }
 516    } else {
 517  0 if (shadow instanceof ProcessingInstruction) {
 518  0 ProcessingInstruction pi = (ProcessingInstruction) shadow;
 519   
 520  0 if (target.equals(pi.getName())) {
 521  0 this.content = null;
 522   
 523  0 return true;
 524    }
 525    }
 526    }
 527   
 528  0 return false;
 529    }
 530   
 531  125 public Element element(String name) {
 532  125 final Object contentShadow = content;
 533   
 534  125 if (contentShadow instanceof List) {
 535  30 List list = (List) contentShadow;
 536   
 537  30 int size = list.size();
 538   
 539  82 for (int i = 0; i < size; i++) {
 540  82 Object object = list.get(i);
 541   
 542  82 if (object instanceof Element) {
 543  36 Element element = (Element) object;
 544   
 545  36 if (name.equals(element.getName())) {
 546  30 return element;
 547    }
 548    }
 549    }
 550    } else {
 551  95 if (contentShadow instanceof Element) {
 552  6 Element element = (Element) contentShadow;
 553   
 554  6 if (name.equals(element.getName())) {
 555  6 return element;
 556    }
 557    }
 558    }
 559   
 560  89 return null;
 561    }
 562   
 563  2965 public Element element(QName qName) {
 564  2965 final Object contentShadow = content;
 565   
 566  2965 if (contentShadow instanceof List) {
 567  2705 List list = (List) contentShadow;
 568   
 569  2705 int size = list.size();
 570   
 571  2705 for (int i = 0; i < size; i++) {
 572  21262 Object object = list.get(i);
 573   
 574  21262 if (object instanceof Element) {
 575  11680 Element element = (Element) object;
 576   
 577  11680 if (qName.equals(element.getQName())) {
 578  2290 return element;
 579    }
 580    }
 581    }
 582    } else {
 583  260 if (contentShadow instanceof Element) {
 584  1 Element element = (Element) contentShadow;
 585   
 586  1 if (qName.equals(element.getQName())) {
 587  1 return element;
 588    }
 589    }
 590    }
 591   
 592  674 return null;
 593    }
 594   
 595  0 public Element element(String name, Namespace namespace) {
 596  0 return element(getDocumentFactory().createQName(name, namespace));
 597    }
 598   
 599  2 public void setContent(List content) {
 600  2 contentRemoved();
 601   
 602  2 if (content instanceof ContentListFacade) {
 603  2 content = ((ContentListFacade) content).getBackingList();
 604    }
 605   
 606  2 if (content == null) {
 607  0 this.content = null;
 608    } else {
 609  2 int size = content.size();
 610   
 611  2 List newContent = createContentList(size);
 612   
 613  2 for (int i = 0; i < size; i++) {
 614  7 Object object = content.get(i);
 615   
 616  7 if (object instanceof Node) {
 617  7 Node node = (Node) object;
 618  7 Element parent = node.getParent();
 619   
 620  7 if ((parent != null) && (parent != this)) {
 621  2 node = (Node) node.clone();
 622    }
 623   
 624  7 newContent.add(node);
 625  7 childAdded(node);
 626  0 } else if (object != null) {
 627  0 String text = object.toString();
 628  0 Node node = getDocumentFactory().createText(text);
 629  0 newContent.add(node);
 630  0 childAdded(node);
 631    }
 632    }
 633   
 634  2 this.content = newContent;
 635    }
 636    }
 637   
 638  0 public void clearContent() {
 639  0 if (content != null) {
 640  0 contentRemoved();
 641   
 642  0 content = null;
 643    }
 644    }
 645   
 646  355275 public Node node(int index) {
 647  355275 if (index >= 0) {
 648  355275 final Object contentShadow = content;
 649  355275 Object node;
 650   
 651  355275 if (contentShadow instanceof List) {
 652  333677 List list = (List) contentShadow;
 653   
 654  333677 if (index >= list.size()) {
 655  0 return null;
 656    }
 657   
 658  333677 node = list.get(index);
 659    } else {
 660  21598 node = (index == 0) ? contentShadow : null;
 661    }
 662   
 663  355275 if (node != null) {
 664  355275 if (node instanceof Node) {
 665  355275 return (Node) node;
 666    } else {
 667  0 return new DefaultText(node.toString());
 668    }
 669    }
 670    }
 671   
 672  0 return null;
 673    }
 674   
 675  0 public int indexOf(Node node) {
 676  0 final Object contentShadow = content;
 677   
 678  0 if (contentShadow instanceof List) {
 679  0 List list = (List) contentShadow;
 680   
 681  0 return list.indexOf(node);
 682    } else {
 683  0 if ((contentShadow != null) && contentShadow.equals(node)) {
 684  0 return 0;
 685    } else {
 686  0 return -1;
 687    }
 688    }
 689    }
 690   
 691  125606 public int nodeCount() {
 692  125606 final Object contentShadow = content;
 693   
 694  125606 if (contentShadow instanceof List) {
 695  103856 List list = (List) contentShadow;
 696   
 697  103856 return list.size();
 698    } else {
 699  21750 return (contentShadow != null) ? 1 : 0;
 700    }
 701    }
 702   
 703  94704 public Iterator nodeIterator() {
 704  94704 final Object contentShadow = content;
 705   
 706  94704 if (contentShadow instanceof List) {
 707  33208 List list = (List) contentShadow;
 708   
 709  33208 return list.iterator();
 710    } else {
 711  61496 if (contentShadow != null) {
 712  61120 return createSingleIterator(contentShadow);
 713    } else {
 714  376 return EMPTY_ITERATOR;
 715    }
 716    }
 717    }
 718   
 719  109 public List attributes() {
 720  109 return new ContentListFacade(this, attributeList());
 721    }
 722   
 723  0 public void setAttributes(List attributes) {
 724  0 if (attributes instanceof ContentListFacade) {
 725  0 attributes = ((ContentListFacade) attributes).getBackingList();
 726    }
 727   
 728  0 this.attributes = attributes;
 729    }
 730   
 731  5028 public Iterator attributeIterator() {
 732  5028 final Object attributesShadow = this.attributes;
 733   
 734  5028 if (attributesShadow instanceof List) {
 735  2596 List list = (List) attributesShadow;
 736   
 737  2596 return list.iterator();
 738  2432 } else if (attributesShadow != null) {
 739  998 return createSingleIterator(attributesShadow);
 740    } else {
 741  1434 return EMPTY_ITERATOR;
 742    }
 743    }
 744   
 745  24324 public Attribute attribute(int index) {
 746  24324 final Object attributesShadow = this.attributes;
 747   
 748  24324 if (attributesShadow instanceof List) {
 749  22129 List list = (List) attributesShadow;
 750   
 751  22129 return (Attribute) list.get(index);
 752  2195 } else if ((attributesShadow != null) && (index == 0)) {
 753  2195 return (Attribute) attributesShadow;
 754    } else {
 755  0 return null;
 756    }
 757    }
 758   
 759  110652 public int attributeCount() {
 760  110652 final Object attributesShadow = this.attributes;
 761   
 762  110652 if (attributesShadow instanceof List) {
 763  65626 List list = (List) attributesShadow;
 764   
 765  65626 return list.size();
 766    } else {
 767  45026 return (attributesShadow != null) ? 1 : 0;
 768    }
 769    }
 770   
 771  3958 public Attribute attribute(String name) {
 772  3958 final Object attributesShadow = this.attributes;
 773   
 774  3958 if (attributesShadow instanceof List) {
 775  1292 List list = (List) attributesShadow;
 776   
 777  1292 int size = list.size();
 778   
 779  1292 for (int i = 0; i < size; i++) {
 780  2294 Attribute attribute = (Attribute) list.get(i);
 781   
 782  2294 if (name.equals(attribute.getName())) {
 783  974 return attribute;
 784    }
 785    }
 786  2666 } else if (attributesShadow != null) {
 787  1729 Attribute attribute = (Attribute) attributesShadow;
 788   
 789  1729 if (name.equals(attribute.getName())) {
 790  575 return attribute;
 791    }
 792    }
 793   
 794  2409 return null;
 795    }
 796   
 797  20997 public Attribute attribute(QName qName) {
 798  20997 final Object attributesShadow = this.attributes;
 799   
 800  20997 if (attributesShadow instanceof List) {
 801  17846 List list = (List) attributesShadow;
 802   
 803  17846 int size = list.size();
 804   
 805  17846 for (int i = 0; i < size; i++) {
 806  20862 Attribute attribute = (Attribute) list.get(i);
 807   
 808  20862 if (qName.equals(attribute.getQName())) {
 809  17696 return attribute;
 810    }
 811    }
 812  3151 } else if (attributesShadow != null) {
 813  618 Attribute attribute = (Attribute) attributesShadow;
 814   
 815  618 if (qName.equals(attribute.getQName())) {
 816  231 return attribute;
 817    }
 818    }
 819   
 820  3070 return null;
 821    }
 822   
 823  0 public Attribute attribute(String name, Namespace namespace) {
 824  0 return attribute(getDocumentFactory().createQName(name, namespace));
 825    }
 826   
 827  10743 public void add(Attribute attribute) {
 828  10743 if (attribute.getParent() != null) {
 829  0 String message = "The Attribute already has an existing parent \""
 830    + attribute.getParent().getQualifiedName() + "\"";
 831   
 832  0 throw new IllegalAddException(this, attribute, message);
 833    }
 834   
 835  10743 if (attribute.getValue() == null) {
 836    // try remove a previous attribute with the same
 837    // name since adding an attribute with a null value
 838    // is equivalent to removing it.
 839  2 Attribute oldAttribute = attribute(attribute.getQName());
 840   
 841  2 if (oldAttribute != null) {
 842  1 remove(oldAttribute);
 843    }
 844    } else {
 845  10741 if (attributes == null) {
 846  9433 attributes = attribute;
 847    } else {
 848  1308 attributeList().add(attribute);
 849    }
 850   
 851  10741 childAdded(attribute);
 852    }
 853    }
 854   
 855  6 public boolean remove(Attribute attribute) {
 856  6 boolean answer = false;
 857  6 final Object attributesShadow = this.attributes;
 858   
 859  6 if (attributesShadow instanceof List) {
 860  3 List list = (List) attributesShadow;
 861   
 862  3 answer = list.remove(attribute);
 863   
 864  3 if (!answer) {
 865    // we may have a copy of the attribute
 866  0 Attribute copy = attribute(attribute.getQName());
 867   
 868  0 if (copy != null) {
 869  0 list.remove(copy);
 870   
 871  0 answer = true;
 872    }
 873    }
 874  3 } else if (attributesShadow != null) {
 875  3 if (attribute.equals(attributesShadow)) {
 876  3 this.attributes = null;
 877   
 878  3 answer = true;
 879    } else {
 880    // we may have a copy of the attribute
 881  0 Attribute other = (Attribute) attributesShadow;
 882   
 883  0 if (attribute.getQName().equals(other.getQName())) {
 884  0 attributes = null;
 885   
 886  0 answer = true;
 887    }
 888    }
 889    }
 890   
 891  6 if (answer) {
 892  6 childRemoved(attribute);
 893    }
 894   
 895  6 return answer;
 896    }
 897   
 898    // Implementation methods
 899    // -------------------------------------------------------------------------
 900  219990 protected void addNewNode(Node node) {
 901  219990 final Object contentShadow = content;
 902   
 903  219990 if (contentShadow == null) {
 904  92043 this.content = node;
 905    } else {
 906  127947 if (contentShadow instanceof List) {
 907  103858 List list = (List) contentShadow;
 908   
 909  103858 list.add(node);
 910    } else {
 911  24089 List list = createContentList();
 912   
 913  24089 list.add(contentShadow);
 914   
 915  24089 list.add(node);
 916   
 917  24089 this.content = list;
 918    }
 919    }
 920   
 921  219990 childAdded(node);
 922    }
 923   
 924  13545 protected boolean removeNode(Node node) {
 925  13545 boolean answer = false;
 926  13545 final Object contentShadow = content;
 927   
 928  13545 if (contentShadow != null) {
 929  13545 if (contentShadow == node) {
 930  1 this.content = null;
 931   
 932  1 answer = true;
 933  13544 } else if (contentShadow instanceof List) {
 934  13544 List list = (List) contentShadow;
 935   
 936  13544 answer = list.remove(node);
 937    }
 938    }
 939   
 940  13545 if (answer) {
 941  13545 childRemoved(node);
 942    }
 943   
 944  13545 return answer;
 945    }
 946   
 947  88171 protected List contentList() {
 948  88171 final Object contentShadow = content;
 949   
 950  88171 if (contentShadow instanceof List) {
 951  61297 return (List) contentShadow;
 952    } else {
 953  26874 List list = createContentList();
 954   
 955  26874 if (contentShadow != null) {
 956  23679 list.add(contentShadow);
 957    }
 958   
 959  26874 this.content = list;
 960   
 961  26874 return list;
 962    }
 963    }
 964   
 965  87124 protected List attributeList() {
 966  87124 final Object attributesShadow = this.attributes;
 967   
 968  87124 if (attributesShadow instanceof List) {
 969  58366 return (List) attributesShadow;
 970  28758 } else if (attributesShadow != null) {
 971  9093 List list = createAttributeList();
 972   
 973  9093 list.add(attributesShadow);
 974   
 975  9093 this.attributes = list;
 976   
 977  9093 return list;
 978    } else {
 979  19665 List list = createAttributeList();
 980   
 981  19665 this.attributes = list;
 982   
 983  19665 return list;
 984    }
 985    }
 986   
 987  1618 protected List attributeList(int size) {
 988  1618 final Object attributesShadow = this.attributes;
 989   
 990  1618 if (attributesShadow instanceof List) {
 991  0 return (List) attributesShadow;
 992  1618 } else if (attributesShadow != null) {
 993  0 List list = createAttributeList(size);
 994   
 995  0 list.add(attributesShadow);
 996   
 997  0 this.attributes = list;
 998   
 999  0 return list;
 1000    } else {
 1001  1618 List list = createAttributeList(size);
 1002   
 1003  1618 this.attributes = list;
 1004   
 1005  1618 return list;
 1006    }
 1007    }
 1008   
 1009  2 protected void setAttributeList(List attributeList) {
 1010  2 this.attributes = attributeList;
 1011    }
 1012   
 1013  228999 protected DocumentFactory getDocumentFactory() {
 1014  228999 DocumentFactory factory = qname.getDocumentFactory();
 1015   
 1016  228999 return (factory != null) ? factory : DOCUMENT_FACTORY;
 1017    }
 1018    }
 1019   
 1020    /*
 1021    * Redistribution and use of this software and associated documentation
 1022    * ("Software"), with or without modification, are permitted provided that the
 1023    * following conditions are met:
 1024    *
 1025    * 1. Redistributions of source code must retain copyright statements and
 1026    * notices. Redistributions must also contain a copy of this document.
 1027    *
 1028    * 2. Redistributions in binary form must reproduce the above copyright notice,
 1029    * this list of conditions and the following disclaimer in the documentation
 1030    * and/or other materials provided with the distribution.
 1031    *
 1032    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 1033    * from this Software without prior written permission of MetaStuff, Ltd. For
 1034    * written permission, please contact dom4j-info@metastuff.com.
 1035    *
 1036    * 4. Products derived from this Software may not be called "DOM4J" nor may
 1037    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 1038    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 1039    *
 1040    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 1041    *
 1042    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 1043    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 1044    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 1045    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 1046    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 1047    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 1048    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 1049    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 1050    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 1051    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 1052    * POSSIBILITY OF SUCH DAMAGE.
 1053    *
 1054    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 1055    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/AbstractCharacterData.html0000644000175000017500000005746010242117734024126 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 81   Methods: 4
NCLOC: 21   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
AbstractCharacterData.java 0% 20% 50% 23,1%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import org.dom4j.CharacterData;
 11    import org.dom4j.Element;
 12   
 13    /**
 14    * <p>
 15    * <code>AbstractCharacterData</code> is an abstract base class for tree
 16    * implementors to use for implementation inheritence.
 17    * </p>
 18    *
 19    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 20    * @version $Revision: 1.12 $
 21    */
 22    public abstract class AbstractCharacterData extends AbstractNode implements
 23    CharacterData {
 24  122383 public AbstractCharacterData() {
 25    }
 26   
 27  0 public String getPath(Element context) {
 28  0 Element parent = getParent();
 29   
 30  0 return ((parent != null) && (parent != context)) ? (parent
 31    .getPath(context) + "/text()") : "text()";
 32    }
 33   
 34  0 public String getUniquePath(Element context) {
 35  0 Element parent = getParent();
 36   
 37  0 return ((parent != null) && (parent != context)) ? (parent
 38    .getUniquePath(context) + "/text()") : "text()";
 39    }
 40   
 41  12026 public void appendText(String text) {
 42  12026 setText(getText() + text);
 43    }
 44    }
 45   
 46    /*
 47    * Redistribution and use of this software and associated documentation
 48    * ("Software"), with or without modification, are permitted provided that the
 49    * following conditions are met:
 50    *
 51    * 1. Redistributions of source code must retain copyright statements and
 52    * notices. Redistributions must also contain a copy of this document.
 53    *
 54    * 2. Redistributions in binary form must reproduce the above copyright notice,
 55    * this list of conditions and the following disclaimer in the documentation
 56    * and/or other materials provided with the distribution.
 57    *
 58    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 59    * from this Software without prior written permission of MetaStuff, Ltd. For
 60    * written permission, please contact dom4j-info@metastuff.com.
 61    *
 62    * 4. Products derived from this Software may not be called "DOM4J" nor may
 63    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 64    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 65    *
 66    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 67    *
 68    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 69    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 70    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 71    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 72    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 73    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 74    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 75    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 76    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 77    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 78    * POSSIBILITY OF SUCH DAMAGE.
 79    *
 80    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 81    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/SingleIterator.html0000644000175000017500000006046210242117637022705 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 83   Methods: 4
NCLOC: 22   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
SingleIterator.java - 85,7% 75% 81,8%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.util.Iterator;
 11   
 12    /**
 13    * <p>
 14    * <code>SingleIterator</code> is an {@link Iterator}over a single object
 15    * instance.
 16    * </p>
 17    *
 18    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 19    * @version $Revision: 1.9 $
 20    */
 21    public class SingleIterator implements Iterator {
 22    private boolean first = true;
 23   
 24    private Object object;
 25   
 26  62118 public SingleIterator(Object object) {
 27  62118 this.object = object;
 28    }
 29   
 30  185329 public boolean hasNext() {
 31  185329 return first;
 32    }
 33   
 34  62118 public Object next() {
 35  62118 Object answer = object;
 36  62118 object = null;
 37  62118 first = false;
 38   
 39  62118 return answer;
 40    }
 41   
 42  0 public void remove() {
 43  0 throw new UnsupportedOperationException("remove() is not supported by "
 44    + "this iterator");
 45    }
 46    }
 47   
 48    /*
 49    * Redistribution and use of this software and associated documentation
 50    * ("Software"), with or without modification, are permitted provided that the
 51    * following conditions are met:
 52    *
 53    * 1. Redistributions of source code must retain copyright statements and
 54    * notices. Redistributions must also contain a copy of this document.
 55    *
 56    * 2. Redistributions in binary form must reproduce the above copyright notice,
 57    * this list of conditions and the following disclaimer in the documentation
 58    * and/or other materials provided with the distribution.
 59    *
 60    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 61    * from this Software without prior written permission of MetaStuff, Ltd. For
 62    * written permission, please contact dom4j-info@metastuff.com.
 63    *
 64    * 4. Products derived from this Software may not be called "DOM4J" nor may
 65    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 66    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 67    *
 68    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 69    *
 70    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 71    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 72    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 73    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 74    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 75    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 76    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 77    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 78    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 79    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 80    * POSSIBILITY OF SUCH DAMAGE.
 81    *
 82    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 83    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/FilterIterator.html0000644000175000017500000010727710242117706022714 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 129   Methods: 5
NCLOC: 42   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
FilterIterator.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.util.Iterator;
 11    import java.util.NoSuchElementException;
 12   
 13    /**
 14    * <p>
 15    * <code>FilterIterator</code> is an abstract base class which is useful for
 16    * implementors of {@link Iterator}which filter an existing iterator.
 17    * </p>
 18    *
 19    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 20    * @version $Revision: 1.10 $
 21    *
 22    * @deprecated THIS CLASS WILL BE REMOVED IN dom4j-1.6 !!
 23    */
 24    public abstract class FilterIterator implements Iterator {
 25    protected Iterator proxy;
 26   
 27    private Object next;
 28   
 29    private boolean first = true;
 30   
 31  0 public FilterIterator(Iterator proxy) {
 32  0 this.proxy = proxy;
 33    }
 34   
 35  0 public boolean hasNext() {
 36  0 if (first) {
 37  0 next = findNext();
 38  0 first = false;
 39    }
 40   
 41  0 return next != null;
 42    }
 43   
 44  0 public Object next() throws NoSuchElementException {
 45  0 if (!hasNext()) {
 46  0 throw new NoSuchElementException();
 47    }
 48   
 49  0 Object answer = this.next;
 50  0 this.next = findNext();
 51   
 52  0 return answer;
 53    }
 54   
 55    /**
 56    * Always throws UnsupportedOperationException as this class does look-ahead
 57    * with its internal iterator.
 58    *
 59    * @throws UnsupportedOperationException
 60    * always
 61    */
 62  0 public void remove() {
 63  0 throw new UnsupportedOperationException();
 64    }
 65   
 66    /**
 67    * Filter method to perform some matching on the given element.
 68    *
 69    * @param element
 70    * DOCUMENT ME!
 71    *
 72    * @return true if the given element matches the filter and should be appear
 73    * in the iteration
 74    */
 75    protected abstract boolean matches(Object element);
 76   
 77  0 protected Object findNext() {
 78  0 if (proxy != null) {
 79  0 while (proxy.hasNext()) {
 80  0 Object nextObject = proxy.next();
 81   
 82  0 if ((nextObject != null) && matches(nextObject)) {
 83  0 return nextObject;
 84    }
 85    }
 86   
 87  0 proxy = null;
 88    }
 89   
 90  0 return null;
 91    }
 92    }
 93   
 94    /*
 95    * Redistribution and use of this software and associated documentation
 96    * ("Software"), with or without modification, are permitted provided that the
 97    * following conditions are met:
 98    *
 99    * 1. Redistributions of source code must retain copyright statements and
 100    * notices. Redistributions must also contain a copy of this document.
 101    *
 102    * 2. Redistributions in binary form must reproduce the above copyright notice,
 103    * this list of conditions and the following disclaimer in the documentation
 104    * and/or other materials provided with the distribution.
 105    *
 106    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 107    * from this Software without prior written permission of MetaStuff, Ltd. For
 108    * written permission, please contact dom4j-info@metastuff.com.
 109    *
 110    * 4. Products derived from this Software may not be called "DOM4J" nor may
 111    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 112    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 113    *
 114    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 115    *
 116    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 117    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 118    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 119    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 120    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 121    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 122    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 123    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 124    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 125    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 126    * POSSIBILITY OF SUCH DAMAGE.
 127    *
 128    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 129    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/NamespaceStack.html0000644000175000017500000041523610242117705022633 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 504   Methods: 25
NCLOC: 229   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
NamespaceStack.java 77,9% 88% 88% 84,9%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.util.ArrayList;
 11    import java.util.HashMap;
 12    import java.util.Map;
 13   
 14    import org.dom4j.DocumentFactory;
 15    import org.dom4j.Namespace;
 16    import org.dom4j.QName;
 17   
 18    /**
 19    * NamespaceStack implements a stack of namespaces and optionally maintains a
 20    * cache of all the fully qualified names (<code>QName</code>) which are in
 21    * scope. This is useful when building or navigating a <i>dom4j </i> document.
 22    *
 23    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 24    * @version $Revision: 1.13 $
 25    */
 26    public class NamespaceStack {
 27    /** The factory used to create new <code>Namespace</code> instances */
 28    private DocumentFactory documentFactory;
 29   
 30    /** The Stack of namespaces */
 31    private ArrayList namespaceStack = new ArrayList();
 32   
 33    /** The cache of qualifiedNames to QNames per namespace context */
 34    private ArrayList namespaceCacheList = new ArrayList();
 35   
 36    /**
 37    * A cache of current namespace context cache of mapping from qualifiedName
 38    * to QName
 39    */
 40    private Map currentNamespaceCache;
 41   
 42    /**
 43    * A cache of mapping from qualifiedName to QName before any namespaces are
 44    * declared
 45    */
 46    private Map rootNamespaceCache = new HashMap();
 47   
 48    /** Caches the default namespace defined via xmlns="" */
 49    private Namespace defaultNamespace;
 50   
 51  2198 public NamespaceStack() {
 52  2198 this.documentFactory = DocumentFactory.getInstance();
 53    }
 54   
 55  5831 public NamespaceStack(DocumentFactory documentFactory) {
 56  5831 this.documentFactory = documentFactory;
 57    }
 58   
 59    /**
 60    * Pushes the given namespace onto the stack so that its prefix becomes
 61    * available.
 62    *
 63    * @param namespace
 64    * is the <code>Namespace</code> to add to the stack.
 65    */
 66  8825 public void push(Namespace namespace) {
 67  8825 namespaceStack.add(namespace);
 68  8825 namespaceCacheList.add(null);
 69  8825 currentNamespaceCache = null;
 70   
 71  8825 String prefix = namespace.getPrefix();
 72   
 73  8825 if ((prefix == null) || (prefix.length() == 0)) {
 74  2374 defaultNamespace = namespace;
 75    }
 76    }
 77   
 78    /**
 79    * Pops the most recently used <code>Namespace</code> from the stack
 80    *
 81    * @return Namespace popped from the stack
 82    */
 83  744 public Namespace pop() {
 84  744 return remove(namespaceStack.size() - 1);
 85    }
 86   
 87    /**
 88    * DOCUMENT ME!
 89    *
 90    * @return the number of namespaces on the stackce stack.
 91    */
 92  163293 public int size() {
 93  163293 return namespaceStack.size();
 94    }
 95   
 96    /**
 97    * Clears the stack
 98    */
 99  11678 public void clear() {
 100  11678 namespaceStack.clear();
 101  11678 namespaceCacheList.clear();
 102  11678 rootNamespaceCache.clear();
 103  11678 currentNamespaceCache = null;
 104    }
 105   
 106    /**
 107    * DOCUMENT ME!
 108    *
 109    * @param index
 110    * DOCUMENT ME!
 111    *
 112    * @return the namespace at the specified index on the stack
 113    */
 114  5884 public Namespace getNamespace(int index) {
 115  5884 return (Namespace) namespaceStack.get(index);
 116    }
 117   
 118    /**
 119    * DOCUMENT ME!
 120    *
 121    * @param prefix
 122    * DOCUMENT ME!
 123    *
 124    * @return the namespace for the given prefix or null if it could not be
 125    * found.
 126    */
 127  2140 public Namespace getNamespaceForPrefix(String prefix) {
 128  2140 if (prefix == null) {
 129  0 prefix = "";
 130    }
 131   
 132  2140 for (int i = namespaceStack.size() - 1; i >= 0; i--) {
 133  2767 Namespace namespace = (Namespace) namespaceStack.get(i);
 134   
 135  2767 if (prefix.equals(namespace.getPrefix())) {
 136  1532 return namespace;
 137    }
 138    }
 139   
 140  608 return null;
 141    }
 142   
 143    /**
 144    * DOCUMENT ME!
 145    *
 146    * @param prefix
 147    * DOCUMENT ME!
 148    *
 149    * @return the URI for the given prefix or null if it could not be found.
 150    */
 151  14 public String getURI(String prefix) {
 152  14 Namespace namespace = getNamespaceForPrefix(prefix);
 153   
 154  14 return (namespace != null) ? namespace.getURI() : null;
 155    }
 156   
 157    /**
 158    * DOCUMENT ME!
 159    *
 160    * @param namespace
 161    * DOCUMENT ME!
 162    *
 163    * @return true if the given prefix is in the stack.
 164    */
 165  20698 public boolean contains(Namespace namespace) {
 166  20698 String prefix = namespace.getPrefix();
 167  20698 Namespace current = null;
 168   
 169  20698 if ((prefix == null) || (prefix.length() == 0)) {
 170  18575 current = getDefaultNamespace();
 171    } else {
 172  2123 current = getNamespaceForPrefix(prefix);
 173    }
 174   
 175  20698 if (current == null) {
 176  622 return false;
 177    }
 178   
 179  20076 if (current == namespace) {
 180  19967 return true;
 181    }
 182   
 183  109 return namespace.getURI().equals(current.getURI());
 184    }
 185   
 186  94617 public QName getQName(String namespaceURI, String localName,
 187    String qualifiedName) {
 188  94577 if (localName == null) {
 189  11 localName = qualifiedName;
 190  94606 } else if (qualifiedName == null) {
 191  0 qualifiedName = localName;
 192    }
 193   
 194  94617 if (namespaceURI == null) {
 195  7455 namespaceURI = "";
 196    }
 197   
 198  94577 String prefix = "";
 199  94617 int index = qualifiedName.indexOf(":");
 200   
 201  94617 if (index > 0) {
 202  13475 prefix = qualifiedName.substring(0, index);
 203   
 204  13475 if (localName.trim().length() == 0) {
 205  0 localName = qualifiedName.substring(index + 1);
 206    }
 207  81142 } else if (localName.trim().length() == 0) {
 208  0 localName = qualifiedName;
 209    }
 210   
 211  94617 Namespace namespace = createNamespace(prefix, namespaceURI);
 212   
 213  94617 return pushQName(localName, qualifiedName, namespace, prefix);
 214    }
 215   
 216  10455 public QName getAttributeQName(String namespaceURI, String localName,
 217    String qualifiedName) {
 218  10455 if (qualifiedName == null) {
 219  0 qualifiedName = localName;
 220    }
 221   
 222  10455 Map map = getNamespaceCache();
 223  10455 QName answer = (QName) map.get(qualifiedName);
 224   
 225  10455 if (answer != null) {
 226  9424 return answer;
 227    }
 228   
 229  1031 if (localName == null) {
 230  0 localName = qualifiedName;
 231    }
 232   
 233  1031 if (namespaceURI == null) {
 234  0 namespaceURI = "";
 235    }
 236   
 237  1031 Namespace namespace = null;
 238  1031 String prefix = "";
 239  1031 int index = qualifiedName.indexOf(":");
 240   
 241  1031 if (index > 0) {
 242  99 prefix = qualifiedName.substring(0, index);
 243  99 namespace = createNamespace(prefix, namespaceURI);
 244   
 245  99 if (localName.trim().length() == 0) {
 246  0 localName = qualifiedName.substring(index + 1);
 247    }
 248    } else {
 249    // attributes with no prefix have no namespace
 250  932 namespace = Namespace.NO_NAMESPACE;
 251   
 252  932 if (localName.trim().length() == 0) {
 253  0 localName = qualifiedName;
 254    }
 255    }
 256   
 257  1031 answer = pushQName(localName, qualifiedName, namespace, prefix);
 258  1031 map.put(qualifiedName, answer);
 259   
 260  1031 return answer;
 261    }
 262   
 263    /**
 264    * Adds a namepace to the stack with the given prefix and URI
 265    *
 266    * @param prefix
 267    * DOCUMENT ME!
 268    * @param uri
 269    * DOCUMENT ME!
 270    */
 271  5886 public void push(String prefix, String uri) {
 272  5886 if (uri == null) {
 273  0 uri = "";
 274    }
 275   
 276  5886 Namespace namespace = createNamespace(prefix, uri);
 277  5886 push(namespace);
 278    }
 279   
 280    /**
 281    * Adds a new namespace to the stack
 282    *
 283    * @param prefix
 284    * DOCUMENT ME!
 285    * @param uri
 286    * DOCUMENT ME!
 287    *
 288    * @return DOCUMENT ME!
 289    */
 290  52 public Namespace addNamespace(String prefix, String uri) {
 291  52 Namespace namespace = createNamespace(prefix, uri);
 292  52 push(namespace);
 293   
 294  52 return namespace;
 295    }
 296   
 297    /**
 298    * Pops a namepace from the stack with the given prefix and URI
 299    *
 300    * @param prefix
 301    * DOCUMENT ME!
 302    *
 303    * @return DOCUMENT ME!
 304    */
 305  5884 public Namespace pop(String prefix) {
 306  5884 if (prefix == null) {
 307  0 prefix = "";
 308    }
 309   
 310  5884 Namespace namespace = null;
 311   
 312  5986 for (int i = namespaceStack.size() - 1; i >= 0; i--) {
 313  5986 Namespace ns = (Namespace) namespaceStack.get(i);
 314   
 315  5986 if (prefix.equals(ns.getPrefix())) {
 316  5884 remove(i);
 317  5884 namespace = ns;
 318   
 319  5884 break;
 320    }
 321    }
 322   
 323  5884 if (namespace == null) {
 324  0 System.out.println("Warning: missing namespace prefix ignored: "
 325    + prefix);
 326    }
 327   
 328  5884 return namespace;
 329    }
 330   
 331  0 public String toString() {
 332  0 return super.toString() + " Stack: " + namespaceStack.toString();
 333    }
 334   
 335  0 public DocumentFactory getDocumentFactory() {
 336  0 return documentFactory;
 337    }
 338   
 339  0 public void setDocumentFactory(DocumentFactory documentFactory) {
 340  0 this.documentFactory = documentFactory;
 341    }
 342   
 343  18576 public Namespace getDefaultNamespace() {
 344  18576 if (defaultNamespace == null) {
 345  46 defaultNamespace = findDefaultNamespace();
 346    }
 347   
 348  18576 return defaultNamespace;
 349    }
 350   
 351    // Implementation methods
 352    // -------------------------------------------------------------------------
 353   
 354    /**
 355    * Adds the QName to the stack of available QNames
 356    *
 357    * @param localName
 358    * DOCUMENT ME!
 359    * @param qualifiedName
 360    * DOCUMENT ME!
 361    * @param namespace
 362    * DOCUMENT ME!
 363    * @param prefix
 364    * DOCUMENT ME!
 365    *
 366    * @return DOCUMENT ME!
 367    */
 368  95648 protected QName pushQName(String localName, String qualifiedName,
 369    Namespace namespace, String prefix) {
 370  95648 if ((prefix == null) || (prefix.length() == 0)) {
 371  82074 this.defaultNamespace = null;
 372    }
 373   
 374  95648 return createQName(localName, qualifiedName, namespace);
 375    }
 376   
 377    /**
 378    * Factory method to creeate new QName instances. By default this method
 379    * interns the QName
 380    *
 381    * @param localName
 382    * DOCUMENT ME!
 383    * @param qualifiedName
 384    * DOCUMENT ME!
 385    * @param namespace
 386    * DOCUMENT ME!
 387    *
 388    * @return DOCUMENT ME!
 389    */
 390  95648 protected QName createQName(String localName, String qualifiedName,
 391    Namespace namespace) {
 392  95648 return documentFactory.createQName(localName, namespace);
 393    }
 394   
 395    /**
 396    * Factory method to creeate new Namespace instances. By default this method
 397    * interns the Namespace
 398    *
 399    * @param prefix
 400    * DOCUMENT ME!
 401    * @param namespaceURI
 402    * DOCUMENT ME!
 403    *
 404    * @return DOCUMENT ME!
 405    */
 406  100654 protected Namespace createNamespace(String prefix, String namespaceURI) {
 407  100654 return documentFactory.createNamespace(prefix, namespaceURI);
 408    }
 409   
 410    /**
 411    * Attempts to find the current default namespace on the stack right now or
 412    * returns null if one could not be found
 413    *
 414    * @return DOCUMENT ME!
 415    */
 416  46 protected Namespace findDefaultNamespace() {
 417  46 for (int i = namespaceStack.size() - 1; i >= 0; i--) {
 418  91 Namespace namespace = (Namespace) namespaceStack.get(i);
 419   
 420  91 if (namespace != null) {
 421  91 String prefix = namespace.getPrefix();
 422   
 423  91 if ((prefix == null) || (namespace.getPrefix().length() == 0)) {
 424  30 return namespace;
 425    }
 426    }
 427    }
 428   
 429  16 return null;
 430    }
 431   
 432    /**
 433    * Removes the namespace at the given index of the stack
 434    *
 435    * @param index
 436    * DOCUMENT ME!
 437    *
 438    * @return DOCUMENT ME!
 439    */
 440  6628 protected Namespace remove(int index) {
 441  6628 Namespace namespace = (Namespace) namespaceStack.remove(index);
 442  6628 namespaceCacheList.remove(index);
 443  6628 defaultNamespace = null;
 444  6628 currentNamespaceCache = null;
 445   
 446  6628 return namespace;
 447    }
 448   
 449  10455 protected Map getNamespaceCache() {
 450  10455 if (currentNamespaceCache == null) {
 451  320 int index = namespaceStack.size() - 1;
 452   
 453  320 if (index < 0) {
 454  76 currentNamespaceCache = rootNamespaceCache;
 455    } else {
 456  244 currentNamespaceCache = (Map) namespaceCacheList.get(index);
 457   
 458  244 if (currentNamespaceCache == null) {
 459  212 currentNamespaceCache = new HashMap();
 460  212 namespaceCacheList.set(index, currentNamespaceCache);
 461    }
 462    }
 463    }
 464   
 465  10455 return currentNamespaceCache;
 466    }
 467    }
 468   
 469    /*
 470    * Redistribution and use of this software and associated documentation
 471    * ("Software"), with or without modification, are permitted provided that the
 472    * following conditions are met:
 473    *
 474    * 1. Redistributions of source code must retain copyright statements and
 475    * notices. Redistributions must also contain a copy of this document.
 476    *
 477    * 2. Redistributions in binary form must reproduce the above copyright notice,
 478    * this list of conditions and the following disclaimer in the documentation
 479    * and/or other materials provided with the distribution.
 480    *
 481    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 482    * from this Software without prior written permission of MetaStuff, Ltd. For
 483    * written permission, please contact dom4j-info@metastuff.com.
 484    *
 485    * 4. Products derived from this Software may not be called "DOM4J" nor may
 486    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 487    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 488    *
 489    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 490    *
 491    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 492    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 493    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 494    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 495    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 496    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 497    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 498    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 499    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 500    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 501    * POSSIBILITY OF SUCH DAMAGE.
 502    *
 503    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 504    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/DefaultCDATA.html0000644000175000017500000007274710242117556022104 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 105   Methods: 7
NCLOC: 27   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DefaultCDATA.java - 25% 28,6% 26,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import org.dom4j.Element;
 11   
 12    /**
 13    * <p>
 14    * <code>DefaultCDATA</code> is the default CDATA implementation. It is a
 15    * doubly linked node which supports the parent relationship and can be modified
 16    * in place.
 17    * </p>
 18    *
 19    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 20    * @version $Revision: 1.12 $
 21    */
 22    public class DefaultCDATA extends FlyweightCDATA {
 23    /** The parent of this node */
 24    private Element parent;
 25   
 26    /**
 27    * DOCUMENT ME!
 28    *
 29    * @param text
 30    * is the CDATA text
 31    */
 32  105 public DefaultCDATA(String text) {
 33  105 super(text);
 34    }
 35   
 36    /**
 37    * DOCUMENT ME!
 38    *
 39    * @param parent
 40    * is the parent element
 41    * @param text
 42    * is the CDATA text
 43    */
 44  0 public DefaultCDATA(Element parent, String text) {
 45  0 super(text);
 46  0 this.parent = parent;
 47    }
 48   
 49  0 public void setText(String text) {
 50  0 this.text = text;
 51    }
 52   
 53  0 public Element getParent() {
 54  0 return parent;
 55    }
 56   
 57  102 public void setParent(Element parent) {
 58  102 this.parent = parent;
 59    }
 60   
 61  0 public boolean supportsParent() {
 62  0 return true;
 63    }
 64   
 65  0 public boolean isReadOnly() {
 66  0 return false;
 67    }
 68    }
 69   
 70    /*
 71    * Redistribution and use of this software and associated documentation
 72    * ("Software"), with or without modification, are permitted provided that the
 73    * following conditions are met:
 74    *
 75    * 1. Redistributions of source code must retain copyright statements and
 76    * notices. Redistributions must also contain a copy of this document.
 77    *
 78    * 2. Redistributions in binary form must reproduce the above copyright notice,
 79    * this list of conditions and the following disclaimer in the documentation
 80    * and/or other materials provided with the distribution.
 81    *
 82    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 83    * from this Software without prior written permission of MetaStuff, Ltd. For
 84    * written permission, please contact dom4j-info@metastuff.com.
 85    *
 86    * 4. Products derived from this Software may not be called "DOM4J" nor may
 87    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 88    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 89    *
 90    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 91    *
 92    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 93    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 94    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 95    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 96    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 97    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 98    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 99    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 100    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 101    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 102    * POSSIBILITY OF SUCH DAMAGE.
 103    *
 104    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 105    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/pkg-summary.html0000644000175000017500000012204410242117704022214 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
package stats: LOC: 10.372   Methods: 644
NCLOC: 4.897   Classes: 48
Files: 40  
 
 Package Conditionals Statements Methods TOTAL
org.dom4j.tree 47% 54,6% 54,7% 52,6%
coverage coverage
 
 Classes Conditionals Statements Methods TOTAL
ConcurrentReaderHashMap.EntrySet 0% 0% 0% 0%
coverage
ConcurrentReaderHashMap.HashIterator 0% 0% 0% 0%
coverage
ConcurrentReaderHashMap.KeyIterator - 0% 0% 0%
coverage
ConcurrentReaderHashMap.KeySet - 0% 0% 0%
coverage
ConcurrentReaderHashMap.ValueIterator - 0% 0% 0%
coverage
ConcurrentReaderHashMap.Values - 0% 0% 0%
coverage
ElementIterator - 0% 0% 0%
coverage
ElementNameIterator 0% 0% 0% 0%
coverage
ElementQNameIterator 0% 0% 0% 0%
coverage
FilterIterator 0% 0% 0% 0%
coverage
AbstractEntity 0% 8,3% 22,2% 12%
coverage coverage
FlyweightEntity 0% 22,2% 14,3% 16,7%
coverage coverage
ConcurrentReaderHashMap.Entry 0% 23,5% 14,3% 17,9%
coverage coverage
BaseElement 10% 21,6% 23,5% 18,9%
coverage coverage
DefaultEntity - 20% 22,2% 21,1%
coverage coverage
AbstractComment 0% 18,2% 37,5% 21,7%
coverage coverage
AbstractCharacterData 0% 20% 50% 23,1%
coverage coverage
DefaultProcessingInstruction - 21,4% 27,3% 24%
coverage coverage
DefaultCDATA - 25% 28,6% 26,7%
coverage coverage
ContentListFacade 8,3% 27,9% 38,1% 27,6%
coverage coverage
ConcurrentReaderHashMap 33% 36,6% 30,3% 35%
coverage coverage
AbstractElement 38,2% 48,1% 53% 45,9%
coverage coverage
FlyweightAttribute - 44,4% 50% 46,7%
coverage coverage
BackedList 37,5% 49,1% 61,5% 47,9%
coverage coverage
AbstractProcessingInstruction 60% 50% 35,3% 49,5%
coverage coverage
DefaultDocument 30,8% 52,2% 72,4% 49,5%
coverage coverage
AbstractDocumentType 40,9% 52,4% 54,5% 50%
coverage coverage
DefaultAttribute - 46,2% 54,5% 50%
coverage coverage
DefaultComment - 50% 57,1% 53,3%
coverage coverage
FlyweightProcessingInstruction 50% 60% 55,6% 57,7%
coverage coverage
AbstractDocument 31,8% 66,2% 76,9% 62,4%
coverage coverage
AbstractText - 60% 66,7% 63,6%
coverage coverage
DefaultElement 59,8% 68,3% 75,5% 65,5%
coverage coverage
AbstractAttribute 60% 71,7% 57,9% 66,7%
coverage coverage
AbstractBranch 65% 65,2% 74,3% 66,7%
coverage coverage
FlyweightCDATA - 66,7% 66,7% 66,7%
coverage coverage
FlyweightComment - 66,7% 66,7% 66,7%
coverage coverage
FlyweightText - 66,7% 66,7% 66,7%
coverage coverage
AbstractNode 75% 70% 61,8% 67,9%
coverage coverage
DefaultDocumentType - 73,3% 76,9% 75%
coverage coverage
QNameCache 77,3% 78,6% 76,9% 78%
coverage coverage
DefaultText - 75% 85,7% 80%
coverage coverage
SingleIterator - 85,7% 75% 81,8%
coverage coverage
NamespaceStack 77,9% 88% 88% 84,9%
coverage coverage
NamespaceCache 80% 87,2% 100% 85,9%
coverage coverage
AbstractCDATA 100% 90,9% 83,3% 89,5%
coverage coverage
DefaultNamespace 66,7% 94,1% 100% 90,6%
coverage coverage
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/NamespaceCache.html0000644000175000017500000016654310242117601022570 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 216   Methods: 4
NCLOC: 89   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
NamespaceCache.java 80% 87,2% 100% 85,9%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.lang.ref.WeakReference;
 11    import java.lang.reflect.Constructor;
 12    import java.util.Map;
 13   
 14    import org.dom4j.Namespace;
 15   
 16    /**
 17    * <p>
 18    * <code>NamespaceCache</code> caches instances of
 19    * <code>DefaultNamespace</code> for reuse both across documents and within
 20    * documents.
 21    * </p>
 22    *
 23    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 24    * @author Maarten Coene
 25    * @author Brett Finnell
 26    * @version $Revision: 1.15 $
 27    */
 28    public class NamespaceCache {
 29    private static final String CONCURRENTREADERHASHMAP_CLASS
 30    = "EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap";
 31   
 32    /**
 33    * Cache of {@link Map}instances indexed by URI which contain caches of
 34    * {@link Namespace}for each prefix
 35    */
 36    protected static Map cache;
 37   
 38    /**
 39    * Cache of {@link Namespace}instances indexed by URI for default
 40    * namespaces with no prefixes
 41    */
 42    protected static Map noPrefixCache;
 43   
 44    static {
 45    /* Try the java.util.concurrent.ConcurrentHashMap first. */
 46  90 try {
 47  90 Class clazz = Class
 48    .forName("java.util.concurrent.ConcurrentHashMap");
 49  0 Constructor construct = clazz.getConstructor(new Class[] {
 50    Integer.TYPE, Float.TYPE, Integer.TYPE });
 51  0 cache = (Map) construct.newInstance(new Object[] {new Integer(11),
 52    new Float(0.75f), new Integer(1) });
 53  0 noPrefixCache = (Map) construct.newInstance(new Object[] {
 54    new Integer(11), new Float(0.75f), new Integer(1) });
 55    } catch (Throwable t1) {
 56    /* Try to use the util.concurrent library (if in classpath) */
 57  90 try {
 58  90 Class clazz = Class.forName(CONCURRENTREADERHASHMAP_CLASS);
 59  0 cache = (Map) clazz.newInstance();
 60  0 noPrefixCache = (Map) clazz.newInstance();
 61    } catch (Throwable t2) {
 62    /* If previous implementations fail, use internal one */
 63  90 cache = new ConcurrentReaderHashMap();
 64  90 noPrefixCache = new ConcurrentReaderHashMap();
 65    }
 66    }
 67    }
 68   
 69    /**
 70    * DOCUMENT ME!
 71    *
 72    * @param prefix
 73    * DOCUMENT ME!
 74    * @param uri
 75    * DOCUMENT ME!
 76    *
 77    * @return the namespace for the given prefix and uri
 78    */
 79  1121352 public Namespace get(String prefix, String uri) {
 80  1121352 Map uriCache = getURICache(uri);
 81  1121352 WeakReference ref = (WeakReference) uriCache.get(prefix);
 82  1121352 Namespace answer = null;
 83   
 84  1121352 if (ref != null) {
 85  1111030 answer = (Namespace) ref.get();
 86    }
 87   
 88  1121352 if (answer == null) {
 89  10328 synchronized (uriCache) {
 90  10328 ref = (WeakReference) uriCache.get(prefix);
 91   
 92  10328 if (ref != null) {
 93  6 answer = (Namespace) ref.get();
 94    }
 95   
 96  10328 if (answer == null) {
 97  10328 answer = createNamespace(prefix, uri);
 98  10328 uriCache.put(prefix, new WeakReference(answer));
 99    }
 100    }
 101    }
 102   
 103  1121352 return answer;
 104    }
 105   
 106    /**
 107    * DOCUMENT ME!
 108    *
 109    * @param uri
 110    * DOCUMENT ME!
 111    *
 112    * @return the name model for the given name and namepsace
 113    */
 114  26 public Namespace get(String uri) {
 115  26 WeakReference ref = (WeakReference) noPrefixCache.get(uri);
 116  26 Namespace answer = null;
 117   
 118  26 if (ref != null) {
 119  20 answer = (Namespace) ref.get();
 120    }
 121   
 122  26 if (answer == null) {
 123  6 synchronized (noPrefixCache) {
 124  6 ref = (WeakReference) noPrefixCache.get(uri);
 125   
 126  6 if (ref != null) {
 127  0 answer = (Namespace) ref.get();
 128    }
 129   
 130  6 if (answer == null) {
 131  6 answer = createNamespace("", uri);
 132  6 noPrefixCache.put(uri, new WeakReference(answer));
 133    }
 134    }
 135    }
 136   
 137  26 return answer;
 138    }
 139   
 140    /**
 141    * DOCUMENT ME!
 142    *
 143    * @param uri
 144    * DOCUMENT ME!
 145    *
 146    * @return the cache for the given namespace URI. If one does not currently
 147    * exist it is created.
 148    */
 149  1121352 protected Map getURICache(String uri) {
 150  1121352 Map answer = (Map) cache.get(uri);
 151   
 152  1121352 if (answer == null) {
 153  10296 synchronized (cache) {
 154  10296 answer = (Map) cache.get(uri);
 155   
 156  10296 if (answer == null) {
 157  10296 answer = new ConcurrentReaderHashMap();
 158  10296 cache.put(uri, answer);
 159    }
 160    }
 161    }
 162   
 163  1121352 return answer;
 164    }
 165   
 166    /**
 167    * A factory method to create {@link Namespace}instance
 168    *
 169    * @param prefix
 170    * DOCUMENT ME!
 171    * @param uri
 172    * DOCUMENT ME!
 173    *
 174    * @return a newly created {@link Namespace}instance.
 175    */
 176  10334 protected Namespace createNamespace(String prefix, String uri) {
 177  10334 return new Namespace(prefix, uri);
 178    }
 179    }
 180   
 181    /*
 182    * Redistribution and use of this software and associated documentation
 183    * ("Software"), with or without modification, are permitted provided that the
 184    * following conditions are met:
 185    *
 186    * 1. Redistributions of source code must retain copyright statements and
 187    * notices. Redistributions must also contain a copy of this document.
 188    *
 189    * 2. Redistributions in binary form must reproduce the above copyright notice,
 190    * this list of conditions and the following disclaimer in the documentation
 191    * and/or other materials provided with the distribution.
 192    *
 193    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 194    * from this Software without prior written permission of MetaStuff, Ltd. For
 195    * written permission, please contact dom4j-info@metastuff.com.
 196    *
 197    * 4. Products derived from this Software may not be called "DOM4J" nor may
 198    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 199    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 200    *
 201    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 202    *
 203    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 204    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 205    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 206    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 207    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 208    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 209    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 210    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 211    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 212    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 213    * POSSIBILITY OF SUCH DAMAGE.
 214    *
 215    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 216    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/FlyweightProcessingInstruction.html0000644000175000017500000011746110242117630026206 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 146   Methods: 9
NCLOC: 46   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
FlyweightProcessingInstruction.java 50% 60% 55,6% 57,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.util.Collections;
 11    import java.util.Map;
 12   
 13    import org.dom4j.Element;
 14    import org.dom4j.Node;
 15   
 16    /**
 17    * <p>
 18    * <code>FlyweightProcessingInstruction</code> is a Flyweight pattern
 19    * implementation of a singly linked, read-only XML Processing Instruction.
 20    * </p>
 21    *
 22    * <p>
 23    * This node could be shared across documents and elements though it does not
 24    * support the parent relationship.
 25    * </p>
 26    *
 27    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 28    * @version $Revision: 1.7 $
 29    */
 30    public class FlyweightProcessingInstruction extends
 31    AbstractProcessingInstruction {
 32    /** The target of the PI */
 33    protected String target;
 34   
 35    /** The values for the PI as a String */
 36    protected String text;
 37   
 38    /** The values for the PI in name/value pairs */
 39    protected Map values;
 40   
 41    /**
 42    * A default constructor for implementors to use.
 43    */
 44  0 public FlyweightProcessingInstruction() {
 45    }
 46   
 47    /**
 48    * <p>
 49    * This will create a new PI with the given target and values
 50    * </p>
 51    *
 52    * @param target
 53    * is the name of the PI
 54    * @param values
 55    * is the <code>Map</code> of the values for the PI
 56    */
 57  0 public FlyweightProcessingInstruction(String target, Map values) {
 58  0 this.target = target;
 59  0 this.values = values;
 60  0 this.text = toString(values);
 61    }
 62   
 63    /**
 64    * <p>
 65    * This will create a new PI with the given target and values
 66    * </p>
 67    *
 68    * @param target
 69    * is the name of the PI
 70    * @param text
 71    * is the values for the PI as text
 72    */
 73  28 public FlyweightProcessingInstruction(String target, String text) {
 74  28 this.target = target;
 75  28 this.text = text;
 76  28 this.values = parseValues(text);
 77    }
 78   
 79  29 public String getTarget() {
 80  29 return target;
 81    }
 82   
 83  0 public void setTarget(String target) {
 84  0 throw new UnsupportedOperationException("This PI is read-only and "
 85    + "cannot be modified");
 86    }
 87   
 88  29 public String getText() {
 89  29 return text;
 90    }
 91   
 92  4 public String getValue(String name) {
 93  4 String answer = (String) values.get(name);
 94   
 95  4 if (answer == null) {
 96  0 return "";
 97    }
 98   
 99  4 return answer;
 100    }
 101   
 102  1 public Map getValues() {
 103  1 return Collections.unmodifiableMap(values);
 104    }
 105   
 106  0 protected Node createXPathResult(Element parent) {
 107  0 return new DefaultProcessingInstruction(parent, getTarget(), getText());
 108    }
 109    }
 110   
 111    /*
 112    * Redistribution and use of this software and associated documentation
 113    * ("Software"), with or without modification, are permitted provided that the
 114    * following conditions are met:
 115    *
 116    * 1. Redistributions of source code must retain copyright statements and
 117    * notices. Redistributions must also contain a copy of this document.
 118    *
 119    * 2. Redistributions in binary form must reproduce the above copyright notice,
 120    * this list of conditions and the following disclaimer in the documentation
 121    * and/or other materials provided with the distribution.
 122    *
 123    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 124    * from this Software without prior written permission of MetaStuff, Ltd. For
 125    * written permission, please contact dom4j-info@metastuff.com.
 126    *
 127    * 4. Products derived from this Software may not be called "DOM4J" nor may
 128    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 129    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 130    *
 131    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 132    *
 133    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 134    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 135    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 136    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 137    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 138    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 139    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 140    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 141    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 142    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 143    * POSSIBILITY OF SUCH DAMAGE.
 144    *
 145    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 146    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/FlyweightAttribute.html0000644000175000017500000010121710242117700023561 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 117   Methods: 6
NCLOC: 28   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
FlyweightAttribute.java - 44,4% 50% 46,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import org.dom4j.Namespace;
 11    import org.dom4j.QName;
 12   
 13    /**
 14    * <p>
 15    * <code>FlyweightAttribute</code> is a Flyweight pattern implementation of a
 16    * singly linked, read-only XML Attribute.
 17    * </p>
 18    *
 19    * <p>
 20    * This node could be shared across documents and elements though it does not
 21    * support the parent relationship.
 22    * </p>
 23    *
 24    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 25    * @version $Revision: 1.7 $
 26    */
 27    public class FlyweightAttribute extends AbstractAttribute {
 28    /** The <code>QName</code> for this element */
 29    private QName qname;
 30   
 31    /** The value of the <code>Attribute</code> */
 32    protected String value;
 33   
 34  0 public FlyweightAttribute(QName qname) {
 35  0 this.qname = qname;
 36    }
 37   
 38  14283 public FlyweightAttribute(QName qname, String value) {
 39  14283 this.qname = qname;
 40  14283 this.value = value;
 41    }
 42   
 43    /**
 44    * Creates the <code>Attribute</code> with the specified local name and
 45    * value.
 46    *
 47    * @param name
 48    * is the name of the attribute
 49    * @param value
 50    * is the value of the attribute
 51    */
 52  0 public FlyweightAttribute(String name, String value) {
 53  0 this.qname = getDocumentFactory().createQName(name);
 54  0 this.value = value;
 55    }
 56   
 57    /**
 58    * Creates the <code>Attribute</code> with the specified local name, value
 59    * and <code>Namespace</code>.
 60    *
 61    * @param name
 62    * is the name of the attribute
 63    * @param value
 64    * is the value of the attribute
 65    * @param namespace
 66    * is the namespace of the attribute
 67    */
 68  0 public FlyweightAttribute(String name, String value, Namespace namespace) {
 69  0 this.qname = getDocumentFactory().createQName(name, namespace);
 70  0 this.value = value;
 71    }
 72   
 73  109420 public String getValue() {
 74  109420 return value;
 75    }
 76   
 77  156154 public QName getQName() {
 78  156154 return qname;
 79    }
 80    }
 81   
 82    /*
 83    * Redistribution and use of this software and associated documentation
 84    * ("Software"), with or without modification, are permitted provided that the
 85    * following conditions are met:
 86    *
 87    * 1. Redistributions of source code must retain copyright statements and
 88    * notices. Redistributions must also contain a copy of this document.
 89    *
 90    * 2. Redistributions in binary form must reproduce the above copyright notice,
 91    * this list of conditions and the following disclaimer in the documentation
 92    * and/or other materials provided with the distribution.
 93    *
 94    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 95    * from this Software without prior written permission of MetaStuff, Ltd. For
 96    * written permission, please contact dom4j-info@metastuff.com.
 97    *
 98    * 4. Products derived from this Software may not be called "DOM4J" nor may
 99    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 100    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 101    *
 102    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 103    *
 104    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 105    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 106    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 107    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 108    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 109    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 110    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 111    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 112    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 113    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 114    * POSSIBILITY OF SUCH DAMAGE.
 115    *
 116    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 117    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/ContentListFacade.html0000644000175000017500000015706210242117545023305 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 200   Methods: 21
NCLOC: 105   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
ContentListFacade.java 8,3% 27,9% 38,1% 27,6%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.util.AbstractList;
 11    import java.util.Collection;
 12    import java.util.Iterator;
 13    import java.util.List;
 14   
 15    import org.dom4j.IllegalAddException;
 16    import org.dom4j.Node;
 17   
 18    /**
 19    * <p>
 20    * <code>ContentListFacade</code> represents a facade of the content of a
 21    * {@link org.dom4j.Branch} which is returned via calls to the {@link
 22    * org.dom4j.Branch#content} method to allow users to modify the content of a
 23    * {@link org.dom4j.Branch} directly using the {@link List} interface. This list
 24    * is backed by the branch such that changes to the list will be reflected in
 25    * the branch and changes to the branch will be reflected in this list.
 26    * </p>
 27    *
 28    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 29    * @version $Revision: 1.11 $
 30    */
 31    public class ContentListFacade extends AbstractList {
 32    /** The content of the Branch which is modified if I am modified */
 33    private List branchContent;
 34   
 35    /** The <code>AbstractBranch</code> instance which owns the content */
 36    private AbstractBranch branch;
 37   
 38  5000 public ContentListFacade(AbstractBranch branch, List branchContent) {
 39  5000 this.branch = branch;
 40  5000 this.branchContent = branchContent;
 41    }
 42   
 43  0 public boolean add(Object object) {
 44  0 branch.childAdded(asNode(object));
 45   
 46  0 return branchContent.add(object);
 47    }
 48   
 49  6 public void add(int index, Object object) {
 50  6 branch.childAdded(asNode(object));
 51  6 branchContent.add(index, object);
 52    }
 53   
 54  1 public Object set(int index, Object object) {
 55  1 branch.childAdded(asNode(object));
 56   
 57  1 return branchContent.set(index, object);
 58    }
 59   
 60  0 public boolean remove(Object object) {
 61  0 branch.childRemoved(asNode(object));
 62   
 63  0 return branchContent.remove(object);
 64    }
 65   
 66  0 public Object remove(int index) {
 67  0 Object object = branchContent.remove(index);
 68   
 69  0 if (object != null) {
 70  0 branch.childRemoved(asNode(object));
 71    }
 72   
 73  0 return object;
 74    }
 75   
 76  0 public boolean addAll(Collection collection) {
 77  0 int count = branchContent.size();
 78   
 79  0 for (Iterator iter = collection.iterator(); iter.hasNext(); count++) {
 80  0 add(iter.next());
 81    }
 82   
 83  0 return count == branchContent.size();
 84    }
 85   
 86  0 public boolean addAll(int index, Collection collection) {
 87  0 int count = branchContent.size();
 88   
 89  0 for (Iterator iter = collection.iterator(); iter.hasNext(); count--) {
 90  0 add(index++, iter.next());
 91    }
 92   
 93  0 return count == branchContent.size();
 94    }
 95   
 96  0 public void clear() {
 97  0 for (Iterator iter = iterator(); iter.hasNext();) {
 98  0 Object object = iter.next();
 99  0 branch.childRemoved(asNode(object));
 100    }
 101   
 102  0 branchContent.clear();
 103    }
 104   
 105  0 public boolean removeAll(Collection c) {
 106  0 for (Iterator iter = c.iterator(); iter.hasNext();) {
 107  0 Object object = iter.next();
 108  0 branch.childRemoved(asNode(object));
 109    }
 110   
 111  0 return branchContent.removeAll(c);
 112    }
 113   
 114  5168 public int size() {
 115  5168 return branchContent.size();
 116    }
 117   
 118  0 public boolean isEmpty() {
 119  0 return branchContent.isEmpty();
 120    }
 121   
 122  0 public boolean contains(Object o) {
 123  0 return branchContent.contains(o);
 124    }
 125   
 126  0 public Object[] toArray() {
 127  0 return branchContent.toArray();
 128    }
 129   
 130  0 public Object[] toArray(Object[] a) {
 131  0 return branchContent.toArray(a);
 132    }
 133   
 134  0 public boolean containsAll(Collection c) {
 135  0 return branchContent.containsAll(c);
 136    }
 137   
 138  13434 public Object get(int index) {
 139  13434 return branchContent.get(index);
 140    }
 141   
 142  3 public int indexOf(Object o) {
 143  3 return branchContent.indexOf(o);
 144    }
 145   
 146  0 public int lastIndexOf(Object o) {
 147  0 return branchContent.lastIndexOf(o);
 148    }
 149   
 150  7 protected Node asNode(Object object) {
 151  7 if (object instanceof Node) {
 152  7 return (Node) object;
 153    } else {
 154  0 throw new IllegalAddException(
 155    "This list must contain instances of "
 156    + "Node. Invalid type: " + object);
 157    }
 158    }
 159   
 160  3 protected List getBackingList() {
 161  3 return branchContent;
 162    }
 163    }
 164   
 165    /*
 166    * Redistribution and use of this software and associated documentation
 167    * ("Software"), with or without modification, are permitted provided that the
 168    * following conditions are met:
 169    *
 170    * 1. Redistributions of source code must retain copyright statements and
 171    * notices. Redistributions must also contain a copy of this document.
 172    *
 173    * 2. Redistributions in binary form must reproduce the above copyright notice,
 174    * this list of conditions and the following disclaimer in the documentation
 175    * and/or other materials provided with the distribution.
 176    *
 177    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 178    * from this Software without prior written permission of MetaStuff, Ltd. For
 179    * written permission, please contact dom4j-info@metastuff.com.
 180    *
 181    * 4. Products derived from this Software may not be called "DOM4J" nor may
 182    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 183    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 184    *
 185    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 186    *
 187    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 188    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 189    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 190    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 191    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 192    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 193    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 194    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 195    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 196    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 197    * POSSIBILITY OF SUCH DAMAGE.
 198    *
 199    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 200    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/ElementIterator.html0000644000175000017500000005531510242117740023051 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 79   Methods: 2
NCLOC: 11   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
ElementIterator.java - 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.util.Iterator;
 11   
 12    import org.dom4j.Element;
 13   
 14    /**
 15    * <p>
 16    * <code>ElementIterator</code> is a filtering {@link Iterator}which filters
 17    * out objects which do not implement the {@link Element}interface.
 18    * </p>
 19    *
 20    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 21    * @version $Revision: 1.8 $
 22    *
 23    * @deprecated THIS CLASS WILL BE REMOVED IN dom4j-1.6 !!
 24    */
 25    public class ElementIterator extends FilterIterator {
 26  0 public ElementIterator(Iterator proxy) {
 27  0 super(proxy);
 28    }
 29   
 30    /**
 31    * DOCUMENT ME!
 32    *
 33    * @param element
 34    * DOCUMENT ME!
 35    *
 36    * @return true if the given element implements the {@link Element}
 37    * interface
 38    */
 39  0 protected boolean matches(Object element) {
 40  0 return element instanceof Element;
 41    }
 42    }
 43   
 44    /*
 45    * Redistribution and use of this software and associated documentation
 46    * ("Software"), with or without modification, are permitted provided that the
 47    * following conditions are met:
 48    *
 49    * 1. Redistributions of source code must retain copyright statements and
 50    * notices. Redistributions must also contain a copy of this document.
 51    *
 52    * 2. Redistributions in binary form must reproduce the above copyright notice,
 53    * this list of conditions and the following disclaimer in the documentation
 54    * and/or other materials provided with the distribution.
 55    *
 56    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 57    * from this Software without prior written permission of MetaStuff, Ltd. For
 58    * written permission, please contact dom4j-info@metastuff.com.
 59    *
 60    * 4. Products derived from this Software may not be called "DOM4J" nor may
 61    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 62    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 63    *
 64    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 65    *
 66    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 67    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 68    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 69    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 70    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 71    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 72    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 73    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 74    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 75    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 76    * POSSIBILITY OF SUCH DAMAGE.
 77    *
 78    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 79    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/QNameCache.html0000644000175000017500000024275010242117752021677 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 310   Methods: 13
NCLOC: 117   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
QNameCache.java 77,3% 78,6% 76,9% 78%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.util.ArrayList;
 11    import java.util.Collections;
 12    import java.util.HashMap;
 13    import java.util.Iterator;
 14    import java.util.List;
 15    import java.util.Map;
 16    import java.util.WeakHashMap;
 17   
 18    import org.dom4j.DocumentFactory;
 19    import org.dom4j.Namespace;
 20    import org.dom4j.QName;
 21   
 22    /**
 23    * <p>
 24    * <code>QNameCache</code> caches instances of <code>QName</code> for reuse
 25    * both across documents and within documents.
 26    * </p>< < < < < < < QNameCache.java
 27    *
 28    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 29    * @version $Revision: 1.16 $ =======
 30    *
 31    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 32    * @version $Revision: 1.16 $ >>>>>>> 1.15
 33    */
 34    public class QNameCache {
 35    /** Cache of {@link QName}instances with no namespace */
 36    protected Map noNamespaceCache = Collections
 37    .synchronizedMap(new WeakHashMap());
 38   
 39    /**
 40    * Cache of {@link Map}instances indexed by namespace which contain caches
 41    * of {@link QName}for each name
 42    */
 43    protected Map namespaceCache = Collections
 44    .synchronizedMap(new WeakHashMap());
 45   
 46    /**
 47    * The document factory associated with new QNames instances in this cache
 48    * or null if no instances should be associated by default
 49    */
 50    private DocumentFactory documentFactory;
 51   
 52  90 public QNameCache() {
 53    }
 54   
 55  544 public QNameCache(DocumentFactory documentFactory) {
 56  544 this.documentFactory = documentFactory;
 57    }
 58   
 59    /**
 60    * Returns a list of all the QName instances currently used
 61    *
 62    * @return DOCUMENT ME!
 63    */
 64  1 public List getQNames() {
 65  1 List answer = new ArrayList();
 66  1 answer.addAll(noNamespaceCache.values());
 67   
 68  1 for (Iterator it = namespaceCache.values().iterator(); it.hasNext();) {
 69  10 Map map = (Map) it.next();
 70  10 answer.addAll(map.values());
 71    }
 72   
 73  1 return answer;
 74    }
 75   
 76    /**
 77    * DOCUMENT ME!
 78    *
 79    * @param name
 80    * DOCUMENT ME!
 81    *
 82    * @return the QName for the given name and no namepsace
 83    */
 84  26755 public QName get(String name) {
 85  26755 QName answer = null;
 86   
 87  26755 if (name != null) {
 88  26631 answer = (QName) noNamespaceCache.get(name);
 89    } else {
 90  124 name = "";
 91    }
 92   
 93  26755 if (answer == null) {
 94  1065 answer = createQName(name);
 95  1065 answer.setDocumentFactory(documentFactory);
 96  1065 noNamespaceCache.put(name, answer);
 97    }
 98   
 99  26755 return answer;
 100    }
 101   
 102    /**
 103    * DOCUMENT ME!
 104    *
 105    * @param name
 106    * DOCUMENT ME!
 107    * @param namespace
 108    * DOCUMENT ME!
 109    *
 110    * @return the QName for the given local name and namepsace
 111    */
 112  105078 public QName get(String name, Namespace namespace) {
 113  105078 Map cache = getNamespaceCache(namespace);
 114  105078 QName answer = null;
 115   
 116  105078 if (name != null) {
 117  105054 answer = (QName) cache.get(name);
 118    } else {
 119  24 name = "";
 120    }
 121   
 122  105078 if (answer == null) {
 123  1595 answer = createQName(name, namespace);
 124  1595 answer.setDocumentFactory(documentFactory);
 125  1595 cache.put(name, answer);
 126    }
 127   
 128  105078 return answer;
 129    }
 130   
 131    /**
 132    * DOCUMENT ME!
 133    *
 134    * @param localName
 135    * DOCUMENT ME!
 136    * @param namespace
 137    * DOCUMENT ME!
 138    * @param qName
 139    * DOCUMENT ME!
 140    *
 141    * @return the QName for the given local name, qualified name and namepsace
 142    */
 143  0 public QName get(String localName, Namespace namespace, String qName) {
 144  0 Map cache = getNamespaceCache(namespace);
 145  0 QName answer = null;
 146   
 147  0 if (localName != null) {
 148  0 answer = (QName) cache.get(localName);
 149    } else {
 150  0 localName = "";
 151    }
 152   
 153  0 if (answer == null) {
 154  0 answer = createQName(localName, namespace, qName);
 155  0 answer.setDocumentFactory(documentFactory);
 156  0 cache.put(localName, answer);
 157    }
 158   
 159  0 return answer;
 160    }
 161   
 162  30 public QName get(String qualifiedName, String uri) {
 163  30 int index = qualifiedName.indexOf(':');
 164   
 165  30 if (index < 0) {
 166  26 return get(qualifiedName, Namespace.get(uri));
 167    } else {
 168  4 String name = qualifiedName.substring(index + 1);
 169  4 String prefix = qualifiedName.substring(0, index);
 170   
 171  4 return get(name, Namespace.get(prefix, uri));
 172    }
 173    }
 174   
 175    /**
 176    * DOCUMENT ME!
 177    *
 178    * @param qname
 179    * DOCUMENT ME!
 180    *
 181    * @return the cached QName instance if there is one or adds the given qname
 182    * to the cache if not
 183    */
 184  0 public QName intern(QName qname) {
 185  0 return get(qname.getName(), qname.getNamespace(), qname
 186    .getQualifiedName());
 187    }
 188   
 189    /**
 190    * DOCUMENT ME!
 191    *
 192    * @param namespace
 193    * DOCUMENT ME!
 194    *
 195    * @return the cache for the given namespace. If one does not currently
 196    * exist it is created.
 197    */
 198  105078 protected Map getNamespaceCache(Namespace namespace) {
 199  105078 if (namespace == Namespace.NO_NAMESPACE) {
 200  84795 return noNamespaceCache;
 201    }
 202   
 203  20283 Map answer = null;
 204   
 205  20283 if (namespace != null) {
 206  20283 answer = (Map) namespaceCache.get(namespace);
 207    }
 208   
 209  20283 if (answer == null) {
 210  167 answer = createMap();
 211  167 namespaceCache.put(namespace, answer);
 212    }
 213   
 214  20283 return answer;
 215    }
 216   
 217    /**
 218    * A factory method
 219    *
 220    * @return a newly created {@link Map}instance.
 221    */
 222  167 protected Map createMap() {
 223  167 return Collections.synchronizedMap(new HashMap());
 224    }
 225   
 226    /**
 227    * Factory method to create a new QName object which can be overloaded to
 228    * create derived QName instances
 229    *
 230    * @param name
 231    * DOCUMENT ME!
 232    *
 233    * @return DOCUMENT ME!
 234    */
 235  1065 protected QName createQName(String name) {
 236  1065 return new QName(name);
 237    }
 238   
 239    /**
 240    * Factory method to create a new QName object which can be overloaded to
 241    * create derived QName instances
 242    *
 243    * @param name
 244    * DOCUMENT ME!
 245    * @param namespace
 246    * DOCUMENT ME!
 247    *
 248    * @return DOCUMENT ME!
 249    */
 250  1595 protected QName createQName(String name, Namespace namespace) {
 251  1595 return new QName(name, namespace);
 252    }
 253   
 254    /**
 255    * Factory method to create a new QName object which can be overloaded to
 256    * create derived QName instances
 257    *
 258    * @param name
 259    * DOCUMENT ME!
 260    * @param namespace
 261    * DOCUMENT ME!
 262    * @param qualifiedName
 263    * DOCUMENT ME!
 264    *
 265    * @return DOCUMENT ME!
 266    */
 267  0 protected QName createQName(String name, Namespace namespace,
 268    String qualifiedName) {
 269  0 return new QName(name, namespace, qualifiedName);
 270    }
 271    }
 272   
 273   
 274   
 275    /*
 276    * Redistribution and use of this software and associated documentation
 277    * ("Software"), with or without modification, are permitted provided that the
 278    * following conditions are met:
 279    *
 280    * 1. Redistributions of source code must retain copyright statements and
 281    * notices. Redistributions must also contain a copy of this document.
 282    *
 283    * 2. Redistributions in binary form must reproduce the above copyright notice,
 284    * this list of conditions and the following disclaimer in the documentation
 285    * and/or other materials provided with the distribution.
 286    *
 287    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 288    * from this Software without prior written permission of MetaStuff, Ltd. For
 289    * written permission, please contact dom4j-info@metastuff.com.
 290    *
 291    * 4. Products derived from this Software may not be called "DOM4J" nor may
 292    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 293    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 294    *
 295    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 296    *
 297    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 298    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 299    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 300    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 301    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 302    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 303    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 304    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 305    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 306    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 307    * POSSIBILITY OF SUCH DAMAGE.
 308    *
 309    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 310    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/AbstractElement.html0000644000175000017500000160625210242117676023036 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 1.684   Methods: 115
NCLOC: 1.027   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
AbstractElement.java 38,2% 48,1% 53% 45,9%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.io.IOException;
 11    import java.io.StringWriter;
 12    import java.io.Writer;
 13    import java.util.ArrayList;
 14    import java.util.Collections;
 15    import java.util.Iterator;
 16    import java.util.List;
 17    import java.util.Map;
 18   
 19    import org.dom4j.Attribute;
 20    import org.dom4j.CDATA;
 21    import org.dom4j.CharacterData;
 22    import org.dom4j.Comment;
 23    import org.dom4j.Document;
 24    import org.dom4j.DocumentFactory;
 25    import org.dom4j.Element;
 26    import org.dom4j.Entity;
 27    import org.dom4j.IllegalAddException;
 28    import org.dom4j.Namespace;
 29    import org.dom4j.Node;
 30    import org.dom4j.ProcessingInstruction;
 31    import org.dom4j.QName;
 32    import org.dom4j.Text;
 33    import org.dom4j.Visitor;
 34    import org.dom4j.io.OutputFormat;
 35    import org.dom4j.io.XMLWriter;
 36   
 37    import org.xml.sax.Attributes;
 38   
 39    /**
 40    * <p>
 41    * <code>AbstractElement</code> is an abstract base class for tree
 42    * implementors to use for implementation inheritence.
 43    * </p>
 44    *
 45    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 46    * @version $Revision: 1.80 $
 47    */
 48    public abstract class AbstractElement extends AbstractBranch implements
 49    org.dom4j.Element {
 50    /** The <code>DocumentFactory</code> instance used by default */
 51    private static final DocumentFactory DOCUMENT_FACTORY = DocumentFactory
 52    .getInstance();
 53   
 54    protected static final List EMPTY_LIST = Collections.EMPTY_LIST;
 55   
 56    protected static final Iterator EMPTY_ITERATOR = EMPTY_LIST.iterator();
 57   
 58    protected static final boolean VERBOSE_TOSTRING = false;
 59   
 60    protected static final boolean USE_STRINGVALUE_SEPARATOR = false;
 61   
 62  96009 public AbstractElement() {
 63    }
 64   
 65  105403 public short getNodeType() {
 66  105403 return ELEMENT_NODE;
 67    }
 68   
 69  0 public boolean isRootElement() {
 70  0 Document document = getDocument();
 71   
 72  0 if (document != null) {
 73  0 Element root = document.getRootElement();
 74   
 75  0 if (root == this) {
 76  0 return true;
 77    }
 78    }
 79   
 80  0 return false;
 81    }
 82   
 83  1 public void setName(String name) {
 84  1 setQName(getDocumentFactory().createQName(name));
 85    }
 86   
 87  0 public void setNamespace(Namespace namespace) {
 88  0 setQName(getDocumentFactory().createQName(getName(), namespace));
 89    }
 90   
 91    /**
 92    * Returns the XPath expression to match this Elements name which is
 93    * getQualifiedName() if there is a namespace prefix defined or if no
 94    * namespace is present then it is getName() or if a namespace is defined
 95    * with no prefix then the expression is [name()='X'] where X = getName().
 96    *
 97    * @return DOCUMENT ME!
 98    */
 99  66 public String getXPathNameStep() {
 100  66 String uri = getNamespaceURI();
 101   
 102  66 if ((uri == null) || (uri.length() == 0)) {
 103  56 return getName();
 104    }
 105   
 106  10 String prefix = getNamespacePrefix();
 107   
 108  10 if ((prefix == null) || (prefix.length() == 0)) {
 109  8 return "*[name()='" + getName() + "']";
 110    }
 111   
 112  2 return getQualifiedName();
 113    }
 114   
 115  31 public String getPath(Element context) {
 116  31 if (this == context) {
 117  1 return ".";
 118    }
 119   
 120  30 Element parent = getParent();
 121   
 122  30 if (parent == null) {
 123  11 return "/" + getXPathNameStep();
 124  19 } else if (parent == context) {
 125  7 return getXPathNameStep();
 126    }
 127   
 128  12 return parent.getPath(context) + "/" + getXPathNameStep();
 129    }
 130   
 131  36 public String getUniquePath(Element context) {
 132  36 Element parent = getParent();
 133   
 134  36 if (parent == null) {
 135  13 return "/" + getXPathNameStep();
 136    }
 137   
 138  23 StringBuffer buffer = new StringBuffer();
 139   
 140  23 if (parent != context) {
 141  16 buffer.append(parent.getUniquePath(context));
 142   
 143  16 buffer.append("/");
 144    }
 145   
 146  23 buffer.append(getXPathNameStep());
 147   
 148  23 List mySiblings = parent.elements(getQName());
 149   
 150  23 if (mySiblings.size() > 1) {
 151  13 int idx = mySiblings.indexOf(this);
 152   
 153  13 if (idx >= 0) {
 154  13 buffer.append("[");
 155   
 156  13 buffer.append(Integer.toString(++idx));
 157   
 158  13 buffer.append("]");
 159    }
 160    }
 161   
 162  23 return buffer.toString();
 163    }
 164   
 165  2041 public String asXML() {
 166  2041 try {
 167  2041 StringWriter out = new StringWriter();
 168  2041 XMLWriter writer = new XMLWriter(out, new OutputFormat());
 169   
 170  2041 writer.write(this);
 171  2041 writer.flush();
 172   
 173  2041 return out.toString();
 174    } catch (IOException e) {
 175  0 throw new RuntimeException("IOException while generating "
 176    + "textual representation: " + e.getMessage());
 177    }
 178    }
 179   
 180  0 public void write(Writer out) throws IOException {
 181  0 XMLWriter writer = new XMLWriter(out, new OutputFormat());
 182  0 writer.write(this);
 183    }
 184   
 185    /**
 186    * <p>
 187    * <code>accept</code> method is the <code>Visitor Pattern</code>
 188    * method.
 189    * </p>
 190    *
 191    * @param visitor
 192    * <code>Visitor</code> is the visitor.
 193    */
 194  0 public void accept(Visitor visitor) {
 195  0 visitor.visit(this);
 196   
 197    // visit attributes
 198  0 for (int i = 0, size = attributeCount(); i < size; i++) {
 199  0 Attribute attribute = attribute(i);
 200   
 201  0 visitor.visit(attribute);
 202    }
 203   
 204    // visit content
 205  0 for (int i = 0, size = nodeCount(); i < size; i++) {
 206  0 Node node = node(i);
 207   
 208  0 node.accept(visitor);
 209    }
 210    }
 211   
 212  85700 public String toString() {
 213  85700 String uri = getNamespaceURI();
 214   
 215  85700 if ((uri != null) && (uri.length() > 0)) {
 216  2512 if (VERBOSE_TOSTRING) {
 217  0 return super.toString() + " [Element: <" + getQualifiedName()
 218    + " uri: " + uri + " attributes: " + attributeList()
 219    + " content: " + contentList() + " />]";
 220    } else {
 221  2512 return super.toString() + " [Element: <" + getQualifiedName()
 222    + " uri: " + uri + " attributes: " + attributeList()
 223    + "/>]";
 224    }
 225    } else {
 226  83188 if (VERBOSE_TOSTRING) {
 227  0 return super.toString() + " [Element: <" + getQualifiedName()
 228    + " attributes: " + attributeList() + " content: "
 229    + contentList() + " />]";
 230    } else {
 231  83188 return super.toString() + " [Element: <" + getQualifiedName()
 232    + " attributes: " + attributeList() + "/>]";
 233    }
 234    }
 235    }
 236   
 237    // QName methods
 238    // -------------------------------------------------------------------------
 239  120477 public Namespace getNamespace() {
 240  120477 return getQName().getNamespace();
 241    }
 242   
 243  84347 public String getName() {
 244  84347 return getQName().getName();
 245    }
 246   
 247  8774 public String getNamespacePrefix() {
 248  8774 return getQName().getNamespacePrefix();
 249    }
 250   
 251  172894 public String getNamespaceURI() {
 252  172894 return getQName().getNamespaceURI();
 253    }
 254   
 255  120578 public String getQualifiedName() {
 256  120578 return getQName().getQualifiedName();
 257    }
 258   
 259  0 public Object getData() {
 260  0 return getText();
 261    }
 262   
 263  0 public void setData(Object data) {
 264    // ignore this method
 265    }
 266   
 267    // Node methods
 268    // -------------------------------------------------------------------------
 269  0 public Node node(int index) {
 270  0 if (index >= 0) {
 271  0 List list = contentList();
 272   
 273  0 if (index >= list.size()) {
 274  0 return null;
 275    }
 276   
 277  0 Object node = list.get(index);
 278   
 279  0 if (node != null) {
 280  0 if (node instanceof Node) {
 281  0 return (Node) node;
 282    } else {
 283  0 return getDocumentFactory().createText(node.toString());
 284    }
 285    }
 286    }
 287   
 288  0 return null;
 289    }
 290   
 291  0 public int indexOf(Node node) {
 292  0 return contentList().indexOf(node);
 293    }
 294   
 295  1 public int nodeCount() {
 296  1 return contentList().size();
 297    }
 298   
 299  0 public Iterator nodeIterator() {
 300  0 return contentList().iterator();
 301    }
 302   
 303    // Element methods
 304    // -------------------------------------------------------------------------
 305  0 public Element element(String name) {
 306  0 List list = contentList();
 307   
 308  0 int size = list.size();
 309   
 310  0 for (int i = 0; i < size; i++) {
 311  0 Object object = list.get(i);
 312   
 313  0 if (object instanceof Element) {
 314  0 Element element = (Element) object;
 315   
 316  0 if (name.equals(element.getName())) {
 317  0 return element;
 318    }
 319    }
 320    }
 321   
 322  0 return null;
 323    }
 324   
 325  0 public Element element(QName qName) {
 326  0 List list = contentList();
 327   
 328  0 int size = list.size();
 329   
 330  0 for (int i = 0; i < size; i++) {
 331  0 Object object = list.get(i);
 332   
 333  0 if (object instanceof Element) {
 334  0 Element element = (Element) object;
 335   
 336  0 if (qName.equals(element.getQName())) {
 337  0 return element;
 338    }
 339    }
 340    }
 341   
 342  0 return null;
 343    }
 344   
 345  0 public Element element(String name, Namespace namespace) {
 346  0 return element(getDocumentFactory().createQName(name, namespace));
 347    }
 348   
 349  79 public List elements() {
 350  79 List list = contentList();
 351   
 352  79 BackedList answer = createResultList();
 353   
 354  79 int size = list.size();
 355   
 356  79 for (int i = 0; i < size; i++) {
 357  354 Object object = list.get(i);
 358   
 359  354 if (object instanceof Element) {
 360  145 answer.addLocal(object);
 361    }
 362    }
 363   
 364  79 return answer;
 365    }
 366   
 367  201 public List elements(String name) {
 368  201 List list = contentList();
 369   
 370  201 BackedList answer = createResultList();
 371   
 372  201 int size = list.size();
 373   
 374  201 for (int i = 0; i < size; i++) {
 375  1975 Object object = list.get(i);
 376   
 377  1975 if (object instanceof Element) {
 378  901 Element element = (Element) object;
 379   
 380  901 if (name.equals(element.getName())) {
 381  336 answer.addLocal(element);
 382    }
 383    }
 384    }
 385   
 386  201 return answer;
 387    }
 388   
 389  13972 public List elements(QName qName) {
 390  13972 List list = contentList();
 391   
 392  13972 BackedList answer = createResultList();
 393   
 394  13972 int size = list.size();
 395   
 396  13972 for (int i = 0; i < size; i++) {
 397  42383 Object object = list.get(i);
 398   
 399  42383 if (object instanceof Element) {
 400  14661 Element element = (Element) object;
 401   
 402  14661 if (qName.equals(element.getQName())) {
 403  3653 answer.addLocal(element);
 404    }
 405    }
 406    }
 407   
 408  13972 return answer;
 409    }
 410   
 411  0 public List elements(String name, Namespace namespace) {
 412  0 return elements(getDocumentFactory().createQName(name, namespace));
 413    }
 414   
 415  59 public Iterator elementIterator() {
 416  59 List list = elements();
 417   
 418  59 return list.iterator();
 419    }
 420   
 421  191 public Iterator elementIterator(String name) {
 422  191 List list = elements(name);
 423   
 424  191 return list.iterator();
 425    }
 426   
 427  13948 public Iterator elementIterator(QName qName) {
 428  13948 List list = elements(qName);
 429   
 430  13948 return list.iterator();
 431    }
 432   
 433  0 public Iterator elementIterator(String name, Namespace ns) {
 434  0 return elementIterator(getDocumentFactory().createQName(name, ns));
 435    }
 436   
 437    // Attribute methods
 438    // -------------------------------------------------------------------------
 439  0 public List attributes() {
 440  0 return new ContentListFacade(this, attributeList());
 441    }
 442   
 443  0 public Iterator attributeIterator() {
 444  0 return attributeList().iterator();
 445    }
 446   
 447  0 public Attribute attribute(int index) {
 448  0 return (Attribute) attributeList().get(index);
 449    }
 450   
 451  1 public int attributeCount() {
 452  1 return attributeList().size();
 453    }
 454   
 455  0 public Attribute attribute(String name) {
 456  0 List list = attributeList();
 457   
 458  0 int size = list.size();
 459   
 460  0 for (int i = 0; i < size; i++) {
 461  0 Attribute attribute = (Attribute) list.get(i);
 462   
 463  0 if (name.equals(attribute.getName())) {
 464  0 return attribute;
 465    }
 466    }
 467   
 468  0 return null;
 469    }
 470   
 471  0 public Attribute attribute(QName qName) {
 472  0 List list = attributeList();
 473   
 474  0 int size = list.size();
 475   
 476  0 for (int i = 0; i < size; i++) {
 477  0 Attribute attribute = (Attribute) list.get(i);
 478   
 479  0 if (qName.equals(attribute.getQName())) {
 480  0 return attribute;
 481    }
 482    }
 483   
 484  0 return null;
 485    }
 486   
 487  0 public Attribute attribute(String name, Namespace namespace) {
 488  0 return attribute(getDocumentFactory().createQName(name, namespace));
 489    }
 490   
 491    /**
 492    * This method provides a more optimal way of setting all the attributes on
 493    * an Element particularly for use in {@link org.dom4j.io.SAXReader}.
 494    *
 495    * @param attributes
 496    * DOCUMENT ME!
 497    * @param namespaceStack
 498    * DOCUMENT ME!
 499    * @param noNamespaceAttributes
 500    * DOCUMENT ME!
 501    */
 502  86719 public void setAttributes(Attributes attributes,
 503    NamespaceStack namespaceStack, boolean noNamespaceAttributes) {
 504    // now lets add all attribute values
 505  86719 int size = attributes.getLength();
 506   
 507  86719 if (size > 0) {
 508  7896 DocumentFactory factory = getDocumentFactory();
 509   
 510  7896 if (size == 1) {
 511    // allow lazy construction of the List of Attributes
 512  6278 String name = attributes.getQName(0);
 513   
 514  6278 if (noNamespaceAttributes || !name.startsWith("xmlns")) {
 515  6270 String attributeURI = attributes.getURI(0);
 516   
 517  6270 String attributeLocalName = attributes.getLocalName(0);
 518   
 519  6270 String attributeValue = attributes.getValue(0);
 520   
 521  6270 QName attributeQName = namespaceStack.getAttributeQName(
 522    attributeURI, attributeLocalName, name);
 523   
 524  6270 add(factory.createAttribute(this, attributeQName,
 525    attributeValue));
 526    }
 527    } else {
 528  1618 List list = attributeList(size);
 529   
 530  1618 list.clear();
 531   
 532  1618 for (int i = 0; i < size; i++) {
 533    // optimised to avoid the call to attribute(QName) to
 534    // lookup an attribute for a given QName
 535  4190 String attributeName = attributes.getQName(i);
 536   
 537  4190 if (noNamespaceAttributes
 538    || !attributeName.startsWith("xmlns")) {
 539  4185 String attributeURI = attributes.getURI(i);
 540   
 541  4185 String attributeLocalName = attributes.getLocalName(i);
 542   
 543  4185 String attributeValue = attributes.getValue(i);
 544   
 545  4185 QName attributeQName = namespaceStack
 546    .getAttributeQName(attributeURI,
 547    attributeLocalName, attributeName);
 548   
 549  4185 Attribute attribute = factory.createAttribute(this,
 550    attributeQName, attributeValue);
 551   
 552  4185 list.add(attribute);
 553   
 554  4185 childAdded(attribute);
 555    }
 556    }
 557    }
 558    }
 559    }
 560   
 561  1984 public String attributeValue(String name) {
 562  1984 Attribute attrib = attribute(name);
 563   
 564  1984 if (attrib == null) {
 565  586 return null;
 566    } else {
 567  1398 return attrib.getValue();
 568    }
 569    }
 570   
 571  4 public String attributeValue(QName qName) {
 572  4 Attribute attrib = attribute(qName);
 573   
 574  4 if (attrib == null) {
 575  2 return null;
 576    } else {
 577  2 return attrib.getValue();
 578    }
 579    }
 580   
 581  7 public String attributeValue(String name, String defaultValue) {
 582  7 String answer = attributeValue(name);
 583   
 584  7 return (answer != null) ? answer : defaultValue;
 585    }
 586   
 587  0 public String attributeValue(QName qName, String defaultValue) {
 588  0 String answer = attributeValue(qName);
 589   
 590  0 return (answer != null) ? answer : defaultValue;
 591    }
 592   
 593    /**
 594    * DOCUMENT ME!
 595    *
 596    * @param name
 597    * DOCUMENT ME!
 598    * @param value
 599    * DOCUMENT ME!
 600    *
 601    * @deprecated As of version 0.5. Please use {@link
 602    * #addAttribute(String,String)} instead. WILL BE REMOVED IN
 603    * dom4j-1.6 !!
 604    */
 605  0 public void setAttributeValue(String name, String value) {
 606  0 addAttribute(name, value);
 607    }
 608   
 609    /**
 610    * DOCUMENT ME!
 611    *
 612    * @param qName
 613    * DOCUMENT ME!
 614    * @param value
 615    * DOCUMENT ME!
 616    *
 617    * @deprecated As of version 0.5. Please use {@link
 618    * #addAttribute(String,String)} instead. WILL BE REMOVED IN
 619    * dom4j-1.6 !!
 620    */
 621  0 public void setAttributeValue(QName qName, String value) {
 622  0 addAttribute(qName, value);
 623    }
 624   
 625  0 public void add(Attribute attribute) {
 626  0 if (attribute.getParent() != null) {
 627  0 String message = "The Attribute already has an existing parent \""
 628    + attribute.getParent().getQualifiedName() + "\"";
 629   
 630  0 throw new IllegalAddException(this, attribute, message);
 631    }
 632   
 633  0 if (attribute.getValue() == null) {
 634    // try remove a previous attribute with the same
 635    // name since adding an attribute with a null value
 636    // is equivalent to removing it.
 637  0 Attribute oldAttribute = attribute(attribute.getQName());
 638   
 639  0 if (oldAttribute != null) {
 640  0 remove(oldAttribute);
 641    }
 642    } else {
 643  0 attributeList().add(attribute);
 644   
 645  0 childAdded(attribute);
 646    }
 647    }
 648   
 649  0 public boolean remove(Attribute attribute) {
 650  0 List list = attributeList();
 651   
 652  0 boolean answer = list.remove(attribute);
 653   
 654  0 if (answer) {
 655  0 childRemoved(attribute);
 656    } else {
 657    // we may have a copy of the attribute
 658  0 Attribute copy = attribute(attribute.getQName());
 659   
 660  0 if (copy != null) {
 661  0 list.remove(copy);
 662   
 663  0 answer = true;
 664    }
 665    }
 666   
 667  0 return answer;
 668    }
 669   
 670    // Processing instruction API
 671    // -------------------------------------------------------------------------
 672  0 public List processingInstructions() {
 673  0 List list = contentList();
 674   
 675  0 BackedList answer = createResultList();
 676   
 677  0 int size = list.size();
 678   
 679  0 for (int i = 0; i < size; i++) {
 680  0 Object object = list.get(i);
 681   
 682  0 if (object instanceof ProcessingInstruction) {
 683  0 answer.addLocal(object);
 684    }
 685    }
 686   
 687  0 return answer;
 688    }
 689   
 690  0 public List processingInstructions(String target) {
 691  0 List list = contentList();
 692   
 693  0 BackedList answer = createResultList();
 694   
 695  0 int size = list.size();
 696   
 697  0 for (int i = 0; i < size; i++) {
 698  0 Object object = list.get(i);
 699   
 700  0 if (object instanceof ProcessingInstruction) {
 701  0 ProcessingInstruction pi = (ProcessingInstruction) object;
 702   
 703  0 if (target.equals(pi.getName())) {
 704  0 answer.addLocal(pi);
 705    }
 706    }
 707    }
 708   
 709  0 return answer;
 710    }
 711   
 712  0 public ProcessingInstruction processingInstruction(String target) {
 713  0 List list = contentList();
 714   
 715  0 int size = list.size();
 716   
 717  0 for (int i = 0; i < size; i++) {
 718  0 Object object = list.get(i);
 719   
 720  0 if (object instanceof ProcessingInstruction) {
 721  0 ProcessingInstruction pi = (ProcessingInstruction) object;
 722   
 723  0 if (target.equals(pi.getName())) {
 724  0 return pi;
 725    }
 726    }
 727    }
 728   
 729  0 return null;
 730    }
 731   
 732  0 public boolean removeProcessingInstruction(String target) {
 733  0 List list = contentList();
 734   
 735  0 for (Iterator iter = list.iterator(); iter.hasNext();) {
 736  0 Object object = iter.next();
 737   
 738  0 if (object instanceof ProcessingInstruction) {
 739  0 ProcessingInstruction pi = (ProcessingInstruction) object;
 740   
 741  0 if (target.equals(pi.getName())) {
 742  0 iter.remove();
 743   
 744  0 return true;
 745    }
 746    }
 747    }
 748   
 749  0 return false;
 750    }
 751   
 752    // Content Model methods
 753    // -------------------------------------------------------------------------
 754  2 public Node getXPathResult(int index) {
 755  2 Node answer = node(index);
 756   
 757  2 if ((answer != null) && !answer.supportsParent()) {
 758  0 return answer.asXPathResult(this);
 759    }
 760   
 761  2 return answer;
 762    }
 763   
 764  1631 public Element addAttribute(String name, String value) {
 765    // adding a null value is equivalent to removing the attribute
 766  1631 Attribute attribute = attribute(name);
 767   
 768  1631 if (value != null) {
 769  1628 if (attribute == null) {
 770  1627 add(getDocumentFactory().createAttribute(this, name, value));
 771  1 } else if (attribute.isReadOnly()) {
 772  0 remove(attribute);
 773   
 774  0 add(getDocumentFactory().createAttribute(this, name, value));
 775    } else {
 776  1 attribute.setValue(value);
 777    }
 778  3 } else if (attribute != null) {
 779  2 remove(attribute);
 780    }
 781   
 782  1631 return this;
 783    }
 784   
 785  2845 public Element addAttribute(QName qName, String value) {
 786    // adding a null value is equivalent to removing the attribute
 787  2845 Attribute attribute = attribute(qName);
 788   
 789  2845 if (value != null) {
 790  2843 if (attribute == null) {
 791  2843 add(getDocumentFactory().createAttribute(this, qName, value));
 792  0 } else if (attribute.isReadOnly()) {
 793  0 remove(attribute);
 794   
 795  0 add(getDocumentFactory().createAttribute(this, qName, value));
 796    } else {
 797  0 attribute.setValue(value);
 798    }
 799  2 } else if (attribute != null) {
 800  1 remove(attribute);
 801    }
 802   
 803  2845 return this;
 804    }
 805   
 806  102 public Element addCDATA(String cdata) {
 807  102 CDATA node = getDocumentFactory().createCDATA(cdata);
 808   
 809  102 addNewNode(node);
 810   
 811  102 return this;
 812    }
 813   
 814  491 public Element addComment(String comment) {
 815  491 Comment node = getDocumentFactory().createComment(comment);
 816   
 817  491 addNewNode(node);
 818   
 819  491 return this;
 820    }
 821   
 822  1654 public Element addElement(String name) {
 823  1654 DocumentFactory factory = getDocumentFactory();
 824   
 825  1654 int index = name.indexOf(":");
 826   
 827  1654 String prefix = "";
 828   
 829  1654 String localName = name;
 830   
 831  1654 Namespace namespace = null;
 832   
 833  1654 if (index > 0) {
 834  2 prefix = name.substring(0, index);
 835   
 836  2 localName = name.substring(index + 1);
 837   
 838  2 namespace = getNamespaceForPrefix(prefix);
 839   
 840  2 if (namespace == null) {
 841  0 throw new IllegalAddException("No such namespace prefix: "
 842    + prefix + " is in scope on: " + this
 843    + " so cannot add element: " + name);
 844    }
 845    } else {
 846  1652 namespace = getNamespaceForPrefix("");
 847    }
 848   
 849  1654 Element node;
 850   
 851  1654 if (namespace != null) {
 852  1654 QName qname = factory.createQName(localName, namespace);
 853   
 854  1654 node = factory.createElement(qname);
 855    } else {
 856  0 node = factory.createElement(name);
 857    }
 858   
 859  1654 addNewNode(node);
 860   
 861  1654 return node;
 862    }
 863   
 864  4 public Element addEntity(String name, String text) {
 865  4 Entity node = getDocumentFactory().createEntity(name, text);
 866   
 867  4 addNewNode(node);
 868   
 869  4 return this;
 870    }
 871   
 872  11 public Element addNamespace(String prefix, String uri) {
 873  11 Namespace node = getDocumentFactory().createNamespace(prefix, uri);
 874   
 875  11 addNewNode(node);
 876   
 877  11 return this;
 878    }
 879   
 880  1 public Element addProcessingInstruction(String target, String data) {
 881  1 ProcessingInstruction node = getDocumentFactory()
 882    .createProcessingInstruction(target, data);
 883   
 884  1 addNewNode(node);
 885   
 886  1 return this;
 887    }
 888   
 889  0 public Element addProcessingInstruction(String target, Map data) {
 890  0 ProcessingInstruction node = getDocumentFactory()
 891    .createProcessingInstruction(target, data);
 892   
 893  0 addNewNode(node);
 894   
 895  0 return this;
 896    }
 897   
 898  121732 public Element addText(String text) {
 899  121732 Text node = getDocumentFactory().createText(text);
 900   
 901  121732 addNewNode(node);
 902   
 903  121732 return this;
 904    }
 905   
 906    // polymorphic node methods
 907  370 public void add(Node node) {
 908  370 switch (node.getNodeType()) {
 909  128 case ELEMENT_NODE:
 910  128 add((Element) node);
 911   
 912  128 break;
 913   
 914  0 case ATTRIBUTE_NODE:
 915  0 add((Attribute) node);
 916   
 917  0 break;
 918   
 919  231 case TEXT_NODE:
 920  231 add((Text) node);
 921   
 922  231 break;
 923   
 924  0 case CDATA_SECTION_NODE:
 925  0 add((CDATA) node);
 926   
 927  0 break;
 928   
 929  0 case ENTITY_REFERENCE_NODE:
 930  0 add((Entity) node);
 931   
 932  0 break;
 933   
 934  0 case PROCESSING_INSTRUCTION_NODE:
 935  0 add((ProcessingInstruction) node);
 936   
 937  0 break;
 938   
 939  3 case COMMENT_NODE:
 940  3 add((Comment) node);
 941   
 942  3 break;
 943   
 944    /*
 945    * XXXX: to do! case DOCUMENT_TYPE_NODE: add((DocumentType) node);
 946    * break;
 947    */
 948  8 case NAMESPACE_NODE:
 949  8 add((Namespace) node);
 950   
 951  8 break;
 952   
 953  0 default:
 954  0 invalidNodeTypeAddException(node);
 955    }
 956    }
 957   
 958  1515 public boolean remove(Node node) {
 959  1515 switch (node.getNodeType()) {
 960  1513 case ELEMENT_NODE:
 961  1513 return remove((Element) node);
 962   
 963  2 case ATTRIBUTE_NODE:
 964  2 return remove((Attribute) node);
 965   
 966  0 case TEXT_NODE:
 967  0 return remove((Text) node);
 968   
 969  0 case CDATA_SECTION_NODE:
 970  0 return remove((CDATA) node);
 971   
 972  0 case ENTITY_REFERENCE_NODE:
 973  0 return remove((Entity) node);
 974   
 975  0 case PROCESSING_INSTRUCTION_NODE:
 976  0 return remove((ProcessingInstruction) node);
 977   
 978  0 case COMMENT_NODE:
 979  0 return remove((Comment) node);
 980   
 981    /*
 982    * case DOCUMENT_TYPE_NODE: return remove((DocumentType) node);
 983    */
 984  0 case NAMESPACE_NODE:
 985  0 return remove((Namespace) node);
 986   
 987  0 default:
 988  0 return false;
 989    }
 990    }
 991   
 992    // typesafe versions using node classes
 993  0 public void add(CDATA cdata) {
 994  0 addNode(cdata);
 995    }
 996   
 997  3 public void add(Comment comment) {
 998  3 addNode(comment);
 999    }
 1000   
 1001  89668 public void add(Element element) {
 1002  89668 addNode(element);
 1003    }
 1004   
 1005  0 public void add(Entity entity) {
 1006  0 addNode(entity);
 1007    }
 1008   
 1009  5944 public void add(Namespace namespace) {
 1010  5944 addNode(namespace);
 1011    }
 1012   
 1013  0 public void add(ProcessingInstruction pi) {
 1014  0 addNode(pi);
 1015    }
 1016   
 1017  231 public void add(Text text) {
 1018  231 addNode(text);
 1019    }
 1020   
 1021  0 public boolean remove(CDATA cdata) {
 1022  0 return removeNode(cdata);
 1023    }
 1024   
 1025  0 public boolean remove(Comment comment) {
 1026  0 return removeNode(comment);
 1027    }
 1028   
 1029  1513 public boolean remove(Element element) {
 1030  1513 return removeNode(element);
 1031    }
 1032   
 1033  0 public boolean remove(Entity entity) {
 1034  0 return removeNode(entity);
 1035    }
 1036   
 1037  3 public boolean remove(Namespace namespace) {
 1038  3 return removeNode(namespace);
 1039    }
 1040   
 1041  0 public boolean remove(ProcessingInstruction pi) {
 1042  0 return removeNode(pi);
 1043    }
 1044   
 1045  12026 public boolean remove(Text text) {
 1046  12026 return removeNode(text);
 1047    }
 1048   
 1049    // Helper methods
 1050    // -------------------------------------------------------------------------
 1051  0 public boolean hasMixedContent() {
 1052  0 List content = contentList();
 1053   
 1054  0 if ((content == null) || content.isEmpty() || (content.size() < 2)) {
 1055  0 return false;
 1056    }
 1057   
 1058  0 Class prevClass = null;
 1059   
 1060  0 for (Iterator iter = content.iterator(); iter.hasNext();) {
 1061  0 Object object = iter.next();
 1062   
 1063  0 Class newClass = object.getClass();
 1064   
 1065  0 if (newClass != prevClass) {
 1066  0 if (prevClass != null) {
 1067  0 return true;
 1068    }
 1069   
 1070  0 prevClass = newClass;
 1071    }
 1072    }
 1073   
 1074  0 return false;
 1075    }
 1076   
 1077  2 public boolean isTextOnly() {
 1078  2 List content = contentList();
 1079   
 1080  2 if ((content == null) || content.isEmpty()) {
 1081  0 return true;
 1082    }
 1083   
 1084  2 for (Iterator iter = content.iterator(); iter.hasNext();) {
 1085  2 Object object = iter.next();
 1086   
 1087  2 if (!(object instanceof CharacterData)
 1088    && !(object instanceof String)) {
 1089  1 return false;
 1090    }
 1091    }
 1092   
 1093  1 return true;
 1094    }
 1095   
 1096  2017 public void setText(String text) {
 1097    /* remove all text nodes */
 1098  2017 List allContent = contentList();
 1099   
 1100  2017 if (allContent != null) {
 1101  2017 Iterator it = allContent.iterator();
 1102   
 1103  2017 while (it.hasNext()) {
 1104  9 Node node = (Node) it.next();
 1105   
 1106  9 switch (node.getNodeType()) {
 1107  0 case CDATA_SECTION_NODE:
 1108   
 1109    // case ENTITY_NODE:
 1110  0 case ENTITY_REFERENCE_NODE:
 1111  8 case TEXT_NODE:
 1112  8 it.remove();
 1113   
 1114  1 default:
 1115  9 break;
 1116    }
 1117    }
 1118    }
 1119   
 1120  2017 addText(text);
 1121    }
 1122   
 1123  0 public String getStringValue() {
 1124  0 List list = contentList();
 1125   
 1126  0 int size = list.size();
 1127   
 1128  0 if (size > 0) {
 1129  0 if (size == 1) {
 1130    // optimised to avoid StringBuffer creation
 1131  0 return getContentAsStringValue(list.get(0));
 1132    } else {
 1133  0 StringBuffer buffer = new StringBuffer();
 1134   
 1135  0 for (int i = 0; i < size; i++) {
 1136  0 Object node = list.get(i);
 1137   
 1138  0 String string = getContentAsStringValue(node);
 1139   
 1140  0 if (string.length() > 0) {
 1141  0 if (USE_STRINGVALUE_SEPARATOR) {
 1142  0 if (buffer.length() > 0) {
 1143  0 buffer.append(' ');
 1144    }
 1145    }
 1146   
 1147  0 buffer.append(string);
 1148    }
 1149    }
 1150   
 1151  0 return buffer.toString();
 1152    }
 1153    }
 1154   
 1155  0 return "";
 1156    }
 1157   
 1158    /**
 1159    * Puts all <code>Text</code> nodes in the full depth of the sub-tree
 1160    * underneath this <code>Node</code>, including attribute nodes, into a
 1161    * "normal" form where only structure (e.g., elements, comments, processing
 1162    * instructions, CDATA sections, and entity references) separates
 1163    * <code>Text</code> nodes, i.e., there are neither adjacent
 1164    * <code>Text</code> nodes nor empty <code>Text</code> nodes. This can
 1165    * be used to ensure that the DOM view of a document is the same as if it
 1166    * were saved and re-loaded, and is useful when operations (such as XPointer
 1167    * lookups) that depend on a particular document tree structure are to be
 1168    * used.In cases where the document contains <code>CDATASections</code>,
 1169    * the normalize operation alone may not be sufficient, since XPointers do
 1170    * not differentiate between <code>Text</code> nodes and
 1171    * <code>CDATASection</code> nodes.
 1172    *
 1173    * @since DOM Level 2
 1174    */
 1175  42766 public void normalize() {
 1176  42766 List content = contentList();
 1177   
 1178  42766 Text previousText = null;
 1179   
 1180  42766 int i = 0;
 1181   
 1182  42766 while (i < content.size()) {
 1183  133130 Node node = (Node) content.get(i);
 1184   
 1185  133130 if (node instanceof Text) {
 1186  89266 Text text = (Text) node;
 1187   
 1188  89266 if (previousText != null) {
 1189  12026 previousText.appendText(text.getText());
 1190   
 1191  12026 remove(text);
 1192    } else {
 1193  77240 String value = text.getText();
 1194   
 1195    // only remove empty Text nodes, not whitespace nodes
 1196    // if ( value == null || value.trim().length() <= 0 ) {
 1197  77240 if ((value == null) || (value.length() <= 0)) {
 1198  0 remove(text);
 1199    } else {
 1200  77240 previousText = text;
 1201   
 1202  77240 i++;
 1203    }
 1204    }
 1205    } else {
 1206  43864 if (node instanceof Element) {
 1207  42656 Element element = (Element) node;
 1208   
 1209  42656 element.normalize();
 1210    }
 1211   
 1212  43864 previousText = null;
 1213   
 1214  43864 i++;
 1215    }
 1216    }
 1217    }
 1218   
 1219  0 public String elementText(String name) {
 1220  0 Element element = element(name);
 1221   
 1222  0 return (element != null) ? element.getText() : null;
 1223    }
 1224   
 1225  0 public String elementText(QName qName) {
 1226  0 Element element = element(qName);
 1227   
 1228  0 return (element != null) ? element.getText() : null;
 1229    }
 1230   
 1231  0 public String elementTextTrim(String name) {
 1232  0 Element element = element(name);
 1233   
 1234  0 return (element != null) ? element.getTextTrim() : null;
 1235    }
 1236   
 1237  0 public String elementTextTrim(QName qName) {
 1238  0 Element element = element(qName);
 1239   
 1240  0 return (element != null) ? element.getTextTrim() : null;
 1241    }
 1242   
 1243    // add to me content from another element
 1244    // analagous to the addAll(collection) methods in Java 2 collections
 1245  134 public void appendAttributes(Element element) {
 1246  134 for (int i = 0, size = element.attributeCount(); i < size; i++) {
 1247  58 Attribute attribute = element.attribute(i);
 1248   
 1249  58 if (attribute.supportsParent()) {
 1250  58 addAttribute(attribute.getQName(), attribute.getValue());
 1251    } else {
 1252  0 add(attribute);
 1253    }
 1254    }
 1255    }
 1256   
 1257    /**
 1258    * <p>
 1259    * This returns a deep clone of this element. The new element is detached
 1260    * from its parent, and getParent() on the clone will return null.
 1261    * </p>
 1262    *
 1263    * @return the clone of this element
 1264    */
 1265   
 1266    /*
 1267    * public Object clone() { Element clone = createElement(getQName());
 1268    * clone.appendAttributes(this); clone.appendContent(this); return clone; }
 1269    */
 1270  5 public Element createCopy() {
 1271  5 Element clone = createElement(getQName());
 1272   
 1273  5 clone.appendAttributes(this);
 1274   
 1275  5 clone.appendContent(this);
 1276   
 1277  5 return clone;
 1278    }
 1279   
 1280  0 public Element createCopy(String name) {
 1281  0 Element clone = createElement(name);
 1282   
 1283  0 clone.appendAttributes(this);
 1284   
 1285  0 clone.appendContent(this);
 1286   
 1287  0 return clone;
 1288    }
 1289   
 1290  0 public Element createCopy(QName qName) {
 1291  0 Element clone = createElement(qName);
 1292   
 1293  0 clone.appendAttributes(this);
 1294   
 1295  0 clone.appendContent(this);
 1296   
 1297  0 return clone;
 1298    }
 1299   
 1300  7005 public QName getQName(String qualifiedName) {
 1301  7005 String prefix = "";
 1302   
 1303  7005 String localName = qualifiedName;
 1304   
 1305  7005 int index = qualifiedName.indexOf(":");
 1306   
 1307  7005 if (index > 0) {
 1308  5004 prefix = qualifiedName.substring(0, index);
 1309   
 1310  5004 localName = qualifiedName.substring(index + 1);
 1311    }
 1312   
 1313  7005 Namespace namespace = getNamespaceForPrefix(prefix);
 1314   
 1315  7005 if (namespace != null) {
 1316  7005 return getDocumentFactory().createQName(localName, namespace);
 1317    } else {
 1318  0 return getDocumentFactory().createQName(localName);
 1319    }
 1320    }
 1321   
 1322  0 public Namespace getNamespaceForPrefix(String prefix) {
 1323  0 if (prefix == null) {
 1324  0 prefix = "";
 1325    }
 1326   
 1327  0 if (prefix.equals(getNamespacePrefix())) {
 1328  0 return getNamespace();
 1329  0 } else if (prefix.equals("xml")) {
 1330  0 return Namespace.XML_NAMESPACE;
 1331    } else {
 1332  0 List list = contentList();
 1333   
 1334  0 int size = list.size();
 1335   
 1336  0 for (int i = 0; i < size; i++) {
 1337  0 Object object = list.get(i);
 1338   
 1339  0 if (object instanceof Namespace) {
 1340  0 Namespace namespace = (Namespace) object;
 1341   
 1342  0 if (prefix.equals(namespace.getPrefix())) {
 1343  0 return namespace;
 1344    }
 1345    }
 1346    }
 1347    }
 1348   
 1349  0 Element parent = getParent();
 1350   
 1351  0 if (parent != null) {
 1352  0 Namespace answer = parent.getNamespaceForPrefix(prefix);
 1353   
 1354  0 if (answer != null) {
 1355  0 return answer;
 1356    }
 1357    }
 1358   
 1359  0 if ((prefix == null) || (prefix.length() <= 0)) {
 1360  0 return Namespace.NO_NAMESPACE;
 1361    }
 1362   
 1363  0 return null;
 1364    }
 1365   
 1366  0 public Namespace getNamespaceForURI(String uri) {
 1367  0 if ((uri == null) || (uri.length() <= 0)) {
 1368  0 return Namespace.NO_NAMESPACE;
 1369  0 } else if (uri.equals(getNamespaceURI())) {
 1370  0 return getNamespace();
 1371    } else {
 1372  0 List list = contentList();
 1373   
 1374  0 int size = list.size();
 1375   
 1376  0 for (int i = 0; i < size; i++) {
 1377  0 Object object = list.get(i);
 1378   
 1379  0 if (object instanceof Namespace) {
 1380  0 Namespace namespace = (Namespace) object;
 1381   
 1382  0 if (uri.equals(namespace.getURI())) {
 1383  0 return namespace;
 1384    }
 1385    }
 1386    }
 1387   
 1388  0 return null;
 1389    }
 1390    }
 1391   
 1392  1 public List getNamespacesForURI(String uri) {
 1393  1 BackedList answer = createResultList();
 1394   
 1395    // if (getNamespaceURI().equals(uri)) {
 1396    //
 1397    // answer.addLocal(getNamespace());
 1398    //
 1399    // }
 1400  1 List list = contentList();
 1401   
 1402  1 int size = list.size();
 1403   
 1404  1 for (int i = 0; i < size; i++) {
 1405  4 Object object = list.get(i);
 1406   
 1407  4 if ((object instanceof Namespace)
 1408    && ((Namespace) object).getURI().equals(uri)) {
 1409  2 answer.addLocal(object);
 1410    }
 1411    }
 1412   
 1413  1 return answer;
 1414    }
 1415   
 1416  0 public List declaredNamespaces() {
 1417  0 BackedList answer = createResultList();
 1418   
 1419    // if (getNamespaceURI().length() > 0) {
 1420    //
 1421    // answer.addLocal(getNamespace());
 1422    //
 1423    // }
 1424    //
 1425  0 List list = contentList();
 1426   
 1427  0 int size = list.size();
 1428   
 1429  0 for (int i = 0; i < size; i++) {
 1430  0 Object object = list.get(i);
 1431   
 1432  0 if (object instanceof Namespace) {
 1433  0 answer.addLocal(object);
 1434    }
 1435    }
 1436   
 1437  0 return answer;
 1438    }
 1439   
 1440  0 public List additionalNamespaces() {
 1441  0 List list = contentList();
 1442   
 1443  0 int size = list.size();
 1444   
 1445  0 BackedList answer = createResultList();
 1446   
 1447  0 for (int i = 0; i < size; i++) {
 1448  0 Object object = list.get(i);
 1449   
 1450  0 if (object instanceof Namespace) {
 1451  0 Namespace namespace = (Namespace) object;
 1452   
 1453  0 if (!namespace.equals(getNamespace())) {
 1454  0 answer.addLocal(namespace);
 1455    }
 1456    }
 1457    }
 1458   
 1459  0 return answer;
 1460    }
 1461   
 1462  0 public List additionalNamespaces(String defaultNamespaceURI) {
 1463  0 List list = contentList();
 1464   
 1465  0 BackedList answer = createResultList();
 1466   
 1467  0 int size = list.size();
 1468   
 1469  0 for (int i = 0; i < size; i++) {
 1470  0 Object object = list.get(i);
 1471   
 1472  0 if (object instanceof Namespace) {
 1473  0 Namespace namespace = (Namespace) object;
 1474   
 1475  0 if (!defaultNamespaceURI.equals(namespace.getURI())) {
 1476  0 answer.addLocal(namespace);
 1477    }
 1478    }
 1479    }
 1480   
 1481  0 return answer;
 1482    }
 1483   
 1484    // Implementation helper methods
 1485    // -------------------------------------------------------------------------
 1486   
 1487    /**
 1488    * Ensures that the list of attributes has the given size
 1489    *
 1490    * @param minCapacity
 1491    * DOCUMENT ME!
 1492    */
 1493  0 public void ensureAttributesCapacity(int minCapacity) {
 1494  0 if (minCapacity > 1) {
 1495  0 List list = attributeList();
 1496   
 1497  0 if (list instanceof ArrayList) {
 1498  0 ArrayList arrayList = (ArrayList) list;
 1499   
 1500  0 arrayList.ensureCapacity(minCapacity);
 1501    }
 1502    }
 1503    }
 1504   
 1505    // Implementation methods
 1506    // -------------------------------------------------------------------------
 1507  0 protected Element createElement(String name) {
 1508  0 return getDocumentFactory().createElement(name);
 1509    }
 1510   
 1511  4 protected Element createElement(QName qName) {
 1512  4 return getDocumentFactory().createElement(qName);
 1513    }
 1514   
 1515  95996 protected void addNode(Node node) {
 1516  95996 if (node.getParent() != null) {
 1517    // XXX: could clone here
 1518  1 String message = "The Node already has an existing parent of \""
 1519    + node.getParent().getQualifiedName() + "\"";
 1520   
 1521  1 throw new IllegalAddException(this, node, message);
 1522    }
 1523   
 1524  95995 addNewNode(node);
 1525    }
 1526   
 1527  8 protected void addNode(int index, Node node) {
 1528  8 if (node.getParent() != null) {
 1529    // XXX: could clone here
 1530  1 String message = "The Node already has an existing parent of \""
 1531    + node.getParent().getQualifiedName() + "\"";
 1532   
 1533  1 throw new IllegalAddException(this, node, message);
 1534    }
 1535   
 1536  7 addNewNode(index, node);
 1537    }
 1538   
 1539    /**
 1540    * Like addNode() but does not require a parent check
 1541    *
 1542    * @param node
 1543    * DOCUMENT ME!
 1544    */
 1545  0 protected void addNewNode(Node node) {
 1546  0 contentList().add(node);
 1547   
 1548  0 childAdded(node);
 1549    }
 1550   
 1551  7 protected void addNewNode(int index, Node node) {
 1552  7 contentList().add(index, node);
 1553   
 1554  7 childAdded(node);
 1555    }
 1556   
 1557  0 protected boolean removeNode(Node node) {
 1558  0 boolean answer = contentList().remove(node);
 1559   
 1560  0 if (answer) {
 1561  0 childRemoved(node);
 1562    }
 1563   
 1564  0 return answer;
 1565    }
 1566   
 1567    /**
 1568    * Called when a new child node is added to create any parent relationships
 1569    *
 1570    * @param node
 1571    * DOCUMENT ME!
 1572    */
 1573  234937 protected void childAdded(Node node) {
 1574  234937 if (node != null) {
 1575  234937 node.setParent(this);
 1576    }
 1577    }
 1578   
 1579  13560 protected void childRemoved(Node node) {
 1580  13560 if (node != null) {
 1581  13560 node.setParent(null);
 1582   
 1583  13560 node.setDocument(null);
 1584    }
 1585    }
 1586   
 1587    /**
 1588    * DOCUMENT ME!
 1589    *
 1590    * @return the internal List used to store attributes or creates one if one
 1591    * is not available
 1592    */
 1593    protected abstract List attributeList();
 1594   
 1595    /**
 1596    * DOCUMENT ME!
 1597    *
 1598    * @param attributeCount
 1599    * DOCUMENT ME!
 1600    *
 1601    * @return the internal List used to store attributes or creates one with
 1602    * the specified size if one is not available
 1603    */
 1604    protected abstract List attributeList(int attributeCount);
 1605   
 1606  1 protected DocumentFactory getDocumentFactory() {
 1607  1 QName qName = getQName();
 1608   
 1609    // QName might be null as we might not have been constructed yet
 1610  1 if (qName != null) {
 1611  0 DocumentFactory factory = qName.getDocumentFactory();
 1612   
 1613  0 if (factory != null) {
 1614  0 return factory;
 1615    }
 1616    }
 1617   
 1618  1 return DOCUMENT_FACTORY;
 1619    }
 1620   
 1621    /**
 1622    * A Factory Method pattern which creates a List implementation used to
 1623    * store attributes
 1624    *
 1625    * @return DOCUMENT ME!
 1626    */
 1627  28757 protected List createAttributeList() {
 1628  28757 return createAttributeList(DEFAULT_CONTENT_LIST_SIZE);
 1629    }
 1630   
 1631    /**
 1632    * A Factory Method pattern which creates a List implementation used to
 1633    * store attributes
 1634    *
 1635    * @param size
 1636    * DOCUMENT ME!
 1637    *
 1638    * @return DOCUMENT ME!
 1639    */
 1640  30375 protected List createAttributeList(int size) {
 1641  30375 return new ArrayList(size);
 1642    }
 1643   
 1644  62118 protected Iterator createSingleIterator(Object result) {
 1645  62118 return new SingleIterator(result);
 1646    }
 1647    }
 1648   
 1649    /*
 1650    * Redistribution and use of this software and associated documentation
 1651    * ("Software"), with or without modification, are permitted provided that the
 1652    * following conditions are met:
 1653    *
 1654    * 1. Redistributions of source code must retain copyright statements and
 1655    * notices. Redistributions must also contain a copy of this document.
 1656    *
 1657    * 2. Redistributions in binary form must reproduce the above copyright notice,
 1658    * this list of conditions and the following disclaimer in the documentation
 1659    * and/or other materials provided with the distribution.
 1660    *
 1661    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 1662    * from this Software without prior written permission of MetaStuff, Ltd. For
 1663    * written permission, please contact dom4j-info@metastuff.com.
 1664    *
 1665    * 4. Products derived from this Software may not be called "DOM4J" nor may
 1666    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 1667    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 1668    *
 1669    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 1670    *
 1671    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 1672    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 1673    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 1674    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 1675    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 1676    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 1677    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 1678    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 1679    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 1680    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 1681    * POSSIBILITY OF SUCH DAMAGE.
 1682    *
 1683    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 1684    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/AbstractEntity.html0000644000175000017500000007614310242117724022712 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 108   Methods: 9
NCLOC: 40   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
AbstractEntity.java 0% 8,3% 22,2% 12%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.io.IOException;
 11    import java.io.Writer;
 12   
 13    import org.dom4j.Element;
 14    import org.dom4j.Entity;
 15    import org.dom4j.Visitor;
 16   
 17    /**
 18    * <p>
 19    * <code>AbstractEntity</code> is an abstract base class for tree implementors
 20    * to use for implementation inheritence.
 21    * </p>
 22    *
 23    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 24    * @version $Revision: 1.15 $
 25    */
 26    public abstract class AbstractEntity extends AbstractNode implements Entity {
 27  4 public AbstractEntity() {
 28    }
 29   
 30  2 public short getNodeType() {
 31  2 return ENTITY_REFERENCE_NODE;
 32    }
 33   
 34  0 public String getPath(Element context) {
 35    // From XPaths perspective, entities are included in text
 36  0 Element parent = getParent();
 37   
 38  0 return ((parent != null) && (parent != context)) ? (parent
 39    .getPath(context) + "/text()") : "text()";
 40    }
 41   
 42  0 public String getUniquePath(Element context) {
 43    // From XPaths perspective, entities are included in text
 44  0 Element parent = getParent();
 45   
 46  0 return ((parent != null) && (parent != context)) ? (parent
 47    .getUniquePath(context) + "/text()") : "text()";
 48    }
 49   
 50  0 public String toString() {
 51  0 return super.toString() + " [Entity: &" + getName() + ";]";
 52    }
 53   
 54  0 public String getStringValue() {
 55  0 return "&" + getName() + ";";
 56    }
 57   
 58  0 public String asXML() {
 59  0 return "&" + getName() + ";";
 60    }
 61   
 62  0 public void write(Writer writer) throws IOException {
 63  0 writer.write("&");
 64  0 writer.write(getName());
 65  0 writer.write(";");
 66    }
 67   
 68  0 public void accept(Visitor visitor) {
 69  0 visitor.visit(this);
 70    }
 71    }
 72   
 73    /*
 74    * Redistribution and use of this software and associated documentation
 75    * ("Software"), with or without modification, are permitted provided that the
 76    * following conditions are met:
 77    *
 78    * 1. Redistributions of source code must retain copyright statements and
 79    * notices. Redistributions must also contain a copy of this document.
 80    *
 81    * 2. Redistributions in binary form must reproduce the above copyright notice,
 82    * this list of conditions and the following disclaimer in the documentation
 83    * and/or other materials provided with the distribution.
 84    *
 85    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 86    * from this Software without prior written permission of MetaStuff, Ltd. For
 87    * written permission, please contact dom4j-info@metastuff.com.
 88    *
 89    * 4. Products derived from this Software may not be called "DOM4J" nor may
 90    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 91    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 92    *
 93    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 94    *
 95    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 96    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 97    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 98    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 99    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 100    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 101    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 102    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 103    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 104    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 105    * POSSIBILITY OF SUCH DAMAGE.
 106    *
 107    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 108    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/DefaultComment.html0000644000175000017500000007277110242117752022665 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 105   Methods: 7
NCLOC: 27   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DefaultComment.java - 50% 57,1% 53,3%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import org.dom4j.Element;
 11   
 12    /**
 13    * <p>
 14    * <code>DefaultComment</code> is the default Comment implementation. It is a
 15    * doubly linked node which supports the parent relationship and can be modified
 16    * in place.
 17    * </p>
 18    *
 19    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 20    * @version $Revision: 1.11 $
 21    */
 22    public class DefaultComment extends FlyweightComment {
 23    /** The parent of this node */
 24    private Element parent;
 25   
 26    /**
 27    * DOCUMENT ME!
 28    *
 29    * @param text
 30    * is the Comment text
 31    */
 32  515 public DefaultComment(String text) {
 33  515 super(text);
 34    }
 35   
 36    /**
 37    * DOCUMENT ME!
 38    *
 39    * @param parent
 40    * is the parent element
 41    * @param text
 42    * is the Comment text
 43    */
 44  0 public DefaultComment(Element parent, String text) {
 45  0 super(text);
 46  0 this.parent = parent;
 47    }
 48   
 49  0 public void setText(String text) {
 50  0 this.text = text;
 51    }
 52   
 53  58 public Element getParent() {
 54  58 return parent;
 55    }
 56   
 57  497 public void setParent(Element parent) {
 58  497 this.parent = parent;
 59    }
 60   
 61  0 public boolean supportsParent() {
 62  0 return true;
 63    }
 64   
 65  3 public boolean isReadOnly() {
 66  3 return false;
 67    }
 68    }
 69   
 70    /*
 71    * Redistribution and use of this software and associated documentation
 72    * ("Software"), with or without modification, are permitted provided that the
 73    * following conditions are met:
 74    *
 75    * 1. Redistributions of source code must retain copyright statements and
 76    * notices. Redistributions must also contain a copy of this document.
 77    *
 78    * 2. Redistributions in binary form must reproduce the above copyright notice,
 79    * this list of conditions and the following disclaimer in the documentation
 80    * and/or other materials provided with the distribution.
 81    *
 82    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 83    * from this Software without prior written permission of MetaStuff, Ltd. For
 84    * written permission, please contact dom4j-info@metastuff.com.
 85    *
 86    * 4. Products derived from this Software may not be called "DOM4J" nor may
 87    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 88    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 89    *
 90    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 91    *
 92    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 93    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 94    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 95    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 96    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 97    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 98    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 99    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 100    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 101    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 102    * POSSIBILITY OF SUCH DAMAGE.
 103    *
 104    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 105    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/DefaultText.html0000644000175000017500000007302510242117731022175 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 105   Methods: 7
NCLOC: 27   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DefaultText.java - 75% 85,7% 80%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import org.dom4j.Element;
 11   
 12    /**
 13    * <p>
 14    * <code>DefaultText</code> is the default Text implementation. It is a doubly
 15    * linked node which supports the parent relationship and can be modified in
 16    * place.
 17    * </p>
 18    *
 19    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 20    * @version $Revision: 1.11 $
 21    */
 22    public class DefaultText extends FlyweightText {
 23    /** The parent of this node */
 24    private Element parent;
 25   
 26    /**
 27    * DOCUMENT ME!
 28    *
 29    * @param text
 30    * is the Text text
 31    */
 32  121763 public DefaultText(String text) {
 33  121763 super(text);
 34    }
 35   
 36    /**
 37    * DOCUMENT ME!
 38    *
 39    * @param parent
 40    * is the parent element
 41    * @param text
 42    * is the Text text
 43    */
 44  0 public DefaultText(Element parent, String text) {
 45  0 super(text);
 46  0 this.parent = parent;
 47    }
 48   
 49  12026 public void setText(String text) {
 50  12026 this.text = text;
 51    }
 52   
 53  266 public Element getParent() {
 54  266 return parent;
 55    }
 56   
 57  134189 public void setParent(Element parent) {
 58  134189 this.parent = parent;
 59    }
 60   
 61  6 public boolean supportsParent() {
 62  6 return true;
 63    }
 64   
 65  200 public boolean isReadOnly() {
 66  200 return false;
 67    }
 68    }
 69   
 70    /*
 71    * Redistribution and use of this software and associated documentation
 72    * ("Software"), with or without modification, are permitted provided that the
 73    * following conditions are met:
 74    *
 75    * 1. Redistributions of source code must retain copyright statements and
 76    * notices. Redistributions must also contain a copy of this document.
 77    *
 78    * 2. Redistributions in binary form must reproduce the above copyright notice,
 79    * this list of conditions and the following disclaimer in the documentation
 80    * and/or other materials provided with the distribution.
 81    *
 82    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 83    * from this Software without prior written permission of MetaStuff, Ltd. For
 84    * written permission, please contact dom4j-info@metastuff.com.
 85    *
 86    * 4. Products derived from this Software may not be called "DOM4J" nor may
 87    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 88    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 89    *
 90    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 91    *
 92    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 93    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 94    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 95    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 96    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 97    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 98    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 99    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 100    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 101    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 102    * POSSIBILITY OF SUCH DAMAGE.
 103    *
 104    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 105    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/DefaultEntity.html0000644000175000017500000010416110242117711022517 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 123   Methods: 9
NCLOC: 33   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DefaultEntity.java - 20% 22,2% 21,1%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import org.dom4j.Element;
 11   
 12    /**
 13    * <p>
 14    * <code>DefaultEntity</code> is the default Entity implementation. It is a
 15    * doubly linked node which supports the parent relationship and can be modified
 16    * in place.
 17    * </p>
 18    *
 19    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 20    * @version $Revision: 1.11 $
 21    */
 22    public class DefaultEntity extends FlyweightEntity {
 23    /** The parent of this node */
 24    private Element parent;
 25   
 26    /**
 27    * Creates the <code>Entity</code> with the specified name
 28    *
 29    * @param name
 30    * is the name of the entity
 31    */
 32  0 public DefaultEntity(String name) {
 33  0 super(name);
 34    }
 35   
 36    /**
 37    * Creates the <code>Entity</code> with the specified name and text.
 38    *
 39    * @param name
 40    * is the name of the entity
 41    * @param text
 42    * is the text of the entity
 43    */
 44  4 public DefaultEntity(String name, String text) {
 45  4 super(name, text);
 46    }
 47   
 48    /**
 49    * Creates the <code>Entity</code> with the specified name and text.
 50    *
 51    * @param parent
 52    * is the parent element
 53    * @param name
 54    * is the name of the entity
 55    * @param text
 56    * is the text of the entity
 57    */
 58  0 public DefaultEntity(Element parent, String name, String text) {
 59  0 super(name, text);
 60  0 this.parent = parent;
 61    }
 62   
 63  0 public void setName(String name) {
 64  0 this.name = name;
 65    }
 66   
 67  0 public void setText(String text) {
 68  0 this.text = text;
 69    }
 70   
 71  0 public Element getParent() {
 72  0 return parent;
 73    }
 74   
 75  4 public void setParent(Element parent) {
 76  4 this.parent = parent;
 77    }
 78   
 79  0 public boolean supportsParent() {
 80  0 return true;
 81    }
 82   
 83  0 public boolean isReadOnly() {
 84  0 return false;
 85    }
 86    }
 87   
 88    /*
 89    * Redistribution and use of this software and associated documentation
 90    * ("Software"), with or without modification, are permitted provided that the
 91    * following conditions are met:
 92    *
 93    * 1. Redistributions of source code must retain copyright statements and
 94    * notices. Redistributions must also contain a copy of this document.
 95    *
 96    * 2. Redistributions in binary form must reproduce the above copyright notice,
 97    * this list of conditions and the following disclaimer in the documentation
 98    * and/or other materials provided with the distribution.
 99    *
 100    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 101    * from this Software without prior written permission of MetaStuff, Ltd. For
 102    * written permission, please contact dom4j-info@metastuff.com.
 103    *
 104    * 4. Products derived from this Software may not be called "DOM4J" nor may
 105    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 106    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 107    *
 108    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 109    *
 110    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 111    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 112    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 113    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 114    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 115    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 116    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 117    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 118    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 119    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 120    * POSSIBILITY OF SUCH DAMAGE.
 121    *
 122    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 123    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/AbstractCDATA.html0000644000175000017500000007134210242117730022243 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 101   Methods: 6
NCLOC: 35   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
AbstractCDATA.java 100% 90,9% 83,3% 89,5%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.io.IOException;
 11    import java.io.StringWriter;
 12    import java.io.Writer;
 13   
 14    import org.dom4j.CDATA;
 15    import org.dom4j.Visitor;
 16   
 17    /**
 18    * <p>
 19    * <code>AbstractCDATA</code> is an abstract base class for tree implementors
 20    * to use for implementation inheritence.
 21    * </p>
 22    *
 23    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 24    * @version $Revision: 1.12 $
 25    */
 26    public abstract class AbstractCDATA extends AbstractCharacterData implements
 27    CDATA {
 28  105 public AbstractCDATA() {
 29    }
 30   
 31  386 public short getNodeType() {
 32  386 return CDATA_SECTION_NODE;
 33    }
 34   
 35  180 public String toString() {
 36  180 return super.toString() + " [CDATA: \"" + getText() + "\"]";
 37    }
 38   
 39  2 public String asXML() {
 40  2 StringWriter writer = new StringWriter();
 41   
 42  2 try {
 43  2 write(writer);
 44    } catch (IOException e) {
 45    // will not happen since we are using a StringWriter!
 46    }
 47   
 48  2 return writer.toString();
 49    }
 50   
 51  2 public void write(Writer writer) throws IOException {
 52  2 writer.write("<![CDATA[");
 53   
 54  2 if (getText() != null) {
 55  1 writer.write(getText());
 56    }
 57   
 58  2 writer.write("]]>");
 59    }
 60   
 61  0 public void accept(Visitor visitor) {
 62  0 visitor.visit(this);
 63    }
 64    }
 65   
 66    /*
 67    * Redistribution and use of this software and associated documentation
 68    * ("Software"), with or without modification, are permitted provided that the
 69    * following conditions are met:
 70    *
 71    * 1. Redistributions of source code must retain copyright statements and
 72    * notices. Redistributions must also contain a copy of this document.
 73    *
 74    * 2. Redistributions in binary form must reproduce the above copyright notice,
 75    * this list of conditions and the following disclaimer in the documentation
 76    * and/or other materials provided with the distribution.
 77    *
 78    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 79    * from this Software without prior written permission of MetaStuff, Ltd. For
 80    * written permission, please contact dom4j-info@metastuff.com.
 81    *
 82    * 4. Products derived from this Software may not be called "DOM4J" nor may
 83    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 84    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 85    *
 86    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 87    *
 88    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 89    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 90    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 91    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 92    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 93    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 94    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 95    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 96    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 97    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 98    * POSSIBILITY OF SUCH DAMAGE.
 99    *
 100    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 101    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/FlyweightText.html0000644000175000017500000006103310242117563022552 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 86   Methods: 3
NCLOC: 16   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
FlyweightText.java - 66,7% 66,7% 66,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import org.dom4j.Element;
 11    import org.dom4j.Node;
 12    import org.dom4j.Text;
 13   
 14    /**
 15    * <p>
 16    * <code>FlyweightText</code> is a Flyweight pattern implementation of a
 17    * singly linked, read-only XML Text.
 18    * </p>
 19    *
 20    * <p>
 21    * This node could be shared across documents and elements though it does not
 22    * support the parent relationship.
 23    * </p>
 24    *
 25    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 26    * @version $Revision: 1.7 $
 27    */
 28    public class FlyweightText extends AbstractText implements Text {
 29    /** Text of the <code>Text</code> node */
 30    protected String text;
 31   
 32    /**
 33    * DOCUMENT ME!
 34    *
 35    * @param text
 36    * is the Text text
 37    */
 38  121763 public FlyweightText(String text) {
 39  121763 this.text = text;
 40    }
 41   
 42  392739 public String getText() {
 43  392739 return text;
 44    }
 45   
 46  0 protected Node createXPathResult(Element parent) {
 47  0 return new DefaultText(parent, getText());
 48    }
 49    }
 50   
 51    /*
 52    * Redistribution and use of this software and associated documentation
 53    * ("Software"), with or without modification, are permitted provided that the
 54    * following conditions are met:
 55    *
 56    * 1. Redistributions of source code must retain copyright statements and
 57    * notices. Redistributions must also contain a copy of this document.
 58    *
 59    * 2. Redistributions in binary form must reproduce the above copyright notice,
 60    * this list of conditions and the following disclaimer in the documentation
 61    * and/or other materials provided with the distribution.
 62    *
 63    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 64    * from this Software without prior written permission of MetaStuff, Ltd. For
 65    * written permission, please contact dom4j-info@metastuff.com.
 66    *
 67    * 4. Products derived from this Software may not be called "DOM4J" nor may
 68    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 69    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 70    *
 71    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 72    *
 73    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 74    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 75    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 76    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 77    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 78    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 79    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 80    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 81    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 82    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 83    * POSSIBILITY OF SUCH DAMAGE.
 84    *
 85    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 86    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/AbstractText.html0000644000175000017500000006131210242117742022352 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 85   Methods: 6
NCLOC: 24   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
AbstractText.java - 60% 66,7% 63,6%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.io.IOException;
 11    import java.io.Writer;
 12   
 13    import org.dom4j.Visitor;
 14   
 15    /**
 16    * <p>
 17    * <code>AbstractText</code> is an abstract base class for tree implementors
 18    * to use for implementation inheritence.
 19    * </p>
 20    *
 21    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 22    * @version $Revision: 1.10 $
 23    */
 24    public abstract class AbstractText extends AbstractCharacterData implements
 25    org.dom4j.Text {
 26  121763 public AbstractText() {
 27    }
 28   
 29  192772 public short getNodeType() {
 30  192772 return TEXT_NODE;
 31    }
 32   
 33  77268 public String toString() {
 34  77268 return super.toString() + " [Text: \"" + getText() + "\"]";
 35    }
 36   
 37  2 public String asXML() {
 38  2 return getText();
 39    }
 40   
 41  0 public void write(Writer writer) throws IOException {
 42  0 writer.write(getText());
 43    }
 44   
 45  0 public void accept(Visitor visitor) {
 46  0 visitor.visit(this);
 47    }
 48    }
 49   
 50    /*
 51    * Redistribution and use of this software and associated documentation
 52    * ("Software"), with or without modification, are permitted provided that the
 53    * following conditions are met:
 54    *
 55    * 1. Redistributions of source code must retain copyright statements and
 56    * notices. Redistributions must also contain a copy of this document.
 57    *
 58    * 2. Redistributions in binary form must reproduce the above copyright notice,
 59    * this list of conditions and the following disclaimer in the documentation
 60    * and/or other materials provided with the distribution.
 61    *
 62    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 63    * from this Software without prior written permission of MetaStuff, Ltd. For
 64    * written permission, please contact dom4j-info@metastuff.com.
 65    *
 66    * 4. Products derived from this Software may not be called "DOM4J" nor may
 67    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 68    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 69    *
 70    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 71    *
 72    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 73    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 74    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 75    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 76    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 77    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 78    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 79    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 80    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 81    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 82    * POSSIBILITY OF SUCH DAMAGE.
 83    *
 84    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 85    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/BackedList.html0000644000175000017500000016547010242117766021767 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 209   Methods: 13
NCLOC: 110   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
BackedList.java 37,5% 49,1% 61,5% 47,9%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.util.ArrayList;
 11    import java.util.Collection;
 12    import java.util.Iterator;
 13    import java.util.List;
 14   
 15    import org.dom4j.IllegalAddException;
 16    import org.dom4j.Node;
 17   
 18    /**
 19    * <p>
 20    * <code>BackedList</code> represents a list of content of a {@link
 21    * org.dom4j.Branch}. Changes to the list will be reflected in the branch,
 22    * though changes to the branch will not be reflected in this list.
 23    * </p>
 24    *
 25    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 26    * @version $Revision: 1.14 $
 27    */
 28    public class BackedList extends ArrayList {
 29    /** The content of the Branch which is modified if I am modified */
 30    private List branchContent;
 31   
 32    /** The <code>AbstractBranch</code> instance which owns the content */
 33    private AbstractBranch branch;
 34   
 35  24169 public BackedList(AbstractBranch branch, List branchContent) {
 36  24169 this(branch, branchContent, branchContent.size());
 37    }
 38   
 39  24171 public BackedList(AbstractBranch branch, List branchContent, int capacity) {
 40  24171 super(capacity);
 41  24171 this.branch = branch;
 42  24171 this.branchContent = branchContent;
 43    }
 44   
 45  0 public BackedList(AbstractBranch branch, List branchContent,
 46    List initialContent) {
 47  0 super(initialContent);
 48  0 this.branch = branch;
 49  0 this.branchContent = branchContent;
 50    }
 51   
 52  150 public boolean add(Object object) {
 53  150 branch.addNode(asNode(object));
 54   
 55  150 return super.add(object);
 56    }
 57   
 58  8 public void add(int index, Object object) {
 59  8 int size = size();
 60   
 61  8 if (index < 0) {
 62  0 throw new IndexOutOfBoundsException("Index value: " + index
 63    + " is less than zero");
 64  8 } else if (index > size) {
 65  0 throw new IndexOutOfBoundsException("Index value: " + index
 66    + " cannot be greater than " + "the size: " + size);
 67    }
 68   
 69  8 int realIndex;
 70   
 71  8 if (size == 0) {
 72  0 realIndex = branchContent.size();
 73  8 } else if (index < size) {
 74  5 realIndex = branchContent.indexOf(get(index));
 75    } else {
 76  3 realIndex = branchContent.indexOf(get(size - 1)) + 1;
 77    }
 78   
 79  8 branch.addNode(realIndex, asNode(object));
 80  7 super.add(index, object);
 81    }
 82   
 83  0 public Object set(int index, Object object) {
 84  0 int realIndex = branchContent.indexOf(get(index));
 85   
 86  0 if (realIndex < 0) {
 87  0 realIndex = (index == 0) ? 0 : Integer.MAX_VALUE;
 88    }
 89   
 90  0 if (realIndex < branchContent.size()) {
 91  0 branch.removeNode(asNode(get(index)));
 92  0 branch.addNode(realIndex, asNode(object));
 93    } else {
 94  0 branch.removeNode(asNode(get(index)));
 95  0 branch.addNode(asNode(object));
 96    }
 97   
 98  0 branch.childAdded(asNode(object));
 99   
 100  0 return super.set(index, object);
 101    }
 102   
 103  0 public boolean remove(Object object) {
 104  0 branch.removeNode(asNode(object));
 105   
 106  0 return super.remove(object);
 107    }
 108   
 109  3 public Object remove(int index) {
 110  3 Object object = super.remove(index);
 111   
 112  3 if (object != null) {
 113  3 branch.removeNode(asNode(object));
 114    }
 115   
 116  3 return object;
 117    }
 118   
 119  0 public boolean addAll(Collection collection) {
 120  0 ensureCapacity(size() + collection.size());
 121   
 122  0 int count = size();
 123   
 124  0 for (Iterator iter = collection.iterator(); iter.hasNext(); count--) {
 125  0 add(iter.next());
 126    }
 127   
 128  0 return count != 0;
 129    }
 130   
 131  0 public boolean addAll(int index, Collection collection) {
 132  0 ensureCapacity(size() + collection.size());
 133   
 134  0 int count = size();
 135   
 136  0 for (Iterator iter = collection.iterator(); iter.hasNext(); count--) {
 137  0 add(index++, iter.next());
 138    }
 139   
 140  0 return count != 0;
 141    }
 142   
 143  3 public void clear() {
 144  3 for (Iterator iter = iterator(); iter.hasNext();) {
 145  3 Object object = iter.next();
 146  3 branchContent.remove(object);
 147  3 branch.childRemoved(asNode(object));
 148    }
 149   
 150  3 super.clear();
 151    }
 152   
 153    /**
 154    * Performs a local addition which is not forward through to the Branch or
 155    * backing list
 156    *
 157    * @param object
 158    * DOCUMENT ME!
 159    */
 160  4970 public void addLocal(Object object) {
 161  4970 super.add(object);
 162    }
 163   
 164  164 protected Node asNode(Object object) {
 165  164 if (object instanceof Node) {
 166  164 return (Node) object;
 167    } else {
 168  0 throw new IllegalAddException("This list must contain instances "
 169    + "of Node. Invalid type: " + object);
 170    }
 171    }
 172    }
 173   
 174    /*
 175    * Redistribution and use of this software and associated documentation
 176    * ("Software"), with or without modification, are permitted provided that the
 177    * following conditions are met:
 178    *
 179    * 1. Redistributions of source code must retain copyright statements and
 180    * notices. Redistributions must also contain a copy of this document.
 181    *
 182    * 2. Redistributions in binary form must reproduce the above copyright notice,
 183    * this list of conditions and the following disclaimer in the documentation
 184    * and/or other materials provided with the distribution.
 185    *
 186    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 187    * from this Software without prior written permission of MetaStuff, Ltd. For
 188    * written permission, please contact dom4j-info@metastuff.com.
 189    *
 190    * 4. Products derived from this Software may not be called "DOM4J" nor may
 191    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 192    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 193    *
 194    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 195    *
 196    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 197    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 198    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 199    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 200    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 201    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 202    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 203    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 204    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 205    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 206    * POSSIBILITY OF SUCH DAMAGE.
 207    *
 208    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 209    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/DefaultAttribute.html0000644000175000017500000011656710242117740023225 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 143   Methods: 11
NCLOC: 43   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DefaultAttribute.java - 46,2% 54,5% 50%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import org.dom4j.Element;
 11    import org.dom4j.Namespace;
 12    import org.dom4j.QName;
 13   
 14    /**
 15    * <p>
 16    * <code>DefaultAttribute</code> implements a doubly linked node which
 17    * supports the parent relationship and is mutable.
 18    * </p>
 19    *
 20    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 21    * @version $Revision: 1.13 $
 22    */
 23    public class DefaultAttribute extends FlyweightAttribute {
 24    /** The parent of this node */
 25    private Element parent;
 26   
 27  0 public DefaultAttribute(QName qname) {
 28  0 super(qname);
 29    }
 30   
 31  14283 public DefaultAttribute(QName qname, String value) {
 32  14283 super(qname, value);
 33    }
 34   
 35  0 public DefaultAttribute(Element parent, QName qname, String value) {
 36  0 super(qname, value);
 37  0 this.parent = parent;
 38    }
 39   
 40    /**
 41    * Creates the <code>Attribute</code> with the specified local name and
 42    * value.
 43    *
 44    * @param name
 45    * is the name of the attribute
 46    * @param value
 47    * is the value of the attribute
 48    */
 49  0 public DefaultAttribute(String name, String value) {
 50  0 super(name, value);
 51    }
 52   
 53    /**
 54    * Creates the <code>Attribute</code> with the specified local name, value
 55    * and <code>Namespace</code>.
 56    *
 57    * @param name
 58    * is the name of the attribute
 59    * @param value
 60    * is the value of the attribute
 61    * @param namespace
 62    * is the namespace of the attribute
 63    */
 64  0 public DefaultAttribute(String name, String value, Namespace namespace) {
 65  0 super(name, value, namespace);
 66    }
 67   
 68    /**
 69    * Creates the <code>Attribute</code> with the specified local name, value
 70    * and <code>Namespace</code>.
 71    *
 72    * @param parent
 73    * is the parent element
 74    * @param name
 75    * is the name of the attribute
 76    * @param value
 77    * is the value of the attribute
 78    * @param namespace
 79    * is the namespace of the attribute
 80    */
 81  0 public DefaultAttribute(Element parent, String name, String value,
 82    Namespace namespace) {
 83  0 super(name, value, namespace);
 84  0 this.parent = parent;
 85    }
 86   
 87  1 public void setValue(String value) {
 88  1 this.value = value;
 89    }
 90   
 91  10781 public Element getParent() {
 92  10781 return parent;
 93    }
 94   
 95  14289 public void setParent(Element parent) {
 96  14289 this.parent = parent;
 97    }
 98   
 99  70 public boolean supportsParent() {
 100  70 return true;
 101    }
 102   
 103  1 public boolean isReadOnly() {
 104  1 return false;
 105    }
 106    }
 107   
 108    /*
 109    * Redistribution and use of this software and associated documentation
 110    * ("Software"), with or without modification, are permitted provided that the
 111    * following conditions are met:
 112    *
 113    * 1. Redistributions of source code must retain copyright statements and
 114    * notices. Redistributions must also contain a copy of this document.
 115    *
 116    * 2. Redistributions in binary form must reproduce the above copyright notice,
 117    * this list of conditions and the following disclaimer in the documentation
 118    * and/or other materials provided with the distribution.
 119    *
 120    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 121    * from this Software without prior written permission of MetaStuff, Ltd. For
 122    * written permission, please contact dom4j-info@metastuff.com.
 123    *
 124    * 4. Products derived from this Software may not be called "DOM4J" nor may
 125    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 126    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 127    *
 128    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 129    *
 130    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 131    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 132    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 133    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 134    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 135    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 136    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 137    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 138    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 139    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 140    * POSSIBILITY OF SUCH DAMAGE.
 141    *
 142    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 143    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/DefaultNamespace.html0000644000175000017500000012071710242117624023147 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 147   Methods: 9
NCLOC: 44   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DefaultNamespace.java 66,7% 94,1% 100% 90,6%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import org.dom4j.Element;
 11    import org.dom4j.Namespace;
 12   
 13    /**
 14    * <p>
 15    * <code>DefaultNamespace</code> implements a doubly linked node which
 16    * supports the parent relationship and is mutable. It is useful when returning
 17    * results from XPath expressions.
 18    * </p>
 19    *
 20    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 21    * @version $Revision: 1.16 $
 22    */
 23    public class DefaultNamespace extends Namespace {
 24    /** The parent of this node */
 25    private Element parent;
 26   
 27    /**
 28    * DOCUMENT ME!
 29    *
 30    * @param prefix
 31    * is the prefix for this namespace
 32    * @param uri
 33    * is the URI for this namespace
 34    */
 35  159 public DefaultNamespace(String prefix, String uri) {
 36  159 super(prefix, uri);
 37    }
 38   
 39    /**
 40    * DOCUMENT ME!
 41    *
 42    * @param parent
 43    * is the parent element
 44    * @param prefix
 45    * is the prefix for this namespace
 46    * @param uri
 47    * is the URI for this namespace
 48    */
 49  107 public DefaultNamespace(Element parent, String prefix, String uri) {
 50  107 super(prefix, uri);
 51  107 this.parent = parent;
 52    }
 53   
 54    /**
 55    * DOCUMENT ME!
 56    *
 57    * @return the hash code based on the qualified name and the URI of the
 58    * namespace and the hashCode() of the parent element.
 59    */
 60  170 protected int createHashCode() {
 61  170 int hashCode = super.createHashCode();
 62   
 63  170 if (parent != null) {
 64  29 hashCode ^= parent.hashCode();
 65    }
 66   
 67  170 return hashCode;
 68    }
 69   
 70    /**
 71    * Implements an identity based comparsion using the parent element as well
 72    * as the prefix and URI
 73    *
 74    * @param object
 75    * DOCUMENT ME!
 76    *
 77    * @return DOCUMENT ME!
 78    */
 79  137 public boolean equals(Object object) {
 80  137 if (object instanceof DefaultNamespace) {
 81  137 DefaultNamespace that = (DefaultNamespace) object;
 82   
 83  137 if (that.parent == parent) {
 84  137 return super.equals(object);
 85    }
 86    }
 87   
 88  0 return false;
 89    }
 90   
 91  448 public int hashCode() {
 92  448 return super.hashCode();
 93    }
 94   
 95  581 public Element getParent() {
 96  581 return parent;
 97    }
 98   
 99  20 public void setParent(Element parent) {
 100  20 this.parent = parent;
 101    }
 102   
 103  29 public boolean supportsParent() {
 104  29 return true;
 105    }
 106   
 107  1 public boolean isReadOnly() {
 108  1 return false;
 109    }
 110    }
 111   
 112    /*
 113    * Redistribution and use of this software and associated documentation
 114    * ("Software"), with or without modification, are permitted provided that the
 115    * following conditions are met:
 116    *
 117    * 1. Redistributions of source code must retain copyright statements and
 118    * notices. Redistributions must also contain a copy of this document.
 119    *
 120    * 2. Redistributions in binary form must reproduce the above copyright notice,
 121    * this list of conditions and the following disclaimer in the documentation
 122    * and/or other materials provided with the distribution.
 123    *
 124    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 125    * from this Software without prior written permission of MetaStuff, Ltd. For
 126    * written permission, please contact dom4j-info@metastuff.com.
 127    *
 128    * 4. Products derived from this Software may not be called "DOM4J" nor may
 129    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 130    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 131    *
 132    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 133    *
 134    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 135    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 136    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 137    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 138    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 139    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 140    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 141    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 142    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 143    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 144    * POSSIBILITY OF SUCH DAMAGE.
 145    *
 146    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 147    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/AbstractComment.html0000644000175000017500000007332710242117712023036 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 103   Methods: 8
NCLOC: 38   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
AbstractComment.java 0% 18,2% 37,5% 21,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.io.IOException;
 11    import java.io.Writer;
 12   
 13    import org.dom4j.Comment;
 14    import org.dom4j.Element;
 15    import org.dom4j.Visitor;
 16   
 17    /**
 18    * <p>
 19    * <code>AbstractComment</code> is an abstract base class for tree
 20    * implementors to use for implementation inheritence.
 21    * </p>
 22    *
 23    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 24    * @version $Revision: 1.13 $
 25    */
 26    public abstract class AbstractComment extends AbstractCharacterData implements
 27    Comment {
 28  515 public AbstractComment() {
 29    }
 30   
 31  2085 public short getNodeType() {
 32  2085 return COMMENT_NODE;
 33    }
 34   
 35  0 public String getPath(Element context) {
 36  0 Element parent = getParent();
 37   
 38  0 return ((parent != null) && (parent != context)) ? (parent
 39    .getPath(context) + "/comment()") : "comment()";
 40    }
 41   
 42  0 public String getUniquePath(Element context) {
 43  0 Element parent = getParent();
 44   
 45  0 return ((parent != null) && (parent != context)) ? (parent
 46    .getUniquePath(context) + "/comment()") : "comment()";
 47    }
 48   
 49  816 public String toString() {
 50  816 return super.toString() + " [Comment: \"" + getText() + "\"]";
 51    }
 52   
 53  0 public String asXML() {
 54  0 return "<!--" + getText() + "-->";
 55    }
 56   
 57  0 public void write(Writer writer) throws IOException {
 58  0 writer.write("<!--");
 59  0 writer.write(getText());
 60  0 writer.write("-->");
 61    }
 62   
 63  0 public void accept(Visitor visitor) {
 64  0 visitor.visit(this);
 65    }
 66    }
 67   
 68    /*
 69    * Redistribution and use of this software and associated documentation
 70    * ("Software"), with or without modification, are permitted provided that the
 71    * following conditions are met:
 72    *
 73    * 1. Redistributions of source code must retain copyright statements and
 74    * notices. Redistributions must also contain a copy of this document.
 75    *
 76    * 2. Redistributions in binary form must reproduce the above copyright notice,
 77    * this list of conditions and the following disclaimer in the documentation
 78    * and/or other materials provided with the distribution.
 79    *
 80    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 81    * from this Software without prior written permission of MetaStuff, Ltd. For
 82    * written permission, please contact dom4j-info@metastuff.com.
 83    *
 84    * 4. Products derived from this Software may not be called "DOM4J" nor may
 85    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 86    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 87    *
 88    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 89    *
 90    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 91    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 92    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 93    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 94    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 95    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 96    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 97    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 98    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 99    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 100    * POSSIBILITY OF SUCH DAMAGE.
 101    *
 102    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 103    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/FlyweightComment.html0000644000175000017500000006104710242117755023240 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 86   Methods: 3
NCLOC: 16   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
FlyweightComment.java - 66,7% 66,7% 66,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import org.dom4j.Comment;
 11    import org.dom4j.Element;
 12    import org.dom4j.Node;
 13   
 14    /**
 15    * <p>
 16    * <code>FlyweightComment</code> is a Flyweight pattern implementation of a
 17    * singly linked, read-only XML Comment.
 18    * </p>
 19    *
 20    * <p>
 21    * This node could be shared across documents and elements though it does not
 22    * support the parent relationship.
 23    * </p>
 24    *
 25    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 26    * @version $Revision: 1.7 $
 27    */
 28    public class FlyweightComment extends AbstractComment implements Comment {
 29    /** Text of the <code>Comment</code> node */
 30    protected String text;
 31   
 32    /**
 33    * DOCUMENT ME!
 34    *
 35    * @param text
 36    * is the Comment text
 37    */
 38  515 public FlyweightComment(String text) {
 39  515 this.text = text;
 40    }
 41   
 42  3034 public String getText() {
 43  3034 return text;
 44    }
 45   
 46  0 protected Node createXPathResult(Element parent) {
 47  0 return new DefaultComment(parent, getText());
 48    }
 49    }
 50   
 51    /*
 52    * Redistribution and use of this software and associated documentation
 53    * ("Software"), with or without modification, are permitted provided that the
 54    * following conditions are met:
 55    *
 56    * 1. Redistributions of source code must retain copyright statements and
 57    * notices. Redistributions must also contain a copy of this document.
 58    *
 59    * 2. Redistributions in binary form must reproduce the above copyright notice,
 60    * this list of conditions and the following disclaimer in the documentation
 61    * and/or other materials provided with the distribution.
 62    *
 63    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 64    * from this Software without prior written permission of MetaStuff, Ltd. For
 65    * written permission, please contact dom4j-info@metastuff.com.
 66    *
 67    * 4. Products derived from this Software may not be called "DOM4J" nor may
 68    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 69    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 70    *
 71    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 72    *
 73    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 74    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 75    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 76    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 77    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 78    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 79    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 80    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 81    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 82    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 83    * POSSIBILITY OF SUCH DAMAGE.
 84    *
 85    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 86    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/AbstractProcessingInstruction.html0000644000175000017500000020110510242117750025777 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 235   Methods: 17
NCLOC: 121   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
AbstractProcessingInstruction.java 60% 50% 35,3% 49,5%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.io.IOException;
 11    import java.io.Writer;
 12    import java.util.HashMap;
 13    import java.util.Iterator;
 14    import java.util.Map;
 15    import java.util.StringTokenizer;
 16   
 17    import org.dom4j.Element;
 18    import org.dom4j.ProcessingInstruction;
 19    import org.dom4j.Visitor;
 20   
 21    /**
 22    * <p>
 23    * <code>AbstractProcessingInstruction</code> is an abstract base class for
 24    * tree implementors to use for implementation inheritence.
 25    * </p>
 26    *
 27    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 28    * @version $Revision: 1.17 $
 29    */
 30    public abstract class AbstractProcessingInstruction extends AbstractNode
 31    implements ProcessingInstruction {
 32  28 public AbstractProcessingInstruction() {
 33    }
 34   
 35  26 public short getNodeType() {
 36  26 return PROCESSING_INSTRUCTION_NODE;
 37    }
 38   
 39  0 public String getPath(Element context) {
 40  0 Element parent = getParent();
 41   
 42  0 return ((parent != null) && (parent != context)) ? (parent
 43    .getPath(context) + "/processing-instruction()")
 44    : "processing-instruction()";
 45    }
 46   
 47  0 public String getUniquePath(Element context) {
 48  0 Element parent = getParent();
 49   
 50  0 return ((parent != null) && (parent != context)) ? (parent
 51    .getUniquePath(context) + "/processing-instruction()")
 52    : "processing-instruction()";
 53    }
 54   
 55  0 public String toString() {
 56  0 return super.toString() + " [ProcessingInstruction: &" + getName()
 57    + ";]";
 58    }
 59   
 60  0 public String asXML() {
 61  0 return "<?" + getName() + " " + getText() + "?>";
 62    }
 63   
 64  0 public void write(Writer writer) throws IOException {
 65  0 writer.write("<?");
 66  0 writer.write(getName());
 67  0 writer.write(" ");
 68  0 writer.write(getText());
 69  0 writer.write("?>");
 70    }
 71   
 72  0 public void accept(Visitor visitor) {
 73  0 visitor.visit(this);
 74    }
 75   
 76  0 public void setValue(String name, String value) {
 77  0 throw new UnsupportedOperationException("This PI is read-only and "
 78    + "cannot be modified");
 79    }
 80   
 81  0 public void setValues(Map data) {
 82  0 throw new UnsupportedOperationException("This PI is read-only and "
 83    + "cannot be modified");
 84    }
 85   
 86  1 public String getName() {
 87  1 return getTarget();
 88    }
 89   
 90  0 public void setName(String name) {
 91  0 setTarget(name);
 92    }
 93   
 94  0 public boolean removeValue(String name) {
 95  0 return false;
 96    }
 97   
 98    // Helper methods
 99   
 100    /**
 101    * <p>
 102    * This will convert the Map to a string representation.
 103    * </p>
 104    *
 105    * @param values
 106    * is a <code>Map</code> of PI data to convert
 107    *
 108    * @return DOCUMENT ME!
 109    */
 110  0 protected String toString(Map values) {
 111  0 StringBuffer buffer = new StringBuffer();
 112   
 113  0 for (Iterator iter = values.entrySet().iterator(); iter.hasNext();) {
 114  0 Map.Entry entry = (Map.Entry) iter.next();
 115  0 String name = (String) entry.getKey();
 116  0 String value = (String) entry.getValue();
 117   
 118  0 buffer.append(name);
 119  0 buffer.append("=\"");
 120  0 buffer.append(value);
 121  0 buffer.append("\" ");
 122    }
 123   
 124    // remove the last space
 125  0 buffer.setLength(buffer.length() - 1);
 126   
 127  0 return buffer.toString();
 128    }
 129   
 130    /**
 131    * <p>
 132    * Parses the raw data of PI as a <code>Map</code>.
 133    * </p>
 134    *
 135    * @param text
 136    * <code>String</code> PI data to parse
 137    *
 138    * @return DOCUMENT ME!
 139    */
 140  28 protected Map parseValues(String text) {
 141  28 Map data = new HashMap();
 142   
 143  28 StringTokenizer s = new StringTokenizer(text, " =\'\"", true);
 144   
 145  28 while (s.hasMoreTokens()) {
 146  48 String name = getName(s);
 147   
 148  48 if (s.hasMoreTokens()) {
 149  41 String value = getValue(s);
 150  41 data.put(name, value);
 151    }
 152    }
 153   
 154  28 return data;
 155    }
 156   
 157  48 private String getName(StringTokenizer tokenizer) {
 158  48 String token = tokenizer.nextToken();
 159  48 StringBuffer name = new StringBuffer(token);
 160   
 161  48 while (tokenizer.hasMoreTokens()) {
 162  169 token = tokenizer.nextToken();
 163   
 164  169 if (!token.equals("=")) {
 165  128 name.append(token);
 166    } else {
 167  41 break;
 168    }
 169    }
 170   
 171  48 return name.toString().trim();
 172    }
 173   
 174  41 private String getValue(StringTokenizer tokenizer) {
 175  41 String token = tokenizer.nextToken();
 176  41 StringBuffer value = new StringBuffer();
 177   
 178    /* get the quote */
 179  41 while (tokenizer.hasMoreTokens() && !token.equals("\'")
 180    && !token.equals("\"")) {
 181  0 token = tokenizer.nextToken();
 182    }
 183   
 184  41 String quote = token;
 185   
 186  93 while (tokenizer.hasMoreTokens()) {
 187  93 token = tokenizer.nextToken();
 188   
 189  93 if (!quote.equals(token)) {
 190  52 value.append(token);
 191    } else {
 192  41 break;
 193    }
 194    }
 195   
 196  41 return value.toString();
 197    }
 198    }
 199   
 200    /*
 201    * Redistribution and use of this software and associated documentation
 202    * ("Software"), with or without modification, are permitted provided that the
 203    * following conditions are met:
 204    *
 205    * 1. Redistributions of source code must retain copyright statements and
 206    * notices. Redistributions must also contain a copy of this document.
 207    *
 208    * 2. Redistributions in binary form must reproduce the above copyright notice,
 209    * this list of conditions and the following disclaimer in the documentation
 210    * and/or other materials provided with the distribution.
 211    *
 212    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 213    * from this Software without prior written permission of MetaStuff, Ltd. For
 214    * written permission, please contact dom4j-info@metastuff.com.
 215    *
 216    * 4. Products derived from this Software may not be called "DOM4J" nor may
 217    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 218    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 219    *
 220    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 221    *
 222    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 223    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 224    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 225    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 226    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 227    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 228    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 229    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 230    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 231    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 232    * POSSIBILITY OF SUCH DAMAGE.
 233    *
 234    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 235    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/AbstractDocumentType.html0000644000175000017500000016250710242117737024062 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 203   Methods: 11
NCLOC: 107   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
AbstractDocumentType.java 40,9% 52,4% 54,5% 50%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.io.IOException;
 11    import java.io.Writer;
 12    import java.util.Iterator;
 13    import java.util.List;
 14   
 15    import org.dom4j.DocumentType;
 16    import org.dom4j.Element;
 17    import org.dom4j.Visitor;
 18   
 19    /**
 20    * <p>
 21    * <code>AbstractDocumentType</code> is an abstract base class for tree
 22    * implementors to use for implementation inheritence.
 23    * </p>
 24    *
 25    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 26    * @version $Revision: 1.17 $
 27    */
 28    public abstract class AbstractDocumentType extends AbstractNode implements
 29    DocumentType {
 30  14 public AbstractDocumentType() {
 31    }
 32   
 33  1 public short getNodeType() {
 34  1 return DOCUMENT_TYPE_NODE;
 35    }
 36   
 37  2 public String getName() {
 38  2 return getElementName();
 39    }
 40   
 41  0 public void setName(String name) {
 42  0 setElementName(name);
 43    }
 44   
 45  0 public String getPath(Element context) {
 46    // not available in XPath
 47  0 return "";
 48    }
 49   
 50  0 public String getUniquePath(Element context) {
 51    // not available in XPath
 52  0 return "";
 53    }
 54   
 55    /**
 56    * Returns the text format of the declarations if applicable, or the empty
 57    * String
 58    *
 59    * @return DOCUMENT ME!
 60    */
 61  0 public String getText() {
 62  0 List list = getInternalDeclarations();
 63   
 64  0 if ((list != null) && (list.size() > 0)) {
 65  0 StringBuffer buffer = new StringBuffer();
 66  0 Iterator iter = list.iterator();
 67   
 68  0 if (iter.hasNext()) {
 69  0 Object decl = iter.next();
 70  0 buffer.append(decl.toString());
 71   
 72  0 while (iter.hasNext()) {
 73  0 decl = iter.next();
 74  0 buffer.append("\n");
 75  0 buffer.append(decl.toString());
 76    }
 77    }
 78   
 79  0 return buffer.toString();
 80    }
 81   
 82  0 return "";
 83    }
 84   
 85  6 public String toString() {
 86  6 return super.toString() + " [DocumentType: " + asXML() + "]";
 87    }
 88   
 89  6 public String asXML() {
 90  6 StringBuffer buffer = new StringBuffer("<!DOCTYPE ");
 91  6 buffer.append(getElementName());
 92   
 93  6 boolean hasPublicID = false;
 94  6 String publicID = getPublicID();
 95   
 96  6 if ((publicID != null) && (publicID.length() > 0)) {
 97  0 buffer.append(" PUBLIC \"");
 98  0 buffer.append(publicID);
 99  0 buffer.append("\"");
 100  0 hasPublicID = true;
 101    }
 102   
 103  6 String systemID = getSystemID();
 104   
 105  6 if ((systemID != null) && (systemID.length() > 0)) {
 106  4 if (!hasPublicID) {
 107  4 buffer.append(" SYSTEM");
 108    }
 109   
 110  4 buffer.append(" \"");
 111  4 buffer.append(systemID);
 112  4 buffer.append("\"");
 113    }
 114   
 115  6 buffer.append(">");
 116   
 117  6 return buffer.toString();
 118    }
 119   
 120  1 public void write(Writer writer) throws IOException {
 121  1 writer.write("<!DOCTYPE ");
 122  1 writer.write(getElementName());
 123   
 124  1 boolean hasPublicID = false;
 125  1 String publicID = getPublicID();
 126   
 127  1 if ((publicID != null) && (publicID.length() > 0)) {
 128  0 writer.write(" PUBLIC \"");
 129  0 writer.write(publicID);
 130  0 writer.write("\"");
 131  0 hasPublicID = true;
 132    }
 133   
 134  1 String systemID = getSystemID();
 135   
 136  1 if ((systemID != null) && (systemID.length() > 0)) {
 137  0 if (!hasPublicID) {
 138  0 writer.write(" SYSTEM");
 139    }
 140   
 141  0 writer.write(" \"");
 142  0 writer.write(systemID);
 143  0 writer.write("\"");
 144    }
 145   
 146  1 List list = getInternalDeclarations();
 147   
 148  1 if ((list != null) && (list.size() > 0)) {
 149  1 writer.write(" [");
 150   
 151  1 for (Iterator iter = list.iterator(); iter.hasNext();) {
 152  10 Object decl = iter.next();
 153  10 writer.write("\n ");
 154  10 writer.write(decl.toString());
 155    }
 156   
 157  1 writer.write("\n]");
 158    }
 159   
 160  1 writer.write(">");
 161    }
 162   
 163  0 public void accept(Visitor visitor) {
 164  0 visitor.visit(this);
 165    }
 166    }
 167   
 168    /*
 169    * Redistribution and use of this software and associated documentation
 170    * ("Software"), with or without modification, are permitted provided that the
 171    * following conditions are met:
 172    *
 173    * 1. Redistributions of source code must retain copyright statements and
 174    * notices. Redistributions must also contain a copy of this document.
 175    *
 176    * 2. Redistributions in binary form must reproduce the above copyright notice,
 177    * this list of conditions and the following disclaimer in the documentation
 178    * and/or other materials provided with the distribution.
 179    *
 180    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 181    * from this Software without prior written permission of MetaStuff, Ltd. For
 182    * written permission, please contact dom4j-info@metastuff.com.
 183    *
 184    * 4. Products derived from this Software may not be called "DOM4J" nor may
 185    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 186    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 187    *
 188    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 189    *
 190    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 191    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 192    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 193    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 194    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 195    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 196    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 197    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 198    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 199    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 200    * POSSIBILITY OF SUCH DAMAGE.
 201    *
 202    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 203    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/DefaultProcessingInstruction.html0000644000175000017500000011733010242117726025631 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 145   Methods: 11
NCLOC: 44   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DefaultProcessingInstruction.java - 21,4% 27,3% 24%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.util.Map;
 11   
 12    import org.dom4j.Element;
 13   
 14    /**
 15    * <p>
 16    * <code>DefaultProcessingInstruction</code> is the default Processing
 17    * Instruction implementation. It is a doubly linked node which supports the
 18    * parent relationship and can be modified in place.
 19    * </p>
 20    *
 21    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 22    * @version $Revision: 1.13 $
 23    */
 24    public class DefaultProcessingInstruction extends
 25    org.dom4j.tree.FlyweightProcessingInstruction {
 26    /** The parent of this node */
 27    private Element parent;
 28   
 29    /**
 30    * <p>
 31    * This will create a new PI with the given target and values
 32    * </p>
 33    *
 34    * @param target
 35    * is the name of the PI
 36    * @param values
 37    * is the <code>Map</code> values for the PI
 38    */
 39  0 public DefaultProcessingInstruction(String target, Map values) {
 40  0 super(target, values);
 41    }
 42   
 43    /**
 44    * <p>
 45    * This will create a new PI with the given target and values
 46    * </p>
 47    *
 48    * @param target
 49    * is the name of the PI
 50    * @param values
 51    * is the values for the PI
 52    */
 53  28 public DefaultProcessingInstruction(String target, String values) {
 54  28 super(target, values);
 55    }
 56   
 57    /**
 58    * <p>
 59    * This will create a new PI with the given target and values
 60    * </p>
 61    *
 62    * @param parent
 63    * is the parent element
 64    * @param target
 65    * is the name of the PI
 66    * @param values
 67    * is the values for the PI
 68    */
 69  0 public DefaultProcessingInstruction(Element parent, String target,
 70    String values) {
 71  0 super(target, values);
 72  0 this.parent = parent;
 73    }
 74   
 75  0 public void setTarget(String target) {
 76  0 this.target = target;
 77    }
 78   
 79  0 public void setText(String text) {
 80  0 this.text = text;
 81  0 this.values = parseValues(text);
 82    }
 83   
 84  0 public void setValues(Map values) {
 85  0 this.values = values;
 86  0 this.text = toString(values);
 87    }
 88   
 89  0 public void setValue(String name, String value) {
 90  0 values.put(name, value);
 91    }
 92   
 93  25 public Element getParent() {
 94  25 return parent;
 95    }
 96   
 97  1 public void setParent(Element parent) {
 98  1 this.parent = parent;
 99    }
 100   
 101  0 public boolean supportsParent() {
 102  0 return true;
 103    }
 104   
 105  0 public boolean isReadOnly() {
 106  0 return false;
 107    }
 108    }
 109   
 110    /*
 111    * Redistribution and use of this software and associated documentation
 112    * ("Software"), with or without modification, are permitted provided that the
 113    * following conditions are met:
 114    *
 115    * 1. Redistributions of source code must retain copyright statements and
 116    * notices. Redistributions must also contain a copy of this document.
 117    *
 118    * 2. Redistributions in binary form must reproduce the above copyright notice,
 119    * this list of conditions and the following disclaimer in the documentation
 120    * and/or other materials provided with the distribution.
 121    *
 122    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 123    * from this Software without prior written permission of MetaStuff, Ltd. For
 124    * written permission, please contact dom4j-info@metastuff.com.
 125    *
 126    * 4. Products derived from this Software may not be called "DOM4J" nor may
 127    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 128    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 129    *
 130    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 131    *
 132    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 133    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 134    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 135    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 136    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 137    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 138    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 139    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 140    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 141    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 142    * POSSIBILITY OF SUCH DAMAGE.
 143    *
 144    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 145    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/DefaultDocumentType.html0000644000175000017500000013456610242117715023703 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 174   Methods: 13
NCLOC: 51   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DefaultDocumentType.java - 73,3% 76,9% 75%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.util.List;
 11   
 12    /**
 13    * <p>
 14    * <code>DefaultDocumentType</code> is the DOM4J default implementation of an
 15    * XML document type.
 16    * </p>
 17    *
 18    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 19    * @version $Revision: 1.10 $
 20    */
 21    public class DefaultDocumentType extends AbstractDocumentType {
 22    /** The root element name of the document typ */
 23    protected String elementName;
 24   
 25    /** Holds value of property publicID. */
 26    private String publicID;
 27   
 28    /** Holds value of property systemID. */
 29    private String systemID;
 30   
 31    /** The internal DTD declarations */
 32    private List internalDeclarations;
 33   
 34    /** The external DTD declarations */
 35    private List externalDeclarations;
 36   
 37  1 public DefaultDocumentType() {
 38    }
 39   
 40    /**
 41    * <p>
 42    * This will create a new <code>DocumentType</code> with a reference to
 43    * the external DTD
 44    * </p>
 45    *
 46    * @param elementName
 47    * is the root element name of the document type
 48    * @param systemID
 49    * is the system ID of the external DTD
 50    */
 51  0 public DefaultDocumentType(String elementName, String systemID) {
 52  0 this.elementName = elementName;
 53  0 this.systemID = systemID;
 54    }
 55   
 56    /**
 57    * <p>
 58    * This will create a new <code>DocumentType</code> with a reference to
 59    * the external DTD
 60    * </p>
 61    *
 62    * @param elementName
 63    * is the root element name of the document type
 64    * @param publicID
 65    * is the public ID of the DTD
 66    * @param systemID
 67    * is the system ID of the DTD
 68    */
 69  13 public DefaultDocumentType(String elementName, String publicID,
 70    String systemID) {
 71  13 this.elementName = elementName;
 72  13 this.publicID = publicID;
 73  13 this.systemID = systemID;
 74    }
 75   
 76  9 public String getElementName() {
 77  9 return elementName;
 78    }
 79   
 80  1 public void setElementName(String elementName) {
 81  1 this.elementName = elementName;
 82    }
 83   
 84    /**
 85    * DOCUMENT ME!
 86    *
 87    * @return the public ID of the document type
 88    */
 89  9 public String getPublicID() {
 90  9 return publicID;
 91    }
 92   
 93    /**
 94    * Sets the public ID of the document type
 95    *
 96    * @param publicID
 97    * DOCUMENT ME!
 98    */
 99  0 public void setPublicID(String publicID) {
 100  0 this.publicID = publicID;
 101    }
 102   
 103    /**
 104    * DOCUMENT ME!
 105    *
 106    * @return the system ID of the document type
 107    */
 108  9 public String getSystemID() {
 109  9 return systemID;
 110    }
 111   
 112    /**
 113    * Sets the system ID of the document type
 114    *
 115    * @param systemID
 116    * DOCUMENT ME!
 117    */
 118  0 public void setSystemID(String systemID) {
 119  0 this.systemID = systemID;
 120    }
 121   
 122  8 public List getInternalDeclarations() {
 123  8 return internalDeclarations;
 124    }
 125   
 126  6 public void setInternalDeclarations(List internalDeclarations) {
 127  6 this.internalDeclarations = internalDeclarations;
 128    }
 129   
 130  6 public List getExternalDeclarations() {
 131  6 return externalDeclarations;
 132    }
 133   
 134  5 public void setExternalDeclarations(List externalDeclarations) {
 135  5 this.externalDeclarations = externalDeclarations;
 136    }
 137    }
 138   
 139    /*
 140    * Redistribution and use of this software and associated documentation
 141    * ("Software"), with or without modification, are permitted provided that the
 142    * following conditions are met:
 143    *
 144    * 1. Redistributions of source code must retain copyright statements and
 145    * notices. Redistributions must also contain a copy of this document.
 146    *
 147    * 2. Redistributions in binary form must reproduce the above copyright notice,
 148    * this list of conditions and the following disclaimer in the documentation
 149    * and/or other materials provided with the distribution.
 150    *
 151    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 152    * from this Software without prior written permission of MetaStuff, Ltd. For
 153    * written permission, please contact dom4j-info@metastuff.com.
 154    *
 155    * 4. Products derived from this Software may not be called "DOM4J" nor may
 156    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 157    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 158    *
 159    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 160    *
 161    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 162    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 163    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 164    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 165    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 166    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 167    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 168    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 169    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 170    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 171    * POSSIBILITY OF SUCH DAMAGE.
 172    *
 173    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 174    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/AbstractNode.html0000644000175000017500000022607410242117605022321 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 271   Methods: 34
NCLOC: 161   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
AbstractNode.java 75% 70% 61,8% 67,9%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.io.IOException;
 11    import java.io.Serializable;
 12    import java.io.Writer;
 13    import java.util.List;
 14   
 15    import org.dom4j.Document;
 16    import org.dom4j.DocumentFactory;
 17    import org.dom4j.Element;
 18    import org.dom4j.Node;
 19    import org.dom4j.NodeFilter;
 20    import org.dom4j.XPath;
 21    import org.dom4j.rule.Pattern;
 22   
 23    /**
 24    * <p>
 25    * <code>AbstractNode</code> is an abstract base class for tree implementors
 26    * to use for implementation inheritence.
 27    * </p>
 28    *
 29    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 30    * @version $Revision: 1.31 $
 31    */
 32    public abstract class AbstractNode implements Node, Cloneable, Serializable {
 33    protected static final String[] NODE_TYPE_NAMES = {"Node", "Element",
 34    "Attribute", "Text", "CDATA", "Entity", "Entity",
 35    "ProcessingInstruction", "Comment", "Document", "DocumentType",
 36    "DocumentFragment", "Notation", "Namespace", "Unknown" };
 37   
 38    /** The <code>DocumentFactory</code> instance used by default */
 39    private static final DocumentFactory DOCUMENT_FACTORY = DocumentFactory
 40    .getInstance();
 41   
 42  250254 public AbstractNode() {
 43    }
 44   
 45  0 public short getNodeType() {
 46  0 return UNKNOWN_NODE;
 47    }
 48   
 49  130 public String getNodeTypeName() {
 50  130 int type = getNodeType();
 51   
 52  130 if ((type < 0) || (type >= NODE_TYPE_NAMES.length)) {
 53  0 return "Unknown";
 54    }
 55   
 56  130 return NODE_TYPE_NAMES[type];
 57    }
 58   
 59  94 public Document getDocument() {
 60  94 Element element = getParent();
 61   
 62  94 return (element != null) ? element.getDocument() : null;
 63    }
 64   
 65  12305 public void setDocument(Document document) {
 66    }
 67   
 68  12545 public Element getParent() {
 69  12545 return null;
 70    }
 71   
 72  6102 public void setParent(Element parent) {
 73    }
 74   
 75  107 public boolean supportsParent() {
 76  107 return false;
 77    }
 78   
 79  7 public boolean isReadOnly() {
 80  7 return true;
 81    }
 82   
 83  0 public boolean hasContent() {
 84  0 return false;
 85    }
 86   
 87  18 public String getPath() {
 88  18 return getPath(null);
 89    }
 90   
 91  20 public String getUniquePath() {
 92  20 return getUniquePath(null);
 93    }
 94   
 95  349 public Object clone() {
 96  349 if (isReadOnly()) {
 97  7 return this;
 98    } else {
 99  342 try {
 100  342 Node answer = (Node) super.clone();
 101  342 answer.setParent(null);
 102  342 answer.setDocument(null);
 103   
 104  342 return answer;
 105    } catch (CloneNotSupportedException e) {
 106    // should never happen
 107  0 throw new RuntimeException("This should never happen. Caught: "
 108    + e);
 109    }
 110    }
 111    }
 112   
 113  1517 public Node detach() {
 114  1517 Element parent = getParent();
 115   
 116  1517 if (parent != null) {
 117  1515 parent.remove(this);
 118    } else {
 119  2 Document document = getDocument();
 120   
 121  2 if (document != null) {
 122  2 document.remove(this);
 123    }
 124    }
 125   
 126  1517 setParent(null);
 127  1517 setDocument(null);
 128   
 129  1517 return this;
 130    }
 131   
 132  0 public String getName() {
 133  0 return null;
 134    }
 135   
 136  0 public void setName(String name) {
 137  0 throw new UnsupportedOperationException("This node cannot be modified");
 138    }
 139   
 140  0 public String getText() {
 141  0 return null;
 142    }
 143   
 144  1538 public String getStringValue() {
 145  1538 return getText();
 146    }
 147   
 148  0 public void setText(String text) {
 149  0 throw new UnsupportedOperationException("This node cannot be modified");
 150    }
 151   
 152  0 public void write(Writer writer) throws IOException {
 153  0 writer.write(asXML());
 154    }
 155   
 156    // XPath methods
 157  4 public Object selectObject(String xpathExpression) {
 158  4 XPath xpath = createXPath(xpathExpression);
 159   
 160  2 return xpath.evaluate(this);
 161    }
 162   
 163  227 public List selectNodes(String xpathExpression) {
 164  227 XPath xpath = createXPath(xpathExpression);
 165   
 166  227 return xpath.selectNodes(this);
 167    }
 168   
 169  1 public List selectNodes(String xpathExpression,
 170    String comparisonXPathExpression) {
 171  1 return selectNodes(xpathExpression, comparisonXPathExpression, false);
 172    }
 173   
 174  2 public List selectNodes(String xpathExpression,
 175    String comparisonXPathExpression, boolean removeDuplicates) {
 176  2 XPath xpath = createXPath(xpathExpression);
 177  2 XPath sortBy = createXPath(comparisonXPathExpression);
 178   
 179  2 return xpath.selectNodes(this, sortBy, removeDuplicates);
 180    }
 181   
 182  66 public Node selectSingleNode(String xpathExpression) {
 183  66 XPath xpath = createXPath(xpathExpression);
 184   
 185  66 return xpath.selectSingleNode(this);
 186    }
 187   
 188  81 public String valueOf(String xpathExpression) {
 189  81 XPath xpath = createXPath(xpathExpression);
 190   
 191  81 return xpath.valueOf(this);
 192    }
 193   
 194  0 public Number numberValueOf(String xpathExpression) {
 195  0 XPath xpath = createXPath(xpathExpression);
 196   
 197  0 return xpath.numberValueOf(this);
 198    }
 199   
 200  0 public boolean matches(String patternText) {
 201  0 NodeFilter filter = createXPathFilter(patternText);
 202   
 203  0 return filter.matches(this);
 204    }
 205   
 206  526 public XPath createXPath(String xpathExpression) {
 207  526 return getDocumentFactory().createXPath(xpathExpression);
 208    }
 209   
 210  0 public NodeFilter createXPathFilter(String patternText) {
 211  0 return getDocumentFactory().createXPathFilter(patternText);
 212    }
 213   
 214  0 public Pattern createPattern(String patternText) {
 215  0 return getDocumentFactory().createPattern(patternText);
 216    }
 217   
 218  107 public Node asXPathResult(Element parent) {
 219  107 if (supportsParent()) {
 220  0 return this;
 221    }
 222   
 223  107 return createXPathResult(parent);
 224    }
 225   
 226  0 protected DocumentFactory getDocumentFactory() {
 227  0 return DOCUMENT_FACTORY;
 228    }
 229   
 230  0 protected Node createXPathResult(Element parent) {
 231  0 throw new RuntimeException("asXPathResult() not yet implemented fully "
 232    + "for: " + this);
 233    }
 234    }
 235   
 236    /*
 237    * Redistribution and use of this software and associated documentation
 238    * ("Software"), with or without modification, are permitted provided that the
 239    * following conditions are met:
 240    *
 241    * 1. Redistributions of source code must retain copyright statements and
 242    * notices. Redistributions must also contain a copy of this document.
 243    *
 244    * 2. Redistributions in binary form must reproduce the above copyright notice,
 245    * this list of conditions and the following disclaimer in the documentation
 246    * and/or other materials provided with the distribution.
 247    *
 248    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 249    * from this Software without prior written permission of MetaStuff, Ltd. For
 250    * written permission, please contact dom4j-info@metastuff.com.
 251    *
 252    * 4. Products derived from this Software may not be called "DOM4J" nor may
 253    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 254    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 255    *
 256    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 257    *
 258    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 259    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 260    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 261    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 262    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 263    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 264    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 265    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 266    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 267    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 268    * POSSIBILITY OF SUCH DAMAGE.
 269    *
 270    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 271    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/tree/AbstractDocument.html0000644000175000017500000024177210242117703023213 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 296   Methods: 26
NCLOC: 174   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
AbstractDocument.java 31,8% 66,2% 76,9% 62,4%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.tree;
 9   
 10    import java.io.IOException;
 11    import java.io.StringWriter;
 12    import java.io.Writer;
 13    import java.util.Iterator;
 14    import java.util.List;
 15    import java.util.Map;
 16   
 17    import org.dom4j.Comment;
 18    import org.dom4j.Document;
 19    import org.dom4j.DocumentType;
 20    import org.dom4j.Element;
 21    import org.dom4j.IllegalAddException;
 22    import org.dom4j.Node;
 23    import org.dom4j.ProcessingInstruction;
 24    import org.dom4j.QName;
 25    import org.dom4j.Text;
 26    import org.dom4j.Visitor;
 27    import org.dom4j.io.OutputFormat;
 28    import org.dom4j.io.XMLWriter;
 29   
 30    /**
 31    * <p>
 32    * <code>AbstractDocument</code> is an abstract base class for tree
 33    * implementors to use for implementation inheritence.
 34    * </p>
 35    *
 36    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 37    * @version $Revision: 1.33 $
 38    */
 39    public abstract class AbstractDocument extends AbstractBranch implements
 40    Document {
 41   
 42    /** The encoding of this document as stated in the XML declaration */
 43    protected String encoding;
 44   
 45  6283 public AbstractDocument() {
 46    }
 47   
 48  25 public short getNodeType() {
 49  25 return DOCUMENT_NODE;
 50    }
 51   
 52  1 public String getPath(Element context) {
 53  1 return "/";
 54    }
 55   
 56  1 public String getUniquePath(Element context) {
 57  1 return "/";
 58    }
 59   
 60  6459 public Document getDocument() {
 61  6459 return this;
 62    }
 63   
 64  0 public String getXMLEncoding() {
 65  0 return null;
 66    }
 67   
 68  0 public String getStringValue() {
 69  0 Element root = getRootElement();
 70   
 71  0 return (root != null) ? root.getStringValue() : "";
 72    }
 73   
 74  58 public String asXML() {
 75  58 OutputFormat format = new OutputFormat();
 76  58 format.setEncoding(encoding);
 77   
 78  58 try {
 79  58 StringWriter out = new StringWriter();
 80  58 XMLWriter writer = new XMLWriter(out, format);
 81  58 writer.write(this);
 82  58 writer.flush();
 83   
 84  58 return out.toString();
 85    } catch (IOException e) {
 86  0 throw new RuntimeException("IOException while generating textual "
 87    + "representation: " + e.getMessage());
 88    }
 89    }
 90   
 91  0 public void write(Writer out) throws IOException {
 92  0 OutputFormat format = new OutputFormat();
 93  0 format.setEncoding(encoding);
 94   
 95  0 XMLWriter writer = new XMLWriter(out, format);
 96  0 writer.write(this);
 97    }
 98   
 99    /**
 100    * <p>
 101    * <code>accept</code> method is the <code>Visitor Pattern</code>
 102    * method.
 103    * </p>
 104    *
 105    * @param visitor
 106    * <code>Visitor</code> is the visitor.
 107    */
 108  0 public void accept(Visitor visitor) {
 109  0 visitor.visit(this);
 110   
 111  0 DocumentType docType = getDocType();
 112   
 113  0 if (docType != null) {
 114  0 visitor.visit(docType);
 115    }
 116   
 117    // visit content
 118  0 List content = content();
 119   
 120  0 if (content != null) {
 121  0 for (Iterator iter = content.iterator(); iter.hasNext();) {
 122  0 Object object = iter.next();
 123   
 124  0 if (object instanceof String) {
 125  0 Text text = getDocumentFactory()
 126    .createText((String) object);
 127  0 visitor.visit(text);
 128    } else {
 129  0 Node node = (Node) object;
 130  0 node.accept(visitor);
 131    }
 132    }
 133    }
 134    }
 135   
 136  159 public String toString() {
 137  159 return super.toString() + " [Document: name " + getName() + "]";
 138    }
 139   
 140  110 public void normalize() {
 141  110 Element element = getRootElement();
 142   
 143  110 if (element != null) {
 144  110 element.normalize();
 145    }
 146    }
 147   
 148  24 public Document addComment(String comment) {
 149  24 Comment node = getDocumentFactory().createComment(comment);
 150  24 add(node);
 151   
 152  24 return this;
 153    }
 154   
 155  25 public Document addProcessingInstruction(String target, String data) {
 156  25 ProcessingInstruction node = getDocumentFactory()
 157    .createProcessingInstruction(target, data);
 158  25 add(node);
 159   
 160  25 return this;
 161    }
 162   
 163  0 public Document addProcessingInstruction(String target, Map data) {
 164  0 ProcessingInstruction node = getDocumentFactory()
 165    .createProcessingInstruction(target, data);
 166  0 add(node);
 167   
 168  0 return this;
 169    }
 170   
 171  434 public Element addElement(String name) {
 172  434 Element element = getDocumentFactory().createElement(name);
 173  434 add(element);
 174   
 175  434 return element;
 176    }
 177   
 178  2 public Element addElement(String qualifiedName, String namespaceURI) {
 179  2 Element element = getDocumentFactory().createElement(qualifiedName,
 180    namespaceURI);
 181  2 add(element);
 182   
 183  2 return element;
 184    }
 185   
 186  5835 public Element addElement(QName qName) {
 187  5835 Element element = getDocumentFactory().createElement(qName);
 188  5835 add(element);
 189   
 190  5835 return element;
 191    }
 192   
 193  4 public void setRootElement(Element rootElement) {
 194  4 clearContent();
 195   
 196  4 if (rootElement != null) {
 197  4 super.add(rootElement);
 198  4 rootElementAdded(rootElement);
 199    }
 200    }
 201   
 202  6288 public void add(Element element) {
 203  6288 checkAddElementAllowed(element);
 204  6287 super.add(element);
 205  6287 rootElementAdded(element);
 206    }
 207   
 208  2 public boolean remove(Element element) {
 209  2 boolean answer = super.remove(element);
 210  2 Element root = getRootElement();
 211   
 212  2 if ((root != null) && answer) {
 213  0 setRootElement(null);
 214    }
 215   
 216  2 element.setDocument(null);
 217   
 218  2 return answer;
 219    }
 220   
 221  0 public Node asXPathResult(Element parent) {
 222  0 return this;
 223    }
 224   
 225  6341 protected void childAdded(Node node) {
 226  6341 if (node != null) {
 227  6341 node.setDocument(this);
 228    }
 229    }
 230   
 231  4 protected void childRemoved(Node node) {
 232  4 if (node != null) {
 233  4 node.setDocument(null);
 234    }
 235    }
 236   
 237  6288 protected void checkAddElementAllowed(Element element) {
 238  6288 Element root = getRootElement();
 239   
 240  6288 if (root != null) {
 241  1 throw new IllegalAddException(this, element,
 242    "Cannot add another element to this "
 243    + "Document as it already has a root "
 244    + "element of: " + root.getQualifiedName());
 245    }
 246    }
 247   
 248    /**
 249    * Called to set the root element variable
 250    *
 251    * @param rootElement
 252    * DOCUMENT ME!
 253    */
 254    protected abstract void rootElementAdded(Element rootElement);
 255   
 256  11346 public void setXMLEncoding(String enc) {
 257  11346 this.encoding = enc;
 258    }
 259    }
 260   
 261    /*
 262    * Redistribution and use of this software and associated documentation
 263    * ("Software"), with or without modification, are permitted provided that the
 264    * following conditions are met:
 265    *
 266    * 1. Redistributions of source code must retain copyright statements and
 267    * notices. Redistributions must also contain a copy of this document.
 268    *
 269    * 2. Redistributions in binary form must reproduce the above copyright notice,
 270    * this list of conditions and the following disclaimer in the documentation
 271    * and/or other materials provided with the distribution.
 272    *
 273    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 274    * from this Software without prior written permission of MetaStuff, Ltd. For
 275    * written permission, please contact dom4j-info@metastuff.com.
 276    *
 277    * 4. Products derived from this Software may not be called "DOM4J" nor may
 278    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 279    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 280    *
 281    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 282    *
 283    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 284    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 285    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 286    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 287    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 288    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 289    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 290    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 291    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 292    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 293    * POSSIBILITY OF SUCH DAMAGE.
 294    *
 295    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 296    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/swing/0000755000175000017500000000000012133227266017245 5ustar ebourgebourgdom4j-1.6.1/docs/clover/org/dom4j/swing/pkg-classes.html0000644000175000017500000000307310242117546022350 0ustar ebourgebourg dom4j - 1.6.1 org.dom4j.swing
Classes
BranchTreeNode (0%)
DocumentTreeModel (0%)
LeafTreeNode (0%)
XMLTableColumnDefinition (25,7%)
XMLTableDefinition (76,7%)
XMLTableModel (56,5%)
dom4j-1.6.1/docs/clover/org/dom4j/swing/XMLTableModel.html0000644000175000017500000015461310242117747022537 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 203   Methods: 15
NCLOC: 73   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
XMLTableModel.java 75% 55,6% 53,3% 56,5%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.swing;
 9   
 10    import java.util.List;
 11   
 12    import javax.swing.table.AbstractTableModel;
 13   
 14    import org.dom4j.Document;
 15    import org.dom4j.Element;
 16    import org.dom4j.XPath;
 17   
 18    /**
 19    * <p>
 20    * <code>XMLTableDefinition</code> repro.
 21    * </p>
 22    *
 23    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 24    * @version $Revision: 1.8 $
 25    */
 26    public class XMLTableModel extends AbstractTableModel {
 27    /** Holds value of property definition. */
 28    private XMLTableDefinition definition;
 29   
 30    /** Holds value of property source. */
 31    private Object source;
 32   
 33    /** The rows evaluated from the row XPath expression */
 34    private List rows;
 35   
 36    /**
 37    * Creates a TableModel from an XML table definition document and an XML
 38    * source
 39    *
 40    * @param tableDefinition
 41    * DOCUMENT ME!
 42    * @param source
 43    * DOCUMENT ME!
 44    */
 45  0 public XMLTableModel(Element tableDefinition, Object source) {
 46  0 this(XMLTableDefinition.load(tableDefinition), source);
 47    }
 48   
 49    /**
 50    * Creates a TableModel from an XML table definition document and an XML
 51    * source
 52    *
 53    * @param tableDefinition
 54    * DOCUMENT ME!
 55    * @param source
 56    * DOCUMENT ME!
 57    */
 58  1 public XMLTableModel(Document tableDefinition, Object source) {
 59  1 this(XMLTableDefinition.load(tableDefinition), source);
 60    }
 61   
 62  2 public XMLTableModel(XMLTableDefinition definition, Object source) {
 63  2 this.definition = definition;
 64  2 this.source = source;
 65    }
 66   
 67  12 public Object getRowValue(int rowIndex) {
 68  12 return getRows().get(rowIndex);
 69    }
 70   
 71  14 public List getRows() {
 72  14 if (rows == null) {
 73  2 rows = definition.getRowXPath().selectNodes(source);
 74    }
 75   
 76  14 return rows;
 77    }
 78   
 79    // TableModel interface
 80    // -------------------------------------------------------------------------
 81  0 public Class getColumnClass(int columnIndex) {
 82  0 return definition.getColumnClass(columnIndex);
 83    }
 84   
 85  2 public int getColumnCount() {
 86  2 return definition.getColumnCount();
 87    }
 88   
 89  6 public String getColumnName(int columnIndex) {
 90  6 XPath xpath = definition.getColumnNameXPath(columnIndex);
 91   
 92  6 if (xpath != null) {
 93  0 System.out.println("Evaluating column xpath: " + xpath + " value: "
 94    + xpath.valueOf(source));
 95   
 96  0 return xpath.valueOf(source);
 97    }
 98   
 99  6 return definition.getColumnName(columnIndex);
 100    }
 101   
 102  12 public Object getValueAt(int rowIndex, int columnIndex) {
 103  12 try {
 104  12 Object row = getRowValue(rowIndex);
 105   
 106  12 return definition.getValueAt(row, columnIndex);
 107    } catch (Exception e) {
 108  0 handleException(e);
 109   
 110  0 return null;
 111    }
 112    }
 113   
 114  2 public int getRowCount() {
 115  2 return getRows().size();
 116    }
 117   
 118    // Properties
 119    // -------------------------------------------------------------------------
 120   
 121    /**
 122    * Getter for property definition.
 123    *
 124    * @return Value of property definition.
 125    */
 126  0 public XMLTableDefinition getDefinition() {
 127  0 return definition;
 128    }
 129   
 130    /**
 131    * Setter for property definition.
 132    *
 133    * @param definition
 134    * New value of property definition.
 135    */
 136  0 public void setDefinition(XMLTableDefinition definition) {
 137  0 this.definition = definition;
 138    }
 139   
 140    /**
 141    * Getter for the XML source, which is usually a Node or List of nodes.
 142    *
 143    * @return Value of property source.
 144    */
 145  0 public Object getSource() {
 146  0 return source;
 147    }
 148   
 149    /**
 150    * Setter for the XML source, which is usually a Node or List of nodes.
 151    *
 152    * @param source
 153    * New value of property source.
 154    */
 155  0 public void setSource(Object source) {
 156  0 this.source = source;
 157  0 this.rows = null;
 158    }
 159   
 160    // Implementation methods
 161    // -------------------------------------------------------------------------
 162  0 protected void handleException(Exception e) {
 163    // #### should use jakarta commons-logging
 164  0 System.out.println("Caught: " + e);
 165    }
 166    }
 167   
 168    /*
 169    * Redistribution and use of this software and associated documentation
 170    * ("Software"), with or without modification, are permitted provided that the
 171    * following conditions are met:
 172    *
 173    * 1. Redistributions of source code must retain copyright statements and
 174    * notices. Redistributions must also contain a copy of this document.
 175    *
 176    * 2. Redistributions in binary form must reproduce the above copyright notice,
 177    * this list of conditions and the following disclaimer in the documentation
 178    * and/or other materials provided with the distribution.
 179    *
 180    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 181    * from this Software without prior written permission of MetaStuff, Ltd. For
 182    * written permission, please contact dom4j-info@metastuff.com.
 183    *
 184    * 4. Products derived from this Software may not be called "DOM4J" nor may
 185    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 186    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 187    *
 188    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 189    *
 190    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 191    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 192    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 193    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 194    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 195    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 196    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 197    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 198    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 199    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 200    * POSSIBILITY OF SUCH DAMAGE.
 201    *
 202    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 203    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/swing/pkg-summary.html0000644000175000017500000002100210242117732022375 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
package stats: LOC: 1.193   Methods: 93
NCLOC: 478   Classes: 6
Files: 6  
 
 Package Conditionals Statements Methods TOTAL
org.dom4j.swing 39,5% 40,2% 34,4% 38,4%
coverage coverage
 
 Classes Conditionals Statements Methods TOTAL
BranchTreeNode 0% 0% 0% 0%
coverage
DocumentTreeModel - 0% 0% 0%
coverage
LeafTreeNode 0% 0% 0% 0%
coverage
XMLTableColumnDefinition 25% 24,4% 29,4% 25,7%
coverage coverage
XMLTableModel 75% 55,6% 53,3% 56,5%
coverage coverage
XMLTableDefinition 83,3% 78,1% 70,4% 76,7%
coverage coverage
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/swing/DocumentTreeModel.html0000644000175000017500000006474610242117732023526 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 94   Methods: 3
NCLOC: 17   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DocumentTreeModel.java - 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.swing;
 9   
 10    import javax.swing.tree.DefaultTreeModel;
 11   
 12    import org.dom4j.Document;
 13   
 14    /**
 15    * <p>
 16    * <code>DocumentTreeModel</code> implements a Swing TreeModel for a dom4j XML
 17    * Document.
 18    * </p>
 19    *
 20    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 21    * @author Jakob Jenkov
 22    * @version $Revision: 1.7 $
 23    */
 24    public class DocumentTreeModel extends DefaultTreeModel {
 25    /** The document for this model */
 26    protected Document document;
 27   
 28  0 public DocumentTreeModel(Document document) {
 29  0 super(new BranchTreeNode(document));
 30  0 this.document = document;
 31    }
 32   
 33    // Properties
 34    // -------------------------------------------------------------------------
 35   
 36    /**
 37    * DOCUMENT ME!
 38    *
 39    * @return the <code>Document</code> instance that this
 40    * <code>TreeModel</code> is based on
 41    */
 42  0 public Document getDocument() {
 43  0 return document;
 44    }
 45   
 46    /**
 47    * Sets the <code>Document</code> instance that this
 48    * <code>TreeModel</code> is based on
 49    *
 50    * @param document
 51    * DOCUMENT ME!
 52    */
 53  0 public void setDocument(Document document) {
 54  0 this.document = document;
 55  0 setRoot(new BranchTreeNode(document));
 56    }
 57    }
 58   
 59    /*
 60    * Redistribution and use of this software and associated documentation
 61    * ("Software"), with or without modification, are permitted provided that the
 62    * following conditions are met:
 63    *
 64    * 1. Redistributions of source code must retain copyright statements and
 65    * notices. Redistributions must also contain a copy of this document.
 66    *
 67    * 2. Redistributions in binary form must reproduce the above copyright notice,
 68    * this list of conditions and the following disclaimer in the documentation
 69    * and/or other materials provided with the distribution.
 70    *
 71    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 72    * from this Software without prior written permission of MetaStuff, Ltd. For
 73    * written permission, please contact dom4j-info@metastuff.com.
 74    *
 75    * 4. Products derived from this Software may not be called "DOM4J" nor may
 76    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 77    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 78    *
 79    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 80    *
 81    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 82    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 83    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 84    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 85    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 86    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 87    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 88    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 89    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 90    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 91    * POSSIBILITY OF SUCH DAMAGE.
 92    *
 93    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 94    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/swing/BranchTreeNode.html0000644000175000017500000015172410242117736022767 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 196   Methods: 16
NCLOC: 84   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
BranchTreeNode.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.swing;
 9   
 10    import java.util.ArrayList;
 11    import java.util.Enumeration;
 12    import java.util.List;
 13   
 14    import javax.swing.tree.TreeNode;
 15   
 16    import org.dom4j.Branch;
 17    import org.dom4j.CharacterData;
 18    import org.dom4j.Node;
 19   
 20    /**
 21    * <p>
 22    * <code>BranchTreeNode</code> implements the Swing TreeNode interface to bind
 23    * dom4j XML Branch nodes (i.e. Document and Element nodes) to a Swing
 24    * TreeModel.
 25    * </p>
 26    *
 27    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 28    * @author Jakob Jenkov
 29    * @version $Revision: 1.10 $
 30    */
 31    public class BranchTreeNode extends LeafTreeNode {
 32    /** Stores the child tree nodes */
 33    protected List children;
 34   
 35  0 public BranchTreeNode() {
 36    }
 37   
 38  0 public BranchTreeNode(Branch xmlNode) {
 39  0 super(xmlNode);
 40    }
 41   
 42  0 public BranchTreeNode(TreeNode parent, Branch xmlNode) {
 43  0 super(parent, xmlNode);
 44    }
 45   
 46    // TreeNode methods
 47    // -------------------------------------------------------------------------
 48  0 public Enumeration children() {
 49  0 return new Enumeration() {
 50    private int index = -1;
 51   
 52  0 public boolean hasMoreElements() {
 53  0 return (index + 1) < getChildCount();
 54    }
 55   
 56  0 public Object nextElement() {
 57  0 return getChildAt(++index);
 58    }
 59    };
 60    }
 61   
 62  0 public boolean getAllowsChildren() {
 63  0 return true;
 64    }
 65   
 66  0 public TreeNode getChildAt(int childIndex) {
 67  0 return (TreeNode) getChildList().get(childIndex);
 68    }
 69   
 70  0 public int getChildCount() {
 71  0 return getChildList().size();
 72    }
 73   
 74  0 public int getIndex(TreeNode node) {
 75  0 return getChildList().indexOf(node);
 76    }
 77   
 78  0 public boolean isLeaf() {
 79  0 return getXmlBranch().nodeCount() <= 0;
 80    }
 81   
 82  0 public String toString() {
 83  0 return xmlNode.getName();
 84    }
 85   
 86    // Implementation methods
 87    // -------------------------------------------------------------------------
 88   
 89    /**
 90    * Uses Lazy Initialization pattern to create a List of children
 91    *
 92    * @return DOCUMENT ME!
 93    */
 94  0 protected List getChildList() {
 95    // for now lets just create the children once, the first time they
 96    // are asked for.
 97    // XXXX - we may wish to detect inconsistencies here....
 98  0 if (children == null) {
 99  0 children = createChildList();
 100    }
 101   
 102  0 return children;
 103    }
 104   
 105    /**
 106    * Factory method to create List of children TreeNodes
 107    *
 108    * @return DOCUMENT ME!
 109    */
 110  0 protected List createChildList() {
 111    // add attributes and content as children?
 112  0 Branch branch = getXmlBranch();
 113  0 int size = branch.nodeCount();
 114  0 List childList = new ArrayList(size);
 115   
 116  0 for (int i = 0; i < size; i++) {
 117  0 Node node = branch.node(i);
 118   
 119    // ignore whitespace text nodes
 120  0 if (node instanceof CharacterData) {
 121  0 String text = node.getText();
 122   
 123  0 if (text == null) {
 124  0 continue;
 125    }
 126   
 127  0 text = text.trim();
 128   
 129  0 if (text.length() <= 0) {
 130  0 continue;
 131    }
 132    }
 133   
 134  0 childList.add(createChildTreeNode(node));
 135    }
 136   
 137  0 return childList;
 138    }
 139   
 140    /**
 141    * Factory method to create child tree nodes for a given XML node type
 142    *
 143    * @param xmlNode
 144    * DOCUMENT ME!
 145    *
 146    * @return DOCUMENT ME!
 147    */
 148  0 protected TreeNode createChildTreeNode(Node xmlNode) {
 149  0 if (xmlNode instanceof Branch) {
 150  0 return new BranchTreeNode(this, (Branch) xmlNode);
 151    } else {
 152  0 return new LeafTreeNode(this, xmlNode);
 153    }
 154    }
 155   
 156  0 protected Branch getXmlBranch() {
 157  0 return (Branch) xmlNode;
 158    }
 159    }
 160   
 161    /*
 162    * Redistribution and use of this software and associated documentation
 163    * ("Software"), with or without modification, are permitted provided that the
 164    * following conditions are met:
 165    *
 166    * 1. Redistributions of source code must retain copyright statements and
 167    * notices. Redistributions must also contain a copy of this document.
 168    *
 169    * 2. Redistributions in binary form must reproduce the above copyright notice,
 170    * this list of conditions and the following disclaimer in the documentation
 171    * and/or other materials provided with the distribution.
 172    *
 173    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 174    * from this Software without prior written permission of MetaStuff, Ltd. For
 175    * written permission, please contact dom4j-info@metastuff.com.
 176    *
 177    * 4. Products derived from this Software may not be called "DOM4J" nor may
 178    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 179    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 180    *
 181    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 182    *
 183    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 184    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 185    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 186    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 187    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 188    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 189    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 190    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 191    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 192    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 193    * POSSIBILITY OF SUCH DAMAGE.
 194    *
 195    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 196    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/swing/XMLTableColumnDefinition.html0000644000175000017500000020103010242117741024721 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 238   Methods: 17
NCLOC: 98   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
XMLTableColumnDefinition.java 25% 24,4% 29,4% 25,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.swing;
 9   
 10    import java.io.Serializable;
 11   
 12    import org.dom4j.DocumentHelper;
 13    import org.dom4j.Node;
 14    import org.dom4j.XPath;
 15   
 16    /**
 17    * <p>
 18    * <code>XMLTableColumnDefinition</code> a column within a table definition.
 19    * </p>
 20    *
 21    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 22    * @version $Revision: 1.10 $
 23    */
 24    public class XMLTableColumnDefinition implements Serializable {
 25    public static final int OBJECT_TYPE = 0;
 26   
 27    public static final int STRING_TYPE = 1;
 28   
 29    public static final int NUMBER_TYPE = 2;
 30   
 31    public static final int NODE_TYPE = 3;
 32   
 33    /** Holds value of property type. */
 34    private int type;
 35   
 36    /** Holds value of property name. */
 37    private String name;
 38   
 39    /** Holds value of property xpath. */
 40    private XPath xpath;
 41   
 42    /** Holds the XPath used for the column name */
 43    private XPath columnNameXPath;
 44   
 45  0 public XMLTableColumnDefinition() {
 46    }
 47   
 48  0 public XMLTableColumnDefinition(String name, String expression, int type) {
 49  0 this.name = name;
 50  0 this.type = type;
 51  0 this.xpath = createXPath(expression);
 52    }
 53   
 54  6 public XMLTableColumnDefinition(String name, XPath xpath, int type) {
 55  6 this.name = name;
 56  6 this.xpath = xpath;
 57  6 this.type = type;
 58    }
 59   
 60  0 public XMLTableColumnDefinition(XPath columnXPath, XPath xpath, int type) {
 61  0 this.xpath = xpath;
 62  0 this.columnNameXPath = columnXPath;
 63  0 this.type = type;
 64    }
 65   
 66  3 public static int parseType(String typeName) {
 67  3 if ((typeName != null) && (typeName.length() > 0)) {
 68  3 if (typeName.equals("string")) {
 69  3 return STRING_TYPE;
 70  0 } else if (typeName.equals("number")) {
 71  0 return NUMBER_TYPE;
 72  0 } else if (typeName.equals("node")) {
 73  0 return NODE_TYPE;
 74    }
 75    }
 76   
 77  0 return OBJECT_TYPE;
 78    }
 79   
 80  0 public Class getColumnClass() {
 81  0 switch (type) {
 82  0 case STRING_TYPE:
 83  0 return String.class;
 84   
 85  0 case NUMBER_TYPE:
 86  0 return Number.class;
 87   
 88  0 case NODE_TYPE:
 89  0 return Node.class;
 90   
 91  0 default:
 92  0 return Object.class;
 93    }
 94    }
 95   
 96  16 public Object getValue(Object row) {
 97  16 switch (type) {
 98  16 case STRING_TYPE:
 99  16 return xpath.valueOf(row);
 100   
 101  0 case NUMBER_TYPE:
 102  0 return xpath.numberValueOf(row);
 103   
 104  0 case NODE_TYPE:
 105  0 return xpath.selectSingleNode(row);
 106   
 107  0 default:
 108  0 return xpath.evaluate(row);
 109    }
 110    }
 111   
 112    // Properties
 113    // -------------------------------------------------------------------------
 114   
 115    /**
 116    * Getter for property type.
 117    *
 118    * @return Value of property type.
 119    */
 120  0 public int getType() {
 121  0 return type;
 122    }
 123   
 124    /**
 125    * Setter for property type.
 126    *
 127    * @param type
 128    * New value of property type.
 129    */
 130  0 public void setType(int type) {
 131  0 this.type = type;
 132    }
 133   
 134    /**
 135    * Getter for property name.
 136    *
 137    * @return Value of property name.
 138    */
 139  12 public String getName() {
 140  12 return name;
 141    }
 142   
 143    /**
 144    * Setter for property name.
 145    *
 146    * @param name
 147    * New value of property name.
 148    */
 149  0 public void setName(String name) {
 150  0 this.name = name;
 151    }
 152   
 153    /**
 154    * Getter for property xpath.
 155    *
 156    * @return Value of property xpath.
 157    */
 158  0 public XPath getXPath() {
 159  0 return xpath;
 160    }
 161   
 162    /**
 163    * Setter for property xpath.
 164    *
 165    * @param xPath
 166    * New value of property xpath.
 167    */
 168  0 public void setXPath(XPath xPath) {
 169  0 this.xpath = xPath;
 170    }
 171   
 172    /**
 173    * DOCUMENT ME!
 174    *
 175    * @return the XPath used to create the column name
 176    */
 177  6 public XPath getColumnNameXPath() {
 178  6 return columnNameXPath;
 179    }
 180   
 181    /**
 182    * Setter for property columnNameXPath.
 183    *
 184    * @param columnNameXPath
 185    * New value of property xpath.
 186    */
 187  0 public void setColumnNameXPath(XPath columnNameXPath) {
 188  0 this.columnNameXPath = columnNameXPath;
 189    }
 190   
 191    // Implementation methods
 192    // -------------------------------------------------------------------------
 193  0 protected XPath createXPath(String expression) {
 194  0 return DocumentHelper.createXPath(expression);
 195    }
 196   
 197  0 protected void handleException(Exception e) {
 198    // #### should use jakarta commons-logging
 199  0 System.out.println("Caught: " + e);
 200    }
 201    }
 202   
 203    /*
 204    * Redistribution and use of this software and associated documentation
 205    * ("Software"), with or without modification, are permitted provided that the
 206    * following conditions are met:
 207    *
 208    * 1. Redistributions of source code must retain copyright statements and
 209    * notices. Redistributions must also contain a copy of this document.
 210    *
 211    * 2. Redistributions in binary form must reproduce the above copyright notice,
 212    * this list of conditions and the following disclaimer in the documentation
 213    * and/or other materials provided with the distribution.
 214    *
 215    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 216    * from this Software without prior written permission of MetaStuff, Ltd. For
 217    * written permission, please contact dom4j-info@metastuff.com.
 218    *
 219    * 4. Products derived from this Software may not be called "DOM4J" nor may
 220    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 221    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 222    *
 223    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 224    *
 225    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 226    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 227    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 228    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 229    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 230    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 231    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 232    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 233    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 234    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 235    * POSSIBILITY OF SUCH DAMAGE.
 236    *
 237    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 238    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/swing/LeafTreeNode.html0000644000175000017500000011723210242117745022435 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 145   Methods: 15
NCLOC: 56   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
LeafTreeNode.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.swing;
 9   
 10    import java.util.Enumeration;
 11   
 12    import javax.swing.tree.TreeNode;
 13   
 14    import org.dom4j.Node;
 15   
 16    /**
 17    * <p>
 18    * <code>LeafTreeNode</code> implements the Swing TreeNode interface to bind a
 19    * leaf XML nodes to a Swing TreeModel.
 20    * </p>
 21    *
 22    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 23    * @author Jakob Jenkov
 24    * @version $Revision: 1.7 $
 25    */
 26    public class LeafTreeNode implements TreeNode {
 27    protected static final Enumeration EMPTY_ENUMERATION = new Enumeration() {
 28  0 public boolean hasMoreElements() {
 29  0 return false;
 30    }
 31   
 32  0 public Object nextElement() {
 33  0 return null;
 34    }
 35    };
 36   
 37    /** The parent node of this TreeNode */
 38    private TreeNode parent;
 39   
 40    /** The dom4j Node which contains the */
 41    protected Node xmlNode;
 42   
 43  0 public LeafTreeNode() {
 44    }
 45   
 46  0 public LeafTreeNode(Node xmlNode) {
 47  0 this.xmlNode = xmlNode;
 48    }
 49   
 50  0 public LeafTreeNode(TreeNode parent, Node xmlNode) {
 51  0 this.parent = parent;
 52  0 this.xmlNode = xmlNode;
 53    }
 54   
 55    // TreeNode methods
 56    // -------------------------------------------------------------------------
 57  0 public Enumeration children() {
 58  0 return EMPTY_ENUMERATION;
 59    }
 60   
 61  0 public boolean getAllowsChildren() {
 62  0 return false;
 63    }
 64   
 65  0 public TreeNode getChildAt(int childIndex) {
 66  0 return null;
 67    }
 68   
 69  0 public int getChildCount() {
 70  0 return 0;
 71    }
 72   
 73  0 public int getIndex(TreeNode node) {
 74  0 return -1;
 75    }
 76   
 77  0 public TreeNode getParent() {
 78  0 return parent;
 79    }
 80   
 81  0 public boolean isLeaf() {
 82  0 return true;
 83    }
 84   
 85  0 public String toString() {
 86    // should maybe do things differently based on content?
 87  0 String text = xmlNode.getText();
 88   
 89  0 return (text != null) ? text.trim() : "";
 90    }
 91   
 92    // Properties
 93    // -------------------------------------------------------------------------
 94   
 95    /**
 96    * Sets the parent of this node but doesn't change the parents children
 97    *
 98    * @param parent
 99    * DOCUMENT ME!
 100    */
 101  0 public void setParent(LeafTreeNode parent) {
 102  0 this.parent = parent;
 103    }
 104   
 105  0 public Node getXmlNode() {
 106  0 return xmlNode;
 107    }
 108    }
 109   
 110    /*
 111    * Redistribution and use of this software and associated documentation
 112    * ("Software"), with or without modification, are permitted provided that the
 113    * following conditions are met:
 114    *
 115    * 1. Redistributions of source code must retain copyright statements and
 116    * notices. Redistributions must also contain a copy of this document.
 117    *
 118    * 2. Redistributions in binary form must reproduce the above copyright notice,
 119    * this list of conditions and the following disclaimer in the documentation
 120    * and/or other materials provided with the distribution.
 121    *
 122    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 123    * from this Software without prior written permission of MetaStuff, Ltd. For
 124    * written permission, please contact dom4j-info@metastuff.com.
 125    *
 126    * 4. Products derived from this Software may not be called "DOM4J" nor may
 127    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 128    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 129    *
 130    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 131    *
 132    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 133    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 134    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 135    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 136    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 137    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 138    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 139    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 140    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 141    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 142    * POSSIBILITY OF SUCH DAMAGE.
 143    *
 144    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 145    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/swing/XMLTableDefinition.html0000644000175000017500000025250610242117746023566 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 317   Methods: 27
NCLOC: 150   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
XMLTableDefinition.java 83,3% 78,1% 70,4% 76,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.swing;
 9   
 10    import java.io.Serializable;
 11    import java.util.ArrayList;
 12    import java.util.HashMap;
 13    import java.util.Iterator;
 14    import java.util.List;
 15    import java.util.Map;
 16   
 17    import org.dom4j.Document;
 18    import org.dom4j.DocumentHelper;
 19    import org.dom4j.Element;
 20    import org.dom4j.XPath;
 21   
 22    import org.jaxen.VariableContext;
 23   
 24    /**
 25    * <p>
 26    * <code>XMLTableDefinition</code> represents a table definition based on
 27    * XPath expression evaluated on an XML document.
 28    * </p>
 29    *
 30    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 31    * @version $Revision: 1.8 $
 32    */
 33    public class XMLTableDefinition implements Serializable, VariableContext {
 34    /** Holds value of property rowXPath. */
 35    private XPath rowXPath;
 36   
 37    /** The columns to display in this table */
 38    private List columns = new ArrayList();
 39   
 40    /** integer index array cache */
 41    private XMLTableColumnDefinition[] columnArray;
 42   
 43    /** name index cache */
 44    private Map columnNameIndex;
 45   
 46    /** for cross-row variables */
 47    private VariableContext variableContext;
 48   
 49    /** stores the current row value for the variableContext */
 50    private Object rowValue;
 51   
 52  2 public XMLTableDefinition() {
 53    }
 54   
 55    /**
 56    * Loads an XML table definition from an XML definition document
 57    *
 58    * @param definition
 59    * DOCUMENT ME!
 60    *
 61    * @return DOCUMENT ME!
 62    */
 63  1 public static XMLTableDefinition load(Document definition) {
 64  1 return load(definition.getRootElement());
 65    }
 66   
 67    /**
 68    * Loads an XML table definition from an XML definition document
 69    *
 70    * @param definition
 71    * DOCUMENT ME!
 72    *
 73    * @return DOCUMENT ME!
 74    */
 75  1 public static XMLTableDefinition load(Element definition) {
 76  1 XMLTableDefinition answer = new XMLTableDefinition();
 77  1 answer.setRowExpression(definition.attributeValue("select"));
 78   
 79  1 for (Iterator iter = definition.elementIterator("column"); iter
 80    .hasNext();) {
 81  3 Element element = (Element) iter.next();
 82  3 String expression = element.attributeValue("select");
 83  3 String name = element.getText();
 84  3 String typeName = element.attributeValue("type", "string");
 85  3 String columnXPath = element.attributeValue("columnNameXPath");
 86  3 int type = XMLTableColumnDefinition.parseType(typeName);
 87   
 88  3 if (columnXPath != null) {
 89  0 answer.addColumnWithXPathName(columnXPath, expression, type);
 90    } else {
 91  3 answer.addColumn(name, expression, type);
 92    }
 93    }
 94   
 95  1 return answer;
 96    }
 97   
 98  0 public Class getColumnClass(int columnIndex) {
 99  0 return getColumn(columnIndex).getColumnClass();
 100    }
 101   
 102  2 public int getColumnCount() {
 103  2 return columns.size();
 104    }
 105   
 106    /**
 107    * DOCUMENT ME!
 108    *
 109    * @param columnIndex
 110    * DOCUMENT ME!
 111    *
 112    * @return the static column name. This is used if there is no
 113    * columnNameXPath
 114    */
 115  6 public String getColumnName(int columnIndex) {
 116  6 return getColumn(columnIndex).getName();
 117    }
 118   
 119    /**
 120    * DOCUMENT ME!
 121    *
 122    * @param columnIndex
 123    * DOCUMENT ME!
 124    *
 125    * @return the XPath expression used to evaluate the value of cells in this
 126    * column
 127    */
 128  0 public XPath getColumnXPath(int columnIndex) {
 129  0 return getColumn(columnIndex).getXPath();
 130    }
 131   
 132    /**
 133    * DOCUMENT ME!
 134    *
 135    * @param columnIndex
 136    * DOCUMENT ME!
 137    *
 138    * @return the XPath expresssion used to create the column name, if there is
 139    * one or null if there is no XPath expression to name the column.
 140    */
 141  6 public XPath getColumnNameXPath(int columnIndex) {
 142  6 return getColumn(columnIndex).getColumnNameXPath();
 143    }
 144   
 145  12 public synchronized Object getValueAt(Object row, int columnIndex) {
 146  12 XMLTableColumnDefinition column = getColumn(columnIndex);
 147  12 Object answer = null;
 148   
 149  12 synchronized (this) {
 150  12 this.rowValue = row;
 151  12 answer = column.getValue(row);
 152  12 this.rowValue = null;
 153    }
 154   
 155  12 return answer;
 156    }
 157   
 158  0 public void addColumn(String name, String expression) {
 159  0 addColumn(name, expression, XMLTableColumnDefinition.OBJECT_TYPE);
 160    }
 161   
 162  6 public void addColumn(String name, String expression, int type) {
 163  6 XPath xpath = createColumnXPath(expression);
 164  6 addColumn(new XMLTableColumnDefinition(name, xpath, type));
 165    }
 166   
 167  0 public void addColumnWithXPathName(String columnNameXPathExpression,
 168    String expression, int type) {
 169  0 XPath columnNameXPath = createColumnXPath(columnNameXPathExpression);
 170  0 XPath xpath = createColumnXPath(expression);
 171  0 addColumn(new XMLTableColumnDefinition(columnNameXPath, xpath, type));
 172    }
 173   
 174  3 public void addStringColumn(String name, String expression) {
 175  3 addColumn(name, expression, XMLTableColumnDefinition.STRING_TYPE);
 176    }
 177   
 178  0 public void addNumberColumn(String name, String expression) {
 179  0 addColumn(name, expression, XMLTableColumnDefinition.NUMBER_TYPE);
 180    }
 181   
 182  6 public void addColumn(XMLTableColumnDefinition column) {
 183  6 clearCaches();
 184  6 columns.add(column);
 185    }
 186   
 187  0 public void removeColumn(XMLTableColumnDefinition column) {
 188  0 clearCaches();
 189  0 columns.remove(column);
 190    }
 191   
 192  0 public void clear() {
 193  0 clearCaches();
 194  0 columns.clear();
 195    }
 196   
 197  24 public XMLTableColumnDefinition getColumn(int index) {
 198  24 if (columnArray == null) {
 199  2 columnArray = new XMLTableColumnDefinition[columns.size()];
 200  2 columns.toArray(columnArray);
 201    }
 202   
 203  24 return columnArray[index];
 204    }
 205   
 206  4 public XMLTableColumnDefinition getColumn(String columnName) {
 207  4 if (columnNameIndex == null) {
 208  2 columnNameIndex = new HashMap();
 209   
 210  2 for (Iterator it = columns.iterator(); it.hasNext();) {
 211  6 XMLTableColumnDefinition column = (XMLTableColumnDefinition) it
 212    .next();
 213  6 columnNameIndex.put(column.getName(), column);
 214    }
 215    }
 216   
 217  4 return (XMLTableColumnDefinition) columnNameIndex.get(columnName);
 218    }
 219   
 220    /**
 221    * Getter for property rowXPath.
 222    *
 223    * @return Value of property rowXPath.
 224    */
 225  2 public XPath getRowXPath() {
 226  2 return rowXPath;
 227    }
 228   
 229    /**
 230    * Setter for property rowXPath.
 231    *
 232    * @param rowXPath
 233    * New value of property rowXPath.
 234    */
 235  2 public void setRowXPath(XPath rowXPath) {
 236  2 this.rowXPath = rowXPath;
 237    }
 238   
 239  2 public void setRowExpression(String xpath) {
 240  2 setRowXPath(createXPath(xpath));
 241    }
 242   
 243    // VariableContext interface
 244    // -------------------------------------------------------------------------
 245  4 public Object getVariableValue(String namespaceURI, String prefix,
 246    String localName) {
 247  4 XMLTableColumnDefinition column = getColumn(localName);
 248   
 249  4 if (column != null) {
 250  4 return column.getValue(rowValue);
 251    }
 252   
 253  0 return null;
 254    }
 255   
 256    // Implementation methods
 257    // -------------------------------------------------------------------------
 258  8 protected XPath createXPath(String expression) {
 259  8 return DocumentHelper.createXPath(expression);
 260    }
 261   
 262  6 protected XPath createColumnXPath(String expression) {
 263  6 XPath xpath = createXPath(expression);
 264   
 265    // associate my variable context
 266  6 xpath.setVariableContext(this);
 267   
 268  6 return xpath;
 269    }
 270   
 271  6 protected void clearCaches() {
 272  6 columnArray = null;
 273  6 columnNameIndex = null;
 274    }
 275   
 276  0 protected void handleException(Exception e) {
 277    // #### should use jakarta commons-logging
 278  0 System.out.println("Caught: " + e);
 279    }
 280    }
 281   
 282    /*
 283    * Redistribution and use of this software and associated documentation
 284    * ("Software"), with or without modification, are permitted provided that the
 285    * following conditions are met:
 286    *
 287    * 1. Redistributions of source code must retain copyright statements and
 288    * notices. Redistributions must also contain a copy of this document.
 289    *
 290    * 2. Redistributions in binary form must reproduce the above copyright notice,
 291    * this list of conditions and the following disclaimer in the documentation
 292    * and/or other materials provided with the distribution.
 293    *
 294    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 295    * from this Software without prior written permission of MetaStuff, Ltd. For
 296    * written permission, please contact dom4j-info@metastuff.com.
 297    *
 298    * 4. Products derived from this Software may not be called "DOM4J" nor may
 299    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 300    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 301    *
 302    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 303    *
 304    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 305    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 306    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 307    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 308    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 309    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 310    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 311    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 312    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 313    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 314    * POSSIBILITY OF SUCH DAMAGE.
 315    *
 316    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 317    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/Namespace.html0000644000175000017500000022234110242117725020701 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 272   Methods: 18
NCLOC: 113   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
Namespace.java 81,8% 86,8% 83,3% 84,9%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    import org.dom4j.tree.AbstractNode;
 11    import org.dom4j.tree.DefaultNamespace;
 12    import org.dom4j.tree.NamespaceCache;
 13   
 14    /**
 15    * <p>
 16    * <code>Namespace</code> is a Flyweight Namespace that can be shared amongst
 17    * nodes.
 18    * </p>
 19    *
 20    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 21    * @version $Revision: 1.22 $
 22    */
 23    public class Namespace extends AbstractNode {
 24    /** Cache of Namespace instances */
 25    protected static final NamespaceCache CACHE = new NamespaceCache();
 26   
 27    /** XML Namespace */
 28    public static final Namespace XML_NAMESPACE = CACHE.get("xml",
 29    "http://www.w3.org/XML/1998/namespace");
 30   
 31    /** No Namespace present */
 32    public static final Namespace NO_NAMESPACE = CACHE.get("", "");
 33   
 34    /** The prefix mapped to this namespace */
 35    private String prefix;
 36   
 37    /** The URI for this namespace */
 38    private String uri;
 39   
 40    /** A cached version of the hashcode for efficiency */
 41    private int hashCode;
 42   
 43    /**
 44    * DOCUMENT ME!
 45    *
 46    * @param prefix
 47    * is the prefix for this namespace
 48    * @param uri
 49    * is the URI for this namespace
 50    */
 51  10603 public Namespace(String prefix, String uri) {
 52  10603 this.prefix = (prefix != null) ? prefix : "";
 53  10603 this.uri = (uri != null) ? uri : "";
 54    }
 55   
 56    /**
 57    * A helper method to return the Namespace instance for the given prefix and
 58    * URI
 59    *
 60    * @param prefix
 61    * DOCUMENT ME!
 62    * @param uri
 63    * DOCUMENT ME!
 64    *
 65    * @return an interned Namespace object
 66    */
 67  101172 public static Namespace get(String prefix, String uri) {
 68  101172 return CACHE.get(prefix, uri);
 69    }
 70   
 71    /**
 72    * A helper method to return the Namespace instance for no prefix and the
 73    * URI
 74    *
 75    * @param uri
 76    * DOCUMENT ME!
 77    *
 78    * @return an interned Namespace object
 79    */
 80  26 public static Namespace get(String uri) {
 81  26 return CACHE.get(uri);
 82    }
 83   
 84  732 public short getNodeType() {
 85  732 return NAMESPACE_NODE;
 86    }
 87   
 88    /**
 89    * DOCUMENT ME!
 90    *
 91    * @return the hash code based on the qualified name and the URI of the
 92    * namespace.
 93    */
 94  21734 public int hashCode() {
 95  21734 if (hashCode == 0) {
 96  312 hashCode = createHashCode();
 97    }
 98   
 99  21734 return hashCode;
 100    }
 101   
 102    /**
 103    * Factory method to create the hashcode allowing derived classes to change
 104    * the behaviour
 105    *
 106    * @return DOCUMENT ME!
 107    */
 108  312 protected int createHashCode() {
 109  312 int result = uri.hashCode() ^ prefix.hashCode();
 110   
 111  312 if (result == 0) {
 112  8 result = 0xbabe;
 113    }
 114   
 115  312 return result;
 116    }
 117   
 118    /**
 119    * Checks whether this Namespace equals the given Namespace. Two Namespaces
 120    * are equals if their URI and prefix are equal.
 121    *
 122    * @param object
 123    * DOCUMENT ME!
 124    *
 125    * @return DOCUMENT ME!
 126    */
 127  5594 public boolean equals(Object object) {
 128  5594 if (this == object) {
 129  4783 return true;
 130  811 } else if (object instanceof Namespace) {
 131  626 Namespace that = (Namespace) object;
 132   
 133    // we cache hash codes so this should be quick
 134  626 if (hashCode() == that.hashCode()) {
 135  148 return uri.equals(that.getURI())
 136    && prefix.equals(that.getPrefix());
 137    }
 138    }
 139   
 140  663 return false;
 141    }
 142   
 143  0 public String getText() {
 144  0 return uri;
 145    }
 146   
 147  0 public String getStringValue() {
 148  0 return uri;
 149    }
 150   
 151    /**
 152    * DOCUMENT ME!
 153    *
 154    * @return the prefix for this <code>Namespace</code>.
 155    */
 156  69780 public String getPrefix() {
 157  69780 return prefix;
 158    }
 159   
 160    /**
 161    * DOCUMENT ME!
 162    *
 163    * @return the URI for this <code>Namespace</code>.
 164    */
 165  351051 public String getURI() {
 166  351051 return uri;
 167    }
 168   
 169  12 public String getXPathNameStep() {
 170  12 if ((prefix != null) && !"".equals(prefix)) {
 171  6 return "namespace::" + prefix;
 172    }
 173   
 174  6 return "namespace::*[name()='']";
 175    }
 176   
 177  6 public String getPath(Element context) {
 178  6 StringBuffer path = new StringBuffer(10);
 179  6 Element parent = getParent();
 180   
 181  6 if ((parent != null) && (parent != context)) {
 182  0 path.append(parent.getPath(context));
 183  0 path.append('/');
 184    }
 185   
 186  6 path.append(getXPathNameStep());
 187   
 188  6 return path.toString();
 189    }
 190   
 191  6 public String getUniquePath(Element context) {
 192  6 StringBuffer path = new StringBuffer(10);
 193  6 Element parent = getParent();
 194   
 195  6 if ((parent != null) && (parent != context)) {
 196  0 path.append(parent.getUniquePath(context));
 197  0 path.append('/');
 198    }
 199   
 200  6 path.append(getXPathNameStep());
 201   
 202  6 return path.toString();
 203    }
 204   
 205  32 public String toString() {
 206  32 return super.toString() + " [Namespace: prefix " + getPrefix()
 207    + " mapped to URI \"" + getURI() + "\"]";
 208    }
 209   
 210  26 public String asXML() {
 211  26 StringBuffer asxml = new StringBuffer(10);
 212  26 String pref = getPrefix();
 213   
 214  26 if ((pref != null) && (pref.length() > 0)) {
 215  14 asxml.append("xmlns:");
 216  14 asxml.append(pref);
 217  14 asxml.append("=\"");
 218    } else {
 219  12 asxml.append("xmlns=\"");
 220    }
 221   
 222  26 asxml.append(getURI());
 223  26 asxml.append("\"");
 224   
 225  26 return asxml.toString();
 226    }
 227   
 228  0 public void accept(Visitor visitor) {
 229  0 visitor.visit(this);
 230    }
 231   
 232  107 protected Node createXPathResult(Element parent) {
 233  107 return new DefaultNamespace(parent, getPrefix(), getURI());
 234    }
 235    }
 236   
 237    /*
 238    * Redistribution and use of this software and associated documentation
 239    * ("Software"), with or without modification, are permitted provided that the
 240    * following conditions are met:
 241    *
 242    * 1. Redistributions of source code must retain copyright statements and
 243    * notices. Redistributions must also contain a copy of this document.
 244    *
 245    * 2. Redistributions in binary form must reproduce the above copyright notice,
 246    * this list of conditions and the following disclaimer in the documentation
 247    * and/or other materials provided with the distribution.
 248    *
 249    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 250    * from this Software without prior written permission of MetaStuff, Ltd. For
 251    * written permission, please contact dom4j-info@metastuff.com.
 252    *
 253    * 4. Products derived from this Software may not be called "DOM4J" nor may
 254    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 255    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 256    *
 257    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 258    *
 259    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 260    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 261    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 262    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 263    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 264    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 265    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 266    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 267    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 268    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 269    * POSSIBILITY OF SUCH DAMAGE.
 270    *
 271    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 272    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/xpp/0000755000175000017500000000000012133227266016725 5ustar ebourgebourgdom4j-1.6.1/docs/clover/org/dom4j/xpp/pkg-classes.html0000644000175000017500000000151610242117564022030 0ustar ebourgebourg dom4j - 1.6.1 org.dom4j.xpp
Classes
ProxyXmlStartTag (0%)
dom4j-1.6.1/docs/clover/org/dom4j/xpp/ProxyXmlStartTag.html0000644000175000017500000026134010242117614023067 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 322   Methods: 28
NCLOC: 193   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
ProxyXmlStartTag.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.xpp;
 9   
 10    import java.util.ArrayList;
 11    import java.util.Iterator;
 12   
 13    import org.dom4j.Attribute;
 14    import org.dom4j.DocumentFactory;
 15    import org.dom4j.Element;
 16    import org.dom4j.QName;
 17    import org.dom4j.tree.AbstractElement;
 18   
 19    import org.gjt.xpp.XmlPullParserException;
 20    import org.gjt.xpp.XmlStartTag;
 21   
 22    /**
 23    * <code>ProxyXmlStartTag</code> implements the XPP <code>XmlSmartTag</code>
 24    * interface while creating a dom4j <code>Element</code> underneath.
 25    *
 26    * @author James Strachan
 27    * @author Maarten Coene
 28    * @author Wolfgang Baer
 29    */
 30    public class ProxyXmlStartTag implements XmlStartTag {
 31    /** The element being constructed */
 32    private Element element;
 33   
 34    /** The factory used to create new elements */
 35    private DocumentFactory factory = DocumentFactory.getInstance();
 36   
 37  0 public ProxyXmlStartTag() {
 38    }
 39   
 40  0 public ProxyXmlStartTag(Element element) {
 41  0 this.element = element;
 42    }
 43   
 44    // XmlStartTag interface
 45    // -------------------------------------------------------------------------
 46  0 public void resetStartTag() {
 47  0 this.element = null;
 48    }
 49   
 50  0 public int getAttributeCount() {
 51  0 return (element != null) ? element.attributeCount() : 0;
 52    }
 53   
 54  0 public String getAttributeNamespaceUri(int index) {
 55  0 if (element != null) {
 56  0 Attribute attribute = element.attribute(index);
 57   
 58  0 if (attribute != null) {
 59  0 return attribute.getNamespaceURI();
 60    }
 61    }
 62   
 63  0 return null;
 64    }
 65   
 66  0 public String getAttributeLocalName(int index) {
 67  0 if (element != null) {
 68  0 Attribute attribute = element.attribute(index);
 69   
 70  0 if (attribute != null) {
 71  0 return attribute.getName();
 72    }
 73    }
 74   
 75  0 return null;
 76    }
 77   
 78  0 public String getAttributePrefix(int index) {
 79  0 if (element != null) {
 80  0 Attribute attribute = element.attribute(index);
 81   
 82  0 if (attribute != null) {
 83  0 String prefix = attribute.getNamespacePrefix();
 84   
 85  0 if ((prefix != null) && (prefix.length() > 0)) {
 86  0 return prefix;
 87    }
 88    }
 89    }
 90   
 91  0 return null;
 92    }
 93   
 94  0 public String getAttributeRawName(int index) {
 95  0 if (element != null) {
 96  0 Attribute attribute = element.attribute(index);
 97   
 98  0 if (attribute != null) {
 99  0 return attribute.getQualifiedName();
 100    }
 101    }
 102   
 103  0 return null;
 104    }
 105   
 106  0 public String getAttributeValue(int index) {
 107  0 if (element != null) {
 108  0 Attribute attribute = element.attribute(index);
 109   
 110  0 if (attribute != null) {
 111  0 return attribute.getValue();
 112    }
 113    }
 114   
 115  0 return null;
 116    }
 117   
 118  0 public String getAttributeValueFromRawName(String rawName) {
 119  0 if (element != null) {
 120  0 for (Iterator iter = element.attributeIterator(); iter.hasNext();) {
 121  0 Attribute attribute = (Attribute) iter.next();
 122   
 123  0 if (rawName.equals(attribute.getQualifiedName())) {
 124  0 return attribute.getValue();
 125    }
 126    }
 127    }
 128   
 129  0 return null;
 130    }
 131   
 132  0 public String getAttributeValueFromName(String namespaceURI,
 133    String localName) {
 134  0 if (element != null) {
 135  0 for (Iterator iter = element.attributeIterator(); iter.hasNext();) {
 136  0 Attribute attribute = (Attribute) iter.next();
 137   
 138  0 if (namespaceURI.equals(attribute.getNamespaceURI())
 139    && localName.equals(attribute.getName())) {
 140  0 return attribute.getValue();
 141    }
 142    }
 143    }
 144   
 145  0 return null;
 146    }
 147   
 148  0 public boolean isAttributeNamespaceDeclaration(int index) {
 149  0 if (element != null) {
 150  0 Attribute attribute = element.attribute(index);
 151   
 152  0 if (attribute != null) {
 153  0 return "xmlns".equals(attribute.getNamespacePrefix());
 154    }
 155    }
 156   
 157  0 return false;
 158    }
 159   
 160    /**
 161    * parameters modeled after SAX2 attribute approach
 162    *
 163    * @param namespaceURI DOCUMENT ME!
 164    * @param localName DOCUMENT ME!
 165    * @param rawName DOCUMENT ME!
 166    * @param value DOCUMENT ME!
 167    *
 168    * @throws XmlPullParserException DOCUMENT ME!
 169    */
 170  0 public void addAttribute(String namespaceURI, String localName,
 171    String rawName, String value) throws XmlPullParserException {
 172  0 QName qname = QName.get(rawName, namespaceURI);
 173  0 element.addAttribute(qname, value);
 174    }
 175   
 176  0 public void addAttribute(String namespaceURI, String localName,
 177    String rawName, String value, boolean isNamespaceDeclaration)
 178    throws XmlPullParserException {
 179  0 if (isNamespaceDeclaration) {
 180  0 String prefix = "";
 181  0 int idx = rawName.indexOf(':');
 182   
 183  0 if (idx > 0) {
 184  0 prefix = rawName.substring(0, idx);
 185    }
 186   
 187  0 element.addNamespace(prefix, namespaceURI);
 188    } else {
 189  0 QName qname = QName.get(rawName, namespaceURI);
 190  0 element.addAttribute(qname, value);
 191    }
 192    }
 193   
 194  0 public void ensureAttributesCapacity(int minCapacity)
 195    throws XmlPullParserException {
 196  0 if (element instanceof AbstractElement) {
 197  0 AbstractElement elementImpl = (AbstractElement) element;
 198  0 elementImpl.ensureAttributesCapacity(minCapacity);
 199    }
 200    }
 201   
 202    /**
 203    * Remove all atributes.
 204    *
 205    * @deprecated Use {@link #removeAttributes()} instead.
 206    */
 207  0 public void removeAtttributes() throws XmlPullParserException {
 208  0 removeAttributes();
 209    }
 210   
 211  0 public void removeAttributes() throws XmlPullParserException {
 212  0 if (element != null) {
 213  0 element.setAttributes(new ArrayList());
 214   
 215    // ##### FIXME
 216    // adding this method would be nice...
 217    // element.clearAttributes();
 218    }
 219    }
 220   
 221  0 public String getLocalName() {
 222  0 return element.getName();
 223    }
 224   
 225  0 public String getNamespaceUri() {
 226  0 return element.getNamespaceURI();
 227    }
 228   
 229  0 public String getPrefix() {
 230  0 return element.getNamespacePrefix();
 231    }
 232   
 233  0 public String getRawName() {
 234  0 return element.getQualifiedName();
 235    }
 236   
 237  0 public void modifyTag(String namespaceURI, String lName, String rawName) {
 238  0 this.element = factory.createElement(rawName, namespaceURI);
 239    }
 240   
 241  0 public void resetTag() {
 242  0 this.element = null;
 243    }
 244   
 245  0 public boolean removeAttributeByName(String namespaceURI, String localName)
 246    throws XmlPullParserException {
 247  0 if (element != null) {
 248  0 QName qname = QName.get(localName, namespaceURI);
 249  0 Attribute attribute = element.attribute(qname);
 250  0 return element.remove(attribute);
 251    }
 252  0 return false;
 253    }
 254   
 255  0 public boolean removeAttributeByRawName(String rawName)
 256    throws XmlPullParserException {
 257  0 if (element != null) {
 258  0 Attribute attribute = null;
 259  0 Iterator it = element.attributeIterator();
 260  0 while (it.hasNext()) {
 261  0 Attribute current = (Attribute) it.next();
 262  0 if (current.getQualifiedName().equals(rawName)) {
 263  0 attribute = current;
 264  0 break;
 265    }
 266    }
 267  0 return element.remove(attribute);
 268    }
 269  0 return false;
 270    }
 271   
 272    // Properties
 273    // -------------------------------------------------------------------------
 274  0 public DocumentFactory getDocumentFactory() {
 275  0 return factory;
 276    }
 277   
 278  0 public void setDocumentFactory(DocumentFactory documentFactory) {
 279  0 this.factory = documentFactory;
 280    }
 281   
 282  0 public Element getElement() {
 283  0 return element;
 284    }
 285    }
 286   
 287    /*
 288    * Redistribution and use of this software and associated documentation
 289    * ("Software"), with or without modification, are permitted provided that the
 290    * following conditions are met:
 291    *
 292    * 1. Redistributions of source code must retain copyright statements and
 293    * notices. Redistributions must also contain a copy of this document.
 294    *
 295    * 2. Redistributions in binary form must reproduce the above copyright notice,
 296    * this list of conditions and the following disclaimer in the documentation
 297    * and/or other materials provided with the distribution.
 298    *
 299    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 300    * from this Software without prior written permission of MetaStuff, Ltd. For
 301    * written permission, please contact dom4j-info@metastuff.com.
 302    *
 303    * 4. Products derived from this Software may not be called "DOM4J" nor may
 304    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 305    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 306    *
 307    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 308    *
 309    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 310    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 311    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 312    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 313    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 314    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 315    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 316    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 317    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 318    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 319    * POSSIBILITY OF SUCH DAMAGE.
 320    *
 321    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 322    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/xpp/pkg-summary.html0000644000175000017500000001112510242117736022066 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
package stats: LOC: 322   Methods: 28
NCLOC: 193   Classes: 1
Files: 1  
 
 Package Conditionals Statements Methods TOTAL
org.dom4j.xpp 0% 0% 0% 0%
coverage
 
 Classes Conditionals Statements Methods TOTAL
ProxyXmlStartTag 0% 0% 0% 0%
coverage
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/pkg-summary.html0000644000175000017500000002630210242117707021260 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
package stats: LOC: 5.354   Methods: 133
NCLOC: 1.031   Classes: 26
Files: 26  
 
 Package Conditionals Statements Methods TOTAL
org.dom4j 69,6% 72,1% 61,7% 69%
coverage coverage
 
 Classes Conditionals Statements Methods TOTAL
VisitorSupport - - 0% 0%
coverage
DocumentException 0% 9,1% 11,1% 7,7%
coverage coverage
XPathException - 28,6% 25% 27,3%
coverage coverage
InvalidXPathException - 33,3% 33,3% 33,3%
coverage coverage
IllegalAddException - 66,7% 66,7% 66,7%
coverage coverage
DocumentHelper 95% 75,4% 50% 72,6%
coverage coverage
QName 61,8% 76,8% 81% 73,4%
coverage coverage
DocumentFactory 75% 78,9% 86,1% 80,9%
coverage coverage
Namespace 81,8% 86,8% 83,3% 84,9%
coverage coverage
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/jaxb/0000755000175000017500000000000012133227266017042 5ustar ebourgebourgdom4j-1.6.1/docs/clover/org/dom4j/jaxb/pkg-classes.html0000644000175000017500000000366510242117733022152 0ustar ebourgebourg dom4j - 1.6.1 org.dom4j.jaxb
Classes
JAXBModifier (0%)
JAXBModifier.JAXBElementModifier (0%)
JAXBReader (0%)
JAXBReader.PruningElementHandler (0%)
JAXBReader.UnmarshalElementHandler (0%)
JAXBRuntimeException (0%)
JAXBSupport (0%)
JAXBWriter (0%)
dom4j-1.6.1/docs/clover/org/dom4j/jaxb/JAXBObjectHandler.html0000644000175000017500000005035010242117671023101 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 69   Methods: 0
NCLOC: 5   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
JAXBObjectHandler.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.jaxb;
 9   
 10    import javax.xml.bind.Element;
 11   
 12    /**
 13    * JAXBObjectHandler implementations can be registered with the JAXB Reader in
 14    * order to receive unmarshalled XML fragments.
 15    *
 16    * @author Wonne Keysers (Realsoftware.be)
 17    */
 18    public interface JAXBObjectHandler {
 19    /**
 20    * Called when the {@link JAXBReader}has finished parsing the xml path the
 21    * handler was registered for. The provided object is the unmarshalled
 22    * representation of the XML path. It can be casted to the appropriate
 23    * implementation class that is generated by the JAXB compiler.
 24    *
 25    * @param jaxbElement
 26    * the unmarshalled JAXB object to handle
 27    *
 28    * @throws Exception
 29    * of any kind, thrown by the implementation
 30    */
 31    void handleObject(Element jaxbElement) throws Exception;
 32    }
 33   
 34    /*
 35    * Redistribution and use of this software and associated documentation
 36    * ("Software"), with or without modification, are permitted provided that the
 37    * following conditions are met:
 38    *
 39    * 1. Redistributions of source code must retain copyright statements and
 40    * notices. Redistributions must also contain a copy of this document.
 41    *
 42    * 2. Redistributions in binary form must reproduce the above copyright notice,
 43    * this list of conditions and the following disclaimer in the documentation
 44    * and/or other materials provided with the distribution.
 45    *
 46    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 47    * from this Software without prior written permission of MetaStuff, Ltd. For
 48    * written permission, please contact dom4j-info@metastuff.com.
 49    *
 50    * 4. Products derived from this Software may not be called "DOM4J" nor may
 51    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 52    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 53    *
 54    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 55    *
 56    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 57    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 58    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 59    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 60    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 61    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 62    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 63    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 64    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 65    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 66    * POSSIBILITY OF SUCH DAMAGE.
 67    *
 68    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 69    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/jaxb/pkg-summary.html0000644000175000017500000002237310242117704022205 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
package stats: LOC: 1.653   Methods: 77
NCLOC: 511   Classes: 10
Files: 7  
 
 Package Conditionals Statements Methods TOTAL
org.dom4j.jaxb 0% 0% 0% 0%
coverage
 
 Classes Conditionals Statements Methods TOTAL
JAXBModifier 0% 0% 0% 0%
coverage
JAXBModifier.JAXBElementModifier - 0% 0% 0%
coverage
JAXBReader 0% 0% 0% 0%
coverage
JAXBReader.PruningElementHandler - 0% 0% 0%
coverage
JAXBReader.UnmarshalElementHandler 0% 0% 0% 0%
coverage
JAXBRuntimeException - 0% 0% 0%
coverage
JAXBSupport 0% 0% 0% 0%
coverage
JAXBWriter 0% 0% 0% 0%
coverage
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/jaxb/JAXBReader.html0000644000175000017500000034341310242117751021603 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 436   Methods: 25
NCLOC: 165   Classes: 3
 
 Source file Conditionals Statements Methods TOTAL
JAXBReader.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.jaxb;
 9   
 10    import java.io.File;
 11    import java.io.FileInputStream;
 12    import java.io.FileNotFoundException;
 13    import java.io.InputStream;
 14    import java.io.InputStreamReader;
 15    import java.io.Reader;
 16    import java.net.URL;
 17    import java.nio.charset.Charset;
 18   
 19    import org.dom4j.Document;
 20    import org.dom4j.DocumentException;
 21    import org.dom4j.Element;
 22    import org.dom4j.ElementHandler;
 23    import org.dom4j.ElementPath;
 24    import org.dom4j.io.SAXReader;
 25   
 26    import org.xml.sax.InputSource;
 27   
 28    /**
 29    * Reads an XML document and creates a DOM4J tree from SAX parsing events.
 30    * {@link JAXBObjectHandler}objects can be registered to automatically receive
 31    * unmarshalled XML fragments. Registered {@linkorg.dom4j.ElementHandler}
 32    * implementations are notified when a certain element path is encountered
 33    *
 34    * @author Wonne Keysers (Realsoftware.be)
 35    *
 36    * @see org.dom4j.io.SAXReader
 37    * @see javax.xml.bind.JAXBContext
 38    */
 39    public class JAXBReader extends JAXBSupport {
 40    private SAXReader reader;
 41   
 42    private boolean pruneElements;
 43   
 44    /**
 45    * Creates a new JAXBReader for the given JAXB context path. This is the
 46    * Java package where JAXB can find the generated XML classes. This package
 47    * MUST contain jaxb.properties!
 48    *
 49    * @param contextPath
 50    * context path to be used
 51    *
 52    * @see javax.xml.bind.JAXBContext
 53    */
 54  0 public JAXBReader(String contextPath) {
 55  0 super(contextPath);
 56    }
 57   
 58    /**
 59    * Creates a new JAXBReader for the given JAXB context path, using the
 60    * specified {@link java.lang.Classloader}. This is the Java package where
 61    * JAXB can find the generated XML classes. This package MUST contain
 62    * jaxb.properties!
 63    *
 64    * @param contextPath
 65    * to be used
 66    * @param classloader
 67    * to be used
 68    *
 69    * @see javax.xml.bind.JAXBContext
 70    */
 71  0 public JAXBReader(String contextPath, ClassLoader classloader) {
 72  0 super(contextPath, classloader);
 73    }
 74   
 75    /**
 76    * Parses the specified {@link java.io.File}
 77    *
 78    * @param source
 79    * the file to parse
 80    *
 81    * @return the resulting DOM4J document
 82    *
 83    * @throws DocumentException
 84    * when an error occurs while parsing
 85    */
 86  0 public Document read(File source) throws DocumentException {
 87  0 return getReader().read(source);
 88    }
 89   
 90    /**
 91    * Parses the specified {@link java.io.File}, using the given {@link
 92    * java.nio.charset.Charset}.
 93    *
 94    * @param file
 95    * the file to parse
 96    * @param charset
 97    * the charset to be used
 98    *
 99    * @return the resulting DOM4J document
 100    *
 101    * @throws DocumentException
 102    * when an error occurs while parsing
 103    */
 104  0 public Document read(File file, Charset charset) throws DocumentException {
 105  0 try {
 106  0 Reader xmlReader = new InputStreamReader(new FileInputStream(file),
 107    charset);
 108   
 109  0 return getReader().read(xmlReader);
 110    } catch (JAXBRuntimeException ex) {
 111  0 Throwable cause = ex.getCause();
 112  0 throw new DocumentException(cause.getMessage(), cause);
 113    } catch (FileNotFoundException ex) {
 114  0 throw new DocumentException(ex.getMessage(), ex);
 115    }
 116    }
 117   
 118    /**
 119    * Parses the specified {@link org.xml.sax.InputSource}
 120    *
 121    * @param source
 122    * the source to parse
 123    *
 124    * @return the resulting DOM4J document
 125    *
 126    * @throws DocumentException
 127    * when an error occurs while parsing
 128    */
 129  0 public Document read(InputSource source) throws DocumentException {
 130  0 try {
 131  0 return getReader().read(source);
 132    } catch (JAXBRuntimeException ex) {
 133  0 Throwable cause = ex.getCause();
 134  0 throw new DocumentException(cause.getMessage(), cause);
 135    }
 136    }
 137   
 138    /**
 139    * Parses the specified {@link java.io.InputStream}
 140    *
 141    * @param source
 142    * the input stream to parse
 143    *
 144    * @return the resulting DOM4J document
 145    *
 146    * @throws DocumentException
 147    * when an error occurs while parsing
 148    */
 149  0 public Document read(InputStream source) throws DocumentException {
 150  0 try {
 151  0 return getReader().read(source);
 152    } catch (JAXBRuntimeException ex) {
 153  0 Throwable cause = ex.getCause();
 154  0 throw new DocumentException(cause.getMessage(), cause);
 155    }
 156    }
 157   
 158    /**
 159    * Parses the specified {@link java.io.InputStream}
 160    *
 161    * @param source
 162    * the input stream to parse
 163    * @param systemId
 164    * is the URI for the input
 165    *
 166    * @return the resulting DOM4J document
 167    *
 168    * @throws DocumentException
 169    * when an error occurs while parsing
 170    */
 171  0 public Document read(InputStream source, String systemId)
 172    throws DocumentException {
 173  0 try {
 174  0 return getReader().read(source);
 175    } catch (JAXBRuntimeException ex) {
 176  0 Throwable cause = ex.getCause();
 177  0 throw new DocumentException(cause.getMessage(), cause);
 178    }
 179    }
 180   
 181    /**
 182    * Parses the specified {@link java.io.Reader}
 183    *
 184    * @param source
 185    * the input reader to use
 186    *
 187    * @return the resulting DOM4J document
 188    *
 189    * @throws DocumentException
 190    * when an error occurs while parsing
 191    */
 192  0 public Document read(Reader source) throws DocumentException {
 193  0 try {
 194  0 return getReader().read(source);
 195    } catch (JAXBRuntimeException ex) {
 196  0 Throwable cause = ex.getCause();
 197  0 throw new DocumentException(cause.getMessage(), cause);
 198    }
 199    }
 200   
 201    /**
 202    * Parses the specified {@link java.io.Reader}
 203    *
 204    * @param source
 205    * the input reader to parse
 206    * @param systemId
 207    * is the URI for the input
 208    *
 209    * @return the resulting DOM4J document
 210    *
 211    * @throws DocumentException
 212    * when an error occurs while parsing
 213    */
 214  0 public Document read(Reader source, String systemId)
 215    throws DocumentException {
 216  0 try {
 217  0 return getReader().read(source);
 218    } catch (JAXBRuntimeException ex) {
 219  0 Throwable cause = ex.getCause();
 220  0 throw new DocumentException(cause.getMessage(), cause);
 221    }
 222    }
 223   
 224    /**
 225    * Parses the the given URL or filename.
 226    *
 227    * @param source
 228    * the location to parse
 229    *
 230    * @return the resulting DOM4J document
 231    *
 232    * @throws DocumentException
 233    * when an error occurs while parsing
 234    */
 235  0 public Document read(String source) throws DocumentException {
 236  0 try {
 237  0 return getReader().read(source);
 238    } catch (JAXBRuntimeException ex) {
 239  0 Throwable cause = ex.getCause();
 240  0 throw new DocumentException(cause.getMessage(), cause);
 241    }
 242    }
 243   
 244    /**
 245    * Parses the the given URL.
 246    *
 247    * @param source
 248    * the URL to parse
 249    *
 250    * @return the resulting DOM4J document
 251    *
 252    * @throws DocumentException
 253    * when an error occurs while parsing
 254    */
 255  0 public Document read(URL source) throws DocumentException {
 256  0 try {
 257  0 return getReader().read(source);
 258    } catch (JAXBRuntimeException ex) {
 259  0 Throwable cause = ex.getCause();
 260  0 throw new DocumentException(cause.getMessage(), cause);
 261    }
 262    }
 263   
 264    /**
 265    * Registers a {@link JAXBObjectHandler}that will be supplied with the
 266    * unmarshalled representation of the xml fragment whenever the specified
 267    * path is encounted.
 268    *
 269    * @param path
 270    * the path to listen for
 271    * @param handler
 272    * the handler to be notified
 273    */
 274  0 public void addObjectHandler(String path, JAXBObjectHandler handler) {
 275  0 ElementHandler eHandler = new UnmarshalElementHandler(this, handler);
 276  0 getReader().addHandler(path, eHandler);
 277    }
 278   
 279    /**
 280    * Removes the {@link JAXBObjectHandler}from the event based processor, for
 281    * the specified element path.
 282    *
 283    * @param path
 284    * The path to remove the {@link JAXBObjectHandler}for
 285    */
 286  0 public void removeObjectHandler(String path) {
 287  0 getReader().removeHandler(path);
 288    }
 289   
 290    /**
 291    * Adds the <code>ElementHandler</code> to be called when the specified
 292    * path is encounted.
 293    *
 294    * @param path
 295    * is the path to be handled
 296    * @param handler
 297    * is the <code>ElementHandler</code> to be called by the event
 298    * based processor.
 299    */
 300  0 public void addHandler(String path, ElementHandler handler) {
 301  0 getReader().addHandler(path, handler);
 302    }
 303   
 304    /**
 305    * Removes the <code>ElementHandler</code> from the event based processor,
 306    * for the specified path.
 307    *
 308    * @param path
 309    * is the path to remove the <code>ElementHandler</code> for.
 310    */
 311  0 public void removeHandler(String path) {
 312  0 getReader().removeHandler(path);
 313    }
 314   
 315    /**
 316    * Removes all registered {@link JAXBObjectHandler}and {@link
 317    * org.dom4j.ElementHandler} instances from the event based processor.
 318    */
 319  0 public void resetHandlers() {
 320  0 getReader().resetHandlers();
 321    }
 322   
 323    /**
 324    * When 'true', the DOM4J document will not be kept in memory while parsing.
 325    *
 326    * @return Returns the pruneElements.
 327    */
 328  0 public boolean isPruneElements() {
 329  0 return pruneElements;
 330    }
 331   
 332    /**
 333    * Set to true when DOM4J elements must immediately be pruned from the tree.
 334    * The {@link Document}will not be available afterwards!
 335    *
 336    * @param pruneElements
 337    */
 338  0 public void setPruneElements(boolean pruneElements) {
 339  0 this.pruneElements = pruneElements;
 340   
 341  0 if (pruneElements) {
 342  0 getReader().setDefaultHandler(new PruningElementHandler());
 343    }
 344    }
 345   
 346  0 private SAXReader getReader() {
 347  0 if (reader == null) {
 348  0 reader = new SAXReader();
 349    }
 350   
 351  0 return reader;
 352    }
 353   
 354    private class UnmarshalElementHandler implements ElementHandler {
 355    private JAXBReader jaxbReader;
 356   
 357    private JAXBObjectHandler handler;
 358   
 359  0 public UnmarshalElementHandler(JAXBReader documentReader,
 360    JAXBObjectHandler handler) {
 361  0 this.jaxbReader = documentReader;
 362  0 this.handler = handler;
 363    }
 364   
 365  0 public void onStart(ElementPath elementPath) {
 366    }
 367   
 368  0 public void onEnd(ElementPath elementPath) {
 369  0 try {
 370  0 org.dom4j.Element elem = elementPath.getCurrent();
 371   
 372  0 javax.xml.bind.Element jaxbObject
 373    = (javax.xml.bind.Element) jaxbReader.unmarshal(elem);
 374   
 375  0 if (jaxbReader.isPruneElements()) {
 376  0 elem.detach();
 377    }
 378   
 379  0 handler.handleObject(jaxbObject);
 380    } catch (Exception ex) {
 381  0 throw new JAXBRuntimeException(ex);
 382    }
 383    }
 384    }
 385   
 386    private class PruningElementHandler implements ElementHandler {
 387  0 public PruningElementHandler() {
 388    }
 389   
 390  0 public void onStart(ElementPath parm1) {
 391    }
 392   
 393  0 public void onEnd(ElementPath elementPath) {
 394  0 Element elem = elementPath.getCurrent();
 395  0 elem.detach();
 396  0 elem = null;
 397    }
 398    }
 399    }
 400   
 401    /*
 402    * Redistribution and use of this software and associated documentation
 403    * ("Software"), with or without modification, are permitted provided that the
 404    * following conditions are met:
 405    *
 406    * 1. Redistributions of source code must retain copyright statements and
 407    * notices. Redistributions must also contain a copy of this document.
 408    *
 409    * 2. Redistributions in binary form must reproduce the above copyright notice,
 410    * this list of conditions and the following disclaimer in the documentation
 411    * and/or other materials provided with the distribution.
 412    *
 413    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 414    * from this Software without prior written permission of MetaStuff, Ltd. For
 415    * written permission, please contact dom4j-info@metastuff.com.
 416    *
 417    * 4. Products derived from this Software may not be called "DOM4J" nor may
 418    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 419    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 420    *
 421    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 422    *
 423    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 424    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 425    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 426    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 427    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 428    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 429    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 430    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 431    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 432    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 433    * POSSIBILITY OF SUCH DAMAGE.
 434    *
 435    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 436    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/jaxb/JAXBSupport.html0000644000175000017500000012056710242117621022054 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 149   Methods: 7
NCLOC: 56   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
JAXBSupport.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.jaxb;
 9   
 10    import java.io.StringReader;
 11   
 12    import javax.xml.bind.JAXBContext;
 13    import javax.xml.bind.JAXBException;
 14    import javax.xml.bind.Marshaller;
 15    import javax.xml.bind.Unmarshaller;
 16    import javax.xml.transform.Source;
 17    import javax.xml.transform.stream.StreamSource;
 18   
 19    import org.dom4j.dom.DOMDocument;
 20   
 21    /**
 22    * DOCUMENT ME!
 23    *
 24    * @author Wonne Keysers (Realsoftware.be)
 25    */
 26    abstract class JAXBSupport {
 27    private String contextPath;
 28   
 29    private ClassLoader classloader;
 30   
 31    private JAXBContext jaxbContext;
 32   
 33    private Marshaller marshaller;
 34   
 35    private Unmarshaller unmarshaller;
 36   
 37  0 public JAXBSupport(String contextPath) {
 38  0 this.contextPath = contextPath;
 39    }
 40   
 41  0 public JAXBSupport(String contextPath, ClassLoader classloader) {
 42  0 this.contextPath = contextPath;
 43  0 this.classloader = classloader;
 44    }
 45   
 46    /**
 47    * Marshals the given {@link javax.xml.bind.Element}in to its DOM4J
 48    * counterpart.
 49    *
 50    * @param element
 51    * JAXB Element to be marshalled
 52    *
 53    * @return the marshalled DOM4J {@link org.dom4j.Element}
 54    *
 55    * @throws JAXBException
 56    * when an error occurs
 57    */
 58  0 protected org.dom4j.Element marshal(javax.xml.bind.Element element)
 59    throws JAXBException {
 60  0 DOMDocument doc = new DOMDocument();
 61  0 getMarshaller().marshal(element, doc);
 62   
 63  0 return doc.getRootElement();
 64    }
 65   
 66    /**
 67    * Unmarshalls the specified DOM4J {@link org.dom4j.Element}into a {@link
 68    * javax.xml.bind.Element}
 69    *
 70    * @param element
 71    * the DOM4J element to unmarshall
 72    *
 73    * @return the unmarshalled JAXB object
 74    *
 75    * @throws JAXBException
 76    * when an error occurs
 77    */
 78  0 protected javax.xml.bind.Element unmarshal(org.dom4j.Element element)
 79    throws JAXBException {
 80  0 Source source = new StreamSource(new StringReader(element.asXML()));
 81   
 82  0 return (javax.xml.bind.Element) getUnmarshaller().unmarshal(source);
 83    }
 84   
 85  0 private Marshaller getMarshaller() throws JAXBException {
 86  0 if (marshaller == null) {
 87  0 marshaller = getContext().createMarshaller();
 88    }
 89   
 90  0 return marshaller;
 91    }
 92   
 93  0 private Unmarshaller getUnmarshaller() throws JAXBException {
 94  0 if (unmarshaller == null) {
 95  0 unmarshaller = getContext().createUnmarshaller();
 96    }
 97   
 98  0 return unmarshaller;
 99    }
 100   
 101  0 private JAXBContext getContext() throws JAXBException {
 102  0 if (jaxbContext == null) {
 103  0 if (classloader == null) {
 104  0 jaxbContext = JAXBContext.newInstance(contextPath);
 105    } else {
 106  0 jaxbContext = JAXBContext.newInstance(contextPath, classloader);
 107    }
 108    }
 109   
 110  0 return jaxbContext;
 111    }
 112    }
 113   
 114    /*
 115    * Redistribution and use of this software and associated documentation
 116    * ("Software"), with or without modification, are permitted provided that the
 117    * following conditions are met:
 118    *
 119    * 1. Redistributions of source code must retain copyright statements and
 120    * notices. Redistributions must also contain a copy of this document.
 121    *
 122    * 2. Redistributions in binary form must reproduce the above copyright notice,
 123    * this list of conditions and the following disclaimer in the documentation
 124    * and/or other materials provided with the distribution.
 125    *
 126    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 127    * from this Software without prior written permission of MetaStuff, Ltd. For
 128    * written permission, please contact dom4j-info@metastuff.com.
 129    *
 130    * 4. Products derived from this Software may not be called "DOM4J" nor may
 131    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 132    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 133    *
 134    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 135    *
 136    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 137    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 138    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 139    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 140    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 141    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 142    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 143    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 144    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 145    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 146    * POSSIBILITY OF SUCH DAMAGE.
 147    *
 148    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 149    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/jaxb/JAXBModifier.html0000644000175000017500000042651410242117553022143 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 536   Methods: 27
NCLOC: 194   Classes: 2
 
 Source file Conditionals Statements Methods TOTAL
JAXBModifier.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.jaxb;
 9   
 10    import java.io.File;
 11    import java.io.FileInputStream;
 12    import java.io.FileNotFoundException;
 13    import java.io.FileOutputStream;
 14    import java.io.IOException;
 15    import java.io.InputStream;
 16    import java.io.InputStreamReader;
 17    import java.io.OutputStream;
 18    import java.io.Reader;
 19    import java.io.Writer;
 20    import java.net.URL;
 21    import java.nio.charset.Charset;
 22    import java.util.HashMap;
 23    import java.util.Iterator;
 24    import java.util.Map;
 25   
 26    import org.dom4j.Document;
 27    import org.dom4j.DocumentException;
 28    import org.dom4j.io.ElementModifier;
 29    import org.dom4j.io.OutputFormat;
 30    import org.dom4j.io.SAXModifier;
 31    import org.dom4j.io.XMLWriter;
 32   
 33    import org.xml.sax.InputSource;
 34   
 35    /**
 36    * Reads an XML document using SAX and writes its content to the provided
 37    * {@link org.dom4j.io.XMLWriter}. Modifications must be provided by {@link
 38    * org.dom4j.jaxb.JAXBObjectModifier} objects, which are called prior to writing
 39    * the XML fragment they are registered for.
 40    *
 41    * @author Wonne Keysers (Realsoftware.be)
 42    *
 43    * @see org.dom4j.io.SAXModifier
 44    */
 45    public class JAXBModifier extends JAXBSupport {
 46    private SAXModifier modifier;
 47   
 48    private XMLWriter xmlWriter;
 49   
 50    private boolean pruneElements;
 51   
 52    private OutputFormat outputFormat;
 53   
 54    private HashMap modifiers = new HashMap();
 55   
 56    /**
 57    * Creates a new JAXBModifier for the given JAXB context path. This is the
 58    * Java package where JAXB can find the generated XML classes. This package
 59    * MUST contain jaxb.properties!
 60    *
 61    * @param contextPath
 62    * JAXB context path to be used
 63    *
 64    * @see javax.xml.bind.JAXBContext
 65    */
 66  0 public JAXBModifier(String contextPath) {
 67  0 super(contextPath);
 68  0 this.outputFormat = new OutputFormat();
 69    }
 70   
 71    /**
 72    * Creates a new JAXBModifier for the given JAXB context path, using the
 73    * given {@link java.lang.ClassLoader}. This is the Java package where JAXB
 74    * can find the generated XML classes. This package MUST contain
 75    * jaxb.properties!
 76    *
 77    * @param contextPath
 78    * JAXB context path to be used
 79    * @param classloader
 80    * the classloader to use
 81    *
 82    * @see javax.xml.bind.JAXBContext
 83    */
 84  0 public JAXBModifier(String contextPath, ClassLoader classloader) {
 85  0 super(contextPath, classloader);
 86  0 this.outputFormat = new OutputFormat();
 87    }
 88   
 89    /**
 90    * Creates a new JAXBModifier for the given JAXB context path. The specified
 91    * {@link org.dom4j.io.OutputFormat}will be used while writing the XML
 92    * stream.
 93    *
 94    * @param contextPath
 95    * JAXB context path to be used
 96    * @param outputFormat
 97    * the DOM4J {@link org.dom4j.io.OutputFormat}to be used
 98    *
 99    * @see javax.xml.bind.JAXBContext
 100    */
 101  0 public JAXBModifier(String contextPath, OutputFormat outputFormat) {
 102  0 super(contextPath);
 103  0 this.outputFormat = outputFormat;
 104    }
 105   
 106    /**
 107    * Creates a new JAXBModifier for the given JAXB context path, using the
 108    * specified {@link java.lang.Classloader}. The specified {@link
 109    * org.dom4j.io.OutputFormat} will be used while writing the XML stream.
 110    *
 111    * @param contextPath
 112    * JAXB context path to be used
 113    * @param classloader
 114    * the class loader to be used to load JAXB
 115    * @param outputFormat
 116    * the DOM4J {@link org.dom4j.io.OutputFormat}to be used
 117    *
 118    * @see javax.xml.bind.JAXBContext
 119    */
 120  0 public JAXBModifier(String contextPath, ClassLoader classloader,
 121    OutputFormat outputFormat) {
 122  0 super(contextPath, classloader);
 123  0 this.outputFormat = outputFormat;
 124    }
 125   
 126    /**
 127    * Parses the specified {@link java.io.File}with SAX
 128    *
 129    * @param source
 130    * the file to parse
 131    *
 132    * @return the resulting DOM4J document
 133    *
 134    * @throws DocumentException
 135    * when an error occurs while parsing
 136    * @throws IOException
 137    * when an error occurs while writing to the {@link
 138    * org.dom4j.io.XMLWriter}
 139    */
 140  0 public Document modify(File source) throws DocumentException, IOException {
 141  0 return installModifier().modify(source);
 142    }
 143   
 144    /**
 145    * Parses the specified {@link java.io.File}with SAX, using the given
 146    * {@link java.nio.charset.Charset}.
 147    *
 148    * @param source
 149    * the file to parse
 150    * @param charset
 151    * the character set to use
 152    *
 153    * @return the resulting DOM4J document
 154    *
 155    * @throws DocumentException
 156    * when an error occurs while parsing
 157    * @throws IOException
 158    * when an error occurs while writing to the {@link
 159    * org.dom4j.io.XMLWriter}
 160    */
 161  0 public Document modify(File source, Charset charset)
 162    throws DocumentException, IOException {
 163  0 try {
 164  0 Reader reader = new InputStreamReader(new FileInputStream(source),
 165    charset);
 166   
 167  0 return installModifier().modify(reader);
 168    } catch (JAXBRuntimeException ex) {
 169  0 Throwable cause = ex.getCause();
 170  0 throw new DocumentException(cause.getMessage(), cause);
 171    } catch (FileNotFoundException ex) {
 172  0 throw new DocumentException(ex.getMessage(), ex);
 173    }
 174    }
 175   
 176    /**
 177    * Parses the specified {@link org.xml.sax.InputSource}with SAX.
 178    *
 179    * @param source
 180    * the input source to parse
 181    *
 182    * @return the resulting DOM4J document
 183    *
 184    * @throws DocumentException
 185    * when an error occurs while parsing
 186    * @throws IOException
 187    * when an error occurs while writing to the {@link
 188    * org.dom4j.io.XMLWriter}
 189    */
 190  0 public Document modify(InputSource source) throws DocumentException,
 191    IOException {
 192  0 try {
 193  0 return installModifier().modify(source);
 194    } catch (JAXBRuntimeException ex) {
 195  0 Throwable cause = ex.getCause();
 196  0 throw new DocumentException(cause.getMessage(), cause);
 197    }
 198    }
 199   
 200    /**
 201    * Parses the specified {@link java.io.InputStream}with SAX.
 202    *
 203    * @param source
 204    * the inputstream to parse
 205    *
 206    * @return the resulting DOM4J document
 207    *
 208    * @throws DocumentException
 209    * when an error occurs while parsing
 210    * @throws IOException
 211    * when an error occurs while writing to the {@link
 212    * org.dom4j.io.XMLWriter}
 213    */
 214  0 public Document modify(InputStream source) throws DocumentException,
 215    IOException {
 216  0 try {
 217  0 return installModifier().modify(source);
 218    } catch (JAXBRuntimeException ex) {
 219  0 Throwable cause = ex.getCause();
 220  0 throw new DocumentException(cause.getMessage(), cause);
 221    }
 222    }
 223   
 224    /**
 225    * Parses the specified {@link java.io.InputStream}with SAX.
 226    *
 227    * @param source
 228    * the inputstream to parse
 229    * @param systemId
 230    * the URI of the given inputstream
 231    *
 232    * @return the resulting DOM4J document
 233    *
 234    * @throws DocumentException
 235    * when an error occurs while parsing
 236    * @throws IOException
 237    * when an error occurs while writing to the {@link
 238    * org.dom4j.io.XMLWriter}
 239    */
 240  0 public Document modify(InputStream source, String systemId)
 241    throws DocumentException, IOException {
 242  0 try {
 243  0 return installModifier().modify(source);
 244    } catch (JAXBRuntimeException ex) {
 245  0 Throwable cause = ex.getCause();
 246  0 throw new DocumentException(cause.getMessage(), cause);
 247    }
 248    }
 249   
 250    /**
 251    * Parses the specified {@link java.io.Reader}with SAX.
 252    *
 253    * @param r
 254    * the reader to use for parsing
 255    *
 256    * @return the resulting DOM4J document
 257    *
 258    * @throws DocumentException
 259    * when an error occurs while parsing
 260    * @throws IOException
 261    * when an error occurs while writing to the {@link
 262    * org.dom4j.io.XMLWriter}
 263    */
 264  0 public Document modify(Reader r) throws DocumentException, IOException {
 265  0 try {
 266  0 return installModifier().modify(r);
 267    } catch (JAXBRuntimeException ex) {
 268  0 Throwable cause = ex.getCause();
 269  0 throw new DocumentException(cause.getMessage(), cause);
 270    }
 271    }
 272   
 273    /**
 274    * Parses the specified {@link java.io.Reader}with SAX.
 275    *
 276    * @param source
 277    * the reader to parse
 278    * @param systemId
 279    * the URI of the given reader
 280    *
 281    * @return the resulting DOM4J document
 282    *
 283    * @throws DocumentException
 284    * when an error occurs while parsing
 285    * @throws IOException
 286    * when an error occurs while writing to the {@link
 287    * org.dom4j.io.XMLWriter}
 288    */
 289  0 public Document modify(Reader source, String systemId)
 290    throws DocumentException, IOException {
 291  0 try {
 292  0 return installModifier().modify(source);
 293    } catch (JAXBRuntimeException ex) {
 294  0 Throwable cause = ex.getCause();
 295  0 throw new DocumentException(cause.getMessage(), cause);
 296    }
 297    }
 298   
 299    /**
 300    * Parses the the given URL or filename.
 301    *
 302    * @param url
 303    * the URL or filename to parse
 304    *
 305    * @return the resulting DOM4J document
 306    *
 307    * @throws DocumentException
 308    * when an error occurs while parsing
 309    * @throws IOException
 310    * when an error occurs while writing to the {@link
 311    * org.dom4j.io.XMLWriter}
 312    */
 313  0 public Document modify(String url) throws DocumentException, IOException {
 314  0 try {
 315  0 return installModifier().modify(url);
 316    } catch (JAXBRuntimeException ex) {
 317  0 Throwable cause = ex.getCause();
 318  0 throw new DocumentException(cause.getMessage(), cause);
 319    }
 320    }
 321   
 322    /**
 323    * Parses the the given URL.
 324    *
 325    * @param source
 326    * the URL to parse
 327    *
 328    * @return the resulting DOM4J document
 329    *
 330    * @throws DocumentException
 331    * when an error occurs while parsing
 332    * @throws IOException
 333    * when an error occurs while writing to the {@link
 334    * org.dom4j.io.XMLWriter}
 335    */
 336  0 public Document modify(URL source) throws DocumentException, IOException {
 337  0 try {
 338  0 return installModifier().modify(source);
 339    } catch (JAXBRuntimeException ex) {
 340  0 Throwable cause = ex.getCause();
 341  0 throw new DocumentException(cause.getMessage(), cause);
 342    }
 343    }
 344   
 345    /**
 346    * Sets the Output to write the (modified) xml document to.
 347    *
 348    * @param file
 349    * the {@link java.io.File}to write to
 350    *
 351    * @throws IOException
 352    * when the file cannot be found or when the outputformat
 353    */
 354  0 public void setOutput(File file) throws IOException {
 355  0 createXMLWriter().setOutputStream(new FileOutputStream(file));
 356    }
 357   
 358    /**
 359    * Sets the Output to write the (modified) xml document to.
 360    *
 361    * @param outputStream
 362    * the {@link java.io.OutputStream}to write to
 363    *
 364    * @throws IOException
 365    * when an error occurs
 366    */
 367  0 public void setOutput(OutputStream outputStream) throws IOException {
 368  0 createXMLWriter().setOutputStream(outputStream);
 369    }
 370   
 371    /**
 372    * Sets the Output to write the (modified) xml document to.
 373    *
 374    * @param writer
 375    * the {@link java.io.Writer}to write to
 376    *
 377    * @throws IOException
 378    * when an error occurs
 379    */
 380  0 public void setOutput(Writer writer) throws IOException {
 381  0 createXMLWriter().setWriter(writer);
 382    }
 383   
 384    /**
 385    * Adds the {@link JAXBObjectModifier}to be called when the specified xml
 386    * path is encounted while parsing the source.
 387    *
 388    * @param path
 389    * the element path to listen for
 390    * @param mod
 391    * the modifier to register
 392    */
 393  0 public void addObjectModifier(String path, JAXBObjectModifier mod) {
 394  0 modifiers.put(path, mod);
 395    }
 396   
 397    /**
 398    * Removes the {@link JAXBObjectModifier}from the event based processor,
 399    * for the specified element path.
 400    *
 401    * @param path
 402    * the xml path to remove the modifier for
 403    */
 404  0 public void removeObjectModifier(String path) {
 405  0 modifiers.remove(path);
 406  0 getModifier().removeModifier(path);
 407    }
 408   
 409    /**
 410    * Removes all registered {@link JAXBObjectModifier}instances from the
 411    * event based processor.
 412    */
 413  0 public void resetObjectModifiers() {
 414  0 modifiers.clear();
 415  0 getModifier().resetModifiers();
 416    }
 417   
 418    /**
 419    * Returns true when the modified {@link org.dom4j.Document}is not kept in
 420    * memory.
 421    *
 422    * @return Returns true if elements are pruned.
 423    */
 424  0 public boolean isPruneElements() {
 425  0 return pruneElements;
 426    }
 427   
 428    /**
 429    * Define whether the modified {@link org.dom4j.Document}must only be
 430    * written to the output and pruned from the DOM4J tree.
 431    *
 432    * @param pruneElements
 433    * When true, elements will not be kept in memory
 434    */
 435  0 public void setPruneElements(boolean pruneElements) {
 436  0 this.pruneElements = pruneElements;
 437    }
 438   
 439  0 private SAXModifier installModifier() throws IOException {
 440  0 modifier = new SAXModifier(isPruneElements());
 441   
 442  0 modifier.resetModifiers();
 443   
 444  0 Iterator modifierIt = modifiers.entrySet().iterator();
 445   
 446  0 while (modifierIt.hasNext()) {
 447  0 Map.Entry entry = (Map.Entry) modifierIt.next();
 448  0 ElementModifier mod = new JAXBElementModifier(this,
 449    (JAXBObjectModifier) entry.getValue());
 450  0 getModifier().addModifier((String) entry.getKey(), mod);
 451    }
 452   
 453  0 modifier.setXMLWriter(getXMLWriter());
 454   
 455  0 return modifier;
 456    }
 457   
 458  0 private SAXModifier getModifier() {
 459  0 if (this.modifier == null) {
 460  0 modifier = new SAXModifier(isPruneElements());
 461    }
 462   
 463  0 return modifier;
 464    }
 465   
 466  0 private XMLWriter getXMLWriter() {
 467  0 return xmlWriter;
 468    }
 469   
 470  0 private XMLWriter createXMLWriter() throws IOException {
 471  0 if (this.xmlWriter == null) {
 472  0 xmlWriter = new XMLWriter(outputFormat);
 473    }
 474   
 475  0 return xmlWriter;
 476    }
 477   
 478    private class JAXBElementModifier implements ElementModifier {
 479    private JAXBModifier jaxbModifier;
 480   
 481    private JAXBObjectModifier objectModifier;
 482   
 483  0 public JAXBElementModifier(JAXBModifier jaxbModifier,
 484    JAXBObjectModifier objectModifier) {
 485  0 this.jaxbModifier = jaxbModifier;
 486  0 this.objectModifier = objectModifier;
 487    }
 488   
 489  0 public org.dom4j.Element modifyElement(org.dom4j.Element element)
 490    throws Exception {
 491  0 javax.xml.bind.Element originalObject = jaxbModifier
 492    .unmarshal(element);
 493  0 javax.xml.bind.Element modifiedObject = objectModifier
 494    .modifyObject(originalObject);
 495   
 496  0 return jaxbModifier.marshal(modifiedObject);
 497    }
 498    }
 499    }
 500   
 501    /*
 502    * Redistribution and use of this software and associated documentation
 503    * ("Software"), with or without modification, are permitted provided that the
 504    * following conditions are met:
 505    *
 506    * 1. Redistributions of source code must retain copyright statements and
 507    * notices. Redistributions must also contain a copy of this document.
 508    *
 509    * 2. Redistributions in binary form must reproduce the above copyright notice,
 510    * this list of conditions and the following disclaimer in the documentation
 511    * and/or other materials provided with the distribution.
 512    *
 513    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 514    * from this Software without prior written permission of MetaStuff, Ltd. For
 515    * written permission, please contact dom4j-info@metastuff.com.
 516    *
 517    * 4. Products derived from this Software may not be called "DOM4J" nor may
 518    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 519    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 520    *
 521    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 522    *
 523    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 524    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 525    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 526    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 527    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 528    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 529    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 530    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 531    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 532    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 533    * POSSIBILITY OF SUCH DAMAGE.
 534    *
 535    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 536    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/jaxb/JAXBWriter.html0000644000175000017500000025073610242117712021657 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 326   Methods: 17
NCLOC: 80   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
JAXBWriter.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.jaxb;
 9   
 10    import java.io.File;
 11    import java.io.FileOutputStream;
 12    import java.io.IOException;
 13    import java.io.OutputStream;
 14    import java.io.Writer;
 15   
 16    import javax.xml.bind.JAXBException;
 17   
 18    import org.dom4j.Element;
 19    import org.dom4j.io.OutputFormat;
 20    import org.dom4j.io.XMLWriter;
 21   
 22    import org.xml.sax.SAXException;
 23   
 24    /**
 25    * Writes {@link javax.xml.bind.Element}objects to an XML stream. {@link
 26    * javax.xml.bind.Element} instances can be created using the ObjectFactory that
 27    * is generated by the JAXB compiler.
 28    *
 29    * @author Wonne Keysers (Realsoftware.be)
 30    *
 31    * @see org.dom4j.io.XMLWriter
 32    * @see javax.xml.bind.JAXBContext
 33    */
 34    public class JAXBWriter extends JAXBSupport {
 35    private XMLWriter xmlWriter;
 36   
 37    private OutputFormat outputFormat;
 38   
 39    /**
 40    * Creates a new JAXBWriter for the given JAXB context path. This is the
 41    * Java package where JAXB can find the generated XML classes. This package
 42    * MUST contain jaxb.properties!
 43    *
 44    * @param contextPath
 45    * JAXB context path to be used
 46    *
 47    * @see javax.xml.bind.JAXBContext
 48    */
 49  0 public JAXBWriter(String contextPath) {
 50  0 super(contextPath);
 51  0 outputFormat = new OutputFormat();
 52    }
 53   
 54    /**
 55    * Creates a new JAXBWriter for the given JAXB context path. The specied
 56    * {@link org.dom4j.io.OutputFormat}will be used for writing the XML
 57    * stream.
 58    *
 59    * @param contextPath
 60    * JAXB context path to be used
 61    * @param outputFormat
 62    * the DOM4J {@link org.dom4j.io.OutputFormat}to be used
 63    *
 64    * @see javax.xml.bind.JAXBContext
 65    */
 66  0 public JAXBWriter(String contextPath, OutputFormat outputFormat) {
 67  0 super(contextPath);
 68  0 this.outputFormat = outputFormat;
 69    }
 70   
 71    /**
 72    * Creates a new JAXBWriter for the given JAXB context path, using the
 73    * specified {@link java.lang.Classloader}. (This is the Java package where
 74    * JAXB can find the generated XML classes. This package MUST contain
 75    * jaxb.properties!)
 76    *
 77    * @param contextPath
 78    * JAXB context path to be used
 79    * @param classloader
 80    * the classloader to be used for loading JAXB
 81    *
 82    * @see javax.xml.bind.JAXBContext
 83    */
 84  0 public JAXBWriter(String contextPath, ClassLoader classloader) {
 85  0 super(contextPath, classloader);
 86    }
 87   
 88    /**
 89    * Creates a new JAXBWriter for the given JAXB context path, using the
 90    * specified {@link java.lang.Classloader}. The specied {@link
 91    * org.dom4j.io.OutputFormat} will be used while writing the XML stream.
 92    *
 93    * @param contextPath
 94    * JAXB context path to be used
 95    * @param classloader
 96    * the class loader to be used to load JAXB
 97    * @param outputFormat
 98    * the DOM4J {@link org.dom4j.io.OutputFormat}to be used
 99    *
 100    * @see javax.xml.bind.JAXBContext
 101    */
 102  0 public JAXBWriter(String contextPath, ClassLoader classloader,
 103    OutputFormat outputFormat) {
 104  0 super(contextPath, classloader);
 105  0 this.outputFormat = outputFormat;
 106    }
 107   
 108    /**
 109    * Returns the OutputFormat that will be used when writing the XML stream.
 110    *
 111    * @return Returns the output format.
 112    */
 113  0 public OutputFormat getOutputFormat() {
 114  0 return outputFormat;
 115    }
 116   
 117    /**
 118    * Defines to write the resulting output to the specified {@link
 119    * java.io.File}.
 120    *
 121    * @param file
 122    * file to write to
 123    *
 124    * @throws IOException
 125    * when the file cannot be found
 126    */
 127  0 public void setOutput(File file) throws IOException {
 128  0 getWriter().setOutputStream(new FileOutputStream(file));
 129    }
 130   
 131    /**
 132    * Defines to write the resulting output to the specified {@link
 133    * java.io.OutputStream}
 134    *
 135    * @param outputStream
 136    * outputStream to write to.
 137    *
 138    * @throws IOException
 139    * DOCUMENT ME!
 140    */
 141  0 public void setOutput(OutputStream outputStream) throws IOException {
 142  0 getWriter().setOutputStream(outputStream);
 143    }
 144   
 145    /**
 146    * Defines to write the resulting output to the specified {@link Writer}.
 147    *
 148    * @param writer
 149    * writer to write to
 150    *
 151    * @throws IOException
 152    */
 153  0 public void setOutput(Writer writer) throws IOException {
 154  0 getWriter().setWriter(writer);
 155    }
 156   
 157    /**
 158    * Start a document by writing the initial XML declaration to the output.
 159    * This must be done prior to writing any other elements.
 160    *
 161    * @throws IOException
 162    * if an error occured while writing the output
 163    * @throws SAXException
 164    * thrown by the underlying SAX driver
 165    */
 166  0 public void startDocument() throws IOException, SAXException {
 167  0 getWriter().startDocument();
 168    }
 169   
 170    /**
 171    * Stop writing the document to the output. This must be done when all other
 172    * elements are finished.
 173    *
 174    * @throws IOException
 175    * if an error occured while writing the output
 176    * @throws SAXException
 177    * thrown by the underlying SAX driver
 178    */
 179  0 public void endDocument() throws IOException, SAXException {
 180  0 getWriter().endDocument();
 181    }
 182   
 183    /**
 184    * Writes the specified {@link javax.xml.bind.Element}to the document.
 185    * {@link javax.xml.bind.Element}instances can be created using the
 186    * ObjectFactory that is generated by the JAXB compiler.
 187    *
 188    * @param jaxbObject
 189    *
 190    * @throws IOException
 191    * if an error occured while writing the output
 192    * @throws JAXBException
 193    * when an error occured while marshalling the jaxbObject
 194    */
 195  0 public void write(javax.xml.bind.Element jaxbObject) throws IOException,
 196    JAXBException {
 197  0 getWriter().write(marshal(jaxbObject));
 198    }
 199   
 200    /**
 201    * Writes the closing tag of the specified {@link javax.xml.bind.Element}to
 202    * the document. This method can be used for writing {@link
 203    * javax.xml.bind.Element} instances can be created using the ObjectFactory
 204    * that is generated by the JAXB compiler.
 205    *
 206    * @param jaxbObject
 207    * the JAXB element to write
 208    *
 209    * @throws IOException
 210    * if an error occured while writing the output
 211    * @throws JAXBException
 212    * when an error occured while marshalling the jaxbObject
 213    */
 214  0 public void writeClose(javax.xml.bind.Element jaxbObject)
 215    throws IOException, JAXBException {
 216  0 getWriter().writeClose(marshal(jaxbObject));
 217    }
 218   
 219    /**
 220    * Writes the opening tag of the specified {@link javax.xml.bind.Element}to
 221    * the document. {@link javax.xml.bind.Element}instances can be created
 222    * using the ObjectFactory that is generated by the JAXB compiler.
 223    *
 224    * @param jaxbObject
 225    * the JAXB element to write
 226    *
 227    * @throws IOException
 228    * if an error occured while writing the output
 229    * @throws JAXBException
 230    * when an error occured while marshalling the jaxbObject
 231    */
 232  0 public void writeOpen(javax.xml.bind.Element jaxbObject)
 233    throws IOException, JAXBException {
 234  0 getWriter().writeOpen(marshal(jaxbObject));
 235    }
 236   
 237    /**
 238    * Writes the specified {@link org.dom4j.Element}to the document.
 239    *
 240    * @param element
 241    * the {@link org.dom4j.Element}to write
 242    *
 243    * @throws IOException
 244    * if an error occured while writing the output
 245    */
 246  0 public void writeElement(Element element) throws IOException {
 247  0 getWriter().write(element);
 248    }
 249   
 250    /**
 251    * Writes the closing tag of the specified {@link org.dom4j.Element}to the
 252    * document.
 253    *
 254    * @param element
 255    * the {@link org.dom4j.Element}to write
 256    *
 257    * @throws IOException
 258    * if an error occured while writing the output
 259    */
 260  0 public void writeCloseElement(Element element) throws IOException {
 261  0 getWriter().writeClose(element);
 262    }
 263   
 264    /**
 265    * Writes the opening tag of the specified {@link org.dom4j.Element}to the
 266    * document.
 267    *
 268    * @param element
 269    * the {@link org.dom4j.Element}to write
 270    *
 271    * @throws IOException
 272    * if an error occured while writing the output
 273    */
 274  0 public void writeOpenElement(Element element) throws IOException {
 275  0 getWriter().writeOpen(element);
 276    }
 277   
 278  0 private XMLWriter getWriter() throws IOException {
 279  0 if (xmlWriter == null) {
 280  0 if (this.outputFormat != null) {
 281  0 xmlWriter = new XMLWriter(outputFormat);
 282    } else {
 283  0 xmlWriter = new XMLWriter();
 284    }
 285    }
 286   
 287  0 return xmlWriter;
 288    }
 289    }
 290   
 291    /*
 292    * Redistribution and use of this software and associated documentation
 293    * ("Software"), with or without modification, are permitted provided that the
 294    * following conditions are met:
 295    *
 296    * 1. Redistributions of source code must retain copyright statements and
 297    * notices. Redistributions must also contain a copy of this document.
 298    *
 299    * 2. Redistributions in binary form must reproduce the above copyright notice,
 300    * this list of conditions and the following disclaimer in the documentation
 301    * and/or other materials provided with the distribution.
 302    *
 303    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 304    * from this Software without prior written permission of MetaStuff, Ltd. For
 305    * written permission, please contact dom4j-info@metastuff.com.
 306    *
 307    * 4. Products derived from this Software may not be called "DOM4J" nor may
 308    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 309    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 310    *
 311    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 312    *
 313    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 314    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 315    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 316    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 317    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 318    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 319    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 320    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 321    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 322    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 323    * POSSIBILITY OF SUCH DAMAGE.
 324    *
 325    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 326    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/jaxb/JAXBObjectModifier.html0000644000175000017500000005242310242117706023264 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 73   Methods: 0
NCLOC: 5   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
JAXBObjectModifier.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.jaxb;
 9   
 10    import javax.xml.bind.Element;
 11   
 12    /**
 13    * JAXBObjectHandler implementations can be registered with the {@link
 14    * JAXBModifier} in order to change unmarshalled XML fragments.
 15    *
 16    * @author Wonne Keysers (Realsoftware.be)
 17    */
 18    public interface JAXBObjectModifier {
 19    /**
 20    * Called when the {@link JAXBModifier}has finished parsing the xml path
 21    * the handler was registered for. The provided object is the unmarshalled
 22    * representation of the XML fragment. It can be casted to the appropriate
 23    * implementation class that is generated by the JAXB compiler. <br>
 24    * The modified JAXB element that returns from this method will be
 25    * marshalled by the {@link JAXBModifier}and put in the DOM4J tree.
 26    *
 27    * @param jaxbElement
 28    * the JAXB object to be modified
 29    *
 30    * @return the modified JAXB object, or null when it must be removed.
 31    *
 32    * @throws Exception
 33    * possibly thrown by the implementation.
 34    */
 35    Element modifyObject(Element jaxbElement) throws Exception;
 36    }
 37   
 38    /*
 39    * Redistribution and use of this software and associated documentation
 40    * ("Software"), with or without modification, are permitted provided that the
 41    * following conditions are met:
 42    *
 43    * 1. Redistributions of source code must retain copyright statements and
 44    * notices. Redistributions must also contain a copy of this document.
 45    *
 46    * 2. Redistributions in binary form must reproduce the above copyright notice,
 47    * this list of conditions and the following disclaimer in the documentation
 48    * and/or other materials provided with the distribution.
 49    *
 50    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 51    * from this Software without prior written permission of MetaStuff, Ltd. For
 52    * written permission, please contact dom4j-info@metastuff.com.
 53    *
 54    * 4. Products derived from this Software may not be called "DOM4J" nor may
 55    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 56    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 57    *
 58    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 59    *
 60    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 61    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 62    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 63    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 64    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 65    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 66    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 67    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 68    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 69    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 70    * POSSIBILITY OF SUCH DAMAGE.
 71    *
 72    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 73    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/jaxb/JAXBRuntimeException.html0000644000175000017500000004611410242117716023702 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 64   Methods: 1
NCLOC: 6   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
JAXBRuntimeException.java - 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.jaxb;
 9   
 10    /**
 11    * Exception internally thrown by the JAXBReader classes. This is a
 12    * RuntimeException since the {@link org.dom4j.ElementHandler}methods do not
 13    * throw Exceptions.
 14    *
 15    * @author Wonne Keysers (Realsoftware.be)
 16    */
 17    class JAXBRuntimeException extends RuntimeException {
 18    /**
 19    * DOCUMENT ME!
 20    *
 21    * @param cause
 22    * The causing {@link java.lang.Throwable}
 23    */
 24  0 protected JAXBRuntimeException(Throwable cause) {
 25  0 super(cause);
 26    }
 27    }
 28   
 29    /*
 30    * Redistribution and use of this software and associated documentation
 31    * ("Software"), with or without modification, are permitted provided that the
 32    * following conditions are met:
 33    *
 34    * 1. Redistributions of source code must retain copyright statements and
 35    * notices. Redistributions must also contain a copy of this document.
 36    *
 37    * 2. Redistributions in binary form must reproduce the above copyright notice,
 38    * this list of conditions and the following disclaimer in the documentation
 39    * and/or other materials provided with the distribution.
 40    *
 41    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 42    * from this Software without prior written permission of MetaStuff, Ltd. For
 43    * written permission, please contact dom4j-info@metastuff.com.
 44    *
 45    * 4. Products derived from this Software may not be called "DOM4J" nor may
 46    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 47    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 48    *
 49    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 50    *
 51    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 52    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 53    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 54    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 55    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 56    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 57    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 58    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 59    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 60    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 61    * POSSIBILITY OF SUCH DAMAGE.
 62    *
 63    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 64    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/Node.html0000644000175000017500000044013210242117721017666 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 599   Methods: 0
NCLOC: 53   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
Node.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    import java.io.IOException;
 11    import java.io.Writer;
 12    import java.util.List;
 13   
 14    /**
 15    * <p>
 16    * <code>Node</code> defines the polymorphic behavior for all XML nodes in a
 17    * dom4j tree.
 18    * </p>
 19    *
 20    * <p>
 21    * A node can be output as its XML format, can be detached from its position in
 22    * a document and can have XPath expressions evaluated on itself.
 23    * </p>
 24    *
 25    * <p>
 26    * A node may optionally support the parent relationship and may be read only.
 27    * </p>
 28    *
 29    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 30    * @version $Revision: 1.31 $
 31    *
 32    * @see #supportsParent
 33    * @see #isReadOnly
 34    */
 35    public interface Node extends Cloneable {
 36    // W3C DOM complient node type codes
 37   
 38    /** Matches Element nodes */
 39    short ANY_NODE = 0;
 40   
 41    /** Matches Element nodes */
 42    short ELEMENT_NODE = 1;
 43   
 44    /** Matches elements nodes */
 45    short ATTRIBUTE_NODE = 2;
 46   
 47    /** Matches elements nodes */
 48    short TEXT_NODE = 3;
 49   
 50    /** Matches elements nodes */
 51    short CDATA_SECTION_NODE = 4;
 52   
 53    /** Matches elements nodes */
 54    short ENTITY_REFERENCE_NODE = 5;
 55   
 56    /** Matches elements nodes */
 57   
 58    // public static final short ENTITY_NODE = 6;
 59    /** Matches ProcessingInstruction */
 60    short PROCESSING_INSTRUCTION_NODE = 7;
 61   
 62    /** Matches Comments nodes */
 63    short COMMENT_NODE = 8;
 64   
 65    /** Matches Document nodes */
 66    short DOCUMENT_NODE = 9;
 67   
 68    /** Matches DocumentType nodes */
 69    short DOCUMENT_TYPE_NODE = 10;
 70   
 71    // public static final short DOCUMENT_FRAGMENT_NODE = 11;
 72    // public static final short NOTATION_NODE = 12;
 73   
 74    /** Matchs a Namespace Node - NOTE this differs from DOM */
 75   
 76    // XXXX: ????
 77    short NAMESPACE_NODE = 13;
 78   
 79    /** Does not match any valid node */
 80    short UNKNOWN_NODE = 14;
 81   
 82    /** The maximum number of node types for sizing purposes */
 83    short MAX_NODE_TYPE = 14;
 84   
 85    /**
 86    * <p>
 87    * <code>supportsParent</code> returns true if this node supports the
 88    * parent relationship.
 89    * </p>
 90    *
 91    * <p>
 92    * Some XML tree implementations are singly linked and only support downward
 93    * navigation through children relationships. The default case is that both
 94    * parent and children relationships are supported though for memory and
 95    * performance reasons the parent relationship may not be supported.
 96    * </p>
 97    *
 98    * @return true if this node supports the parent relationship or false it is
 99    * not supported
 100    */
 101    boolean supportsParent();
 102   
 103    /**
 104    * <p>
 105    * <code>getParent</code> returns the parent <code>Element</code> if
 106    * this node supports the parent relationship or null if it is the root
 107    * element or does not support the parent relationship.
 108    * </p>
 109    *
 110    * <p>
 111    * This method is an optional feature and may not be supported for all
 112    * <code>Node</code> implementations.
 113    * </p>
 114    *
 115    * @return the parent of this node or null if it is the root of the tree or
 116    * the parent relationship is not supported.
 117    */
 118    Element getParent();
 119   
 120    /**
 121    * <p>
 122    * <code>setParent</code> sets the parent relationship of this node if the
 123    * parent relationship is supported or does nothing if the parent
 124    * relationship is not supported.
 125    * </p>
 126    *
 127    * <p>
 128    * This method should only be called from inside an <code>Element</code>
 129    * implementation method and is not intended for general use.
 130    * </p>
 131    *
 132    * @param parent
 133    * is the new parent of this node.
 134    */
 135    void setParent(Element parent);
 136   
 137    /**
 138    * <p>
 139    * <code>getDocument</code> returns the <code>Document</code> that this
 140    * <code>Node</code> is part of if this node supports the parent
 141    * relationship.
 142    * </p>
 143    *
 144    * <p>
 145    * This method is an optional feature and may not be supported for all
 146    * <code>Node</code> implementations.
 147    * </p>
 148    *
 149    * @return the document of this node or null if this feature is not
 150    * supported or the node is not associated with a
 151    * <code>Document</code>
 152    */
 153    Document getDocument();
 154   
 155    /**
 156    * <p>
 157    * <code>setDocument</code> sets the document of this node if the parent
 158    * relationship is supported or does nothing if the parent relationship is
 159    * not supported.
 160    * </p>
 161    *
 162    * <p>
 163    * This method should only be called from inside a <code>Document</code>
 164    * implementation method and is not intended for general use.
 165    * </p>
 166    *
 167    * @param document
 168    * is the new document of this node.
 169    */
 170    void setDocument(Document document);
 171   
 172    /**
 173    * <p>
 174    * <code>isReadOnly</code> returns true if this node is read only and
 175    * cannot be modified. Any attempt to modify a read-only <code>Node</code>
 176    * will result in an <code>UnsupportedOperationException</code> being
 177    * thrown.
 178    * </p>
 179    *
 180    * @return true if this <code>Node</code> is read only and cannot be
 181    * modified otherwise false.
 182    */
 183    boolean isReadOnly();
 184   
 185    /**
 186    * <p>
 187    * <code>hasContent</code> returns true if this node is a Branch (either
 188    * an Element or a Document) and it contains at least one content node such
 189    * as a child Element or Text node.
 190    * </p>
 191    *
 192    * @return true if this <code>Node</code> is a Branch with a nodeCount()
 193    * of one or more.
 194    */
 195    boolean hasContent();
 196   
 197    /**
 198    * <p>
 199    * <code>getName</code> returns the name of this node. This is the XML
 200    * local name of the element, attribute, entity or processing instruction.
 201    * For CDATA and Text nodes this method will return null.
 202    * </p>
 203    *
 204    * @return the XML name of this node
 205    */
 206    String getName();
 207   
 208    /**
 209    * <p>
 210    * Sets the text data of this node or this method will throw an
 211    * <code>UnsupportedOperationException</code> if it is read-only.
 212    * </p>
 213    *
 214    * @param name
 215    * is the new name of this node
 216    */
 217    void setName(String name);
 218   
 219    /**
 220    * <p>
 221    * Returns the text of this node.
 222    * </p>
 223    *
 224    * @return the text for this node.
 225    */
 226    String getText();
 227   
 228    /**
 229    * <p>
 230    * Sets the text data of this node or this method will throw an
 231    * <code>UnsupportedOperationException</code> if it is read-only.
 232    * </p>
 233    *
 234    * @param text
 235    * is the new textual value of this node
 236    */
 237    void setText(String text);
 238   
 239    /**
 240    * Returns the XPath string-value of this node. The behaviour of this method
 241    * is defined in the <a href="http://www.w3.org/TR/xpath">XPath
 242    * specification </a>.
 243    *
 244    * @return the text from all the child Text and Element nodes appended
 245    * together.
 246    */
 247    String getStringValue();
 248   
 249    /**
 250    * <p>
 251    * Returns the XPath expression which will return a node set containing the
 252    * given node such as /a/b/&#64;c. No indexing will be used to restrict the
 253    * path if multiple elements with the same name occur on the path.
 254    * </p>
 255    *
 256    * @return the XPath expression which will return a nodeset containing at
 257    * least this node.
 258    */
 259    String getPath();
 260   
 261    /**
 262    * Returns the relative XPath expression which will return a node set
 263    * containing the given node such as a/b/&#64;c. No indexing will be used to
 264    * restrict the path if multiple elements with the same name occur on the
 265    * path.
 266    *
 267    * @param context
 268    * is the parent context from which the relative path should
 269    * start. If the context is null or the context is not an
 270    * ancestor of this node then the path will be absolute and start
 271    * from the document and so begin with the '/' character.
 272    *
 273    * @return the XPath expression relative to the given context which will
 274    * return a nodeset containing at least this node.
 275    */
 276    String getPath(Element context);
 277   
 278    /**
 279    * <p>
 280    * Returns the XPath expression which will return a nodeset of one node
 281    * which is the current node. This method will use the XPath index operator
 282    * to restrict the path if multiple elements with the same name occur on the
 283    * path.
 284    * </p>
 285    *
 286    * @return the XPath expression which will return a nodeset containing just
 287    * this node.
 288    */
 289    String getUniquePath();
 290   
 291    /**
 292    * <p>
 293    * Returns the relative unique XPath expression from the given context which
 294    * will return a nodeset of one node which is the current node. This method
 295    * will use the XPath index operator to restrict the path if multiple
 296    * elements with the same name occur on the path.
 297    * </p>
 298    *
 299    * @param context
 300    * is the parent context from which the path should start. If the
 301    * context is null or the context is not an ancestor of this node
 302    * then the path will start from the document and so begin with
 303    * the '/' character.
 304    *
 305    * @return the XPath expression relative to the given context which will
 306    * return a nodeset containing just this node.
 307    */
 308    String getUniquePath(Element context);
 309   
 310    /**
 311    * <p>
 312    * <code>asXML</code> returns the textual XML representation of this node.
 313    * </p>
 314    *
 315    * @return the XML representation of this node
 316    */
 317    String asXML();
 318   
 319    /**
 320    * <p>
 321    * <code>write</code> writes this node as the default XML notation for
 322    * this node. If you wish to control the XML output (such as for pretty
 323    * printing, changing the indentation policy etc.) then please use {@link
 324    * org.dom4j.io.XMLWriter} or its derivations.
 325    * </p>
 326    *
 327    * @param writer
 328    * is the <code>Writer</code> to output the XML to
 329    *
 330    * @throws IOException
 331    * DOCUMENT ME!
 332    */
 333    void write(Writer writer) throws IOException;
 334   
 335    /**
 336    * Returns the code according to the type of node. This makes processing
 337    * nodes polymorphically much easier as the switch statement can be used
 338    * instead of multiple if (instanceof) statements.
 339    *
 340    * @return a W3C DOM complient code for the node type such as ELEMENT_NODE
 341    * or ATTRIBUTE_NODE
 342    */
 343    short getNodeType();
 344   
 345    /**
 346    * DOCUMENT ME!
 347    *
 348    * @return the name of the type of node such as "Document", "Element",
 349    * "Attribute" or "Text"
 350    */
 351    String getNodeTypeName();
 352   
 353    /**
 354    * <p>
 355    * Removes this node from its parent if there is one. If this node is the
 356    * root element of a document then it is removed from the document as well.
 357    * </p>
 358    *
 359    * <p>
 360    * This method is useful if you want to remove a node from its source
 361    * document and add it to another document. For example
 362    * </p>
 363    * <code> Node node = ...; Element someOtherElement = ...;
 364    * someOtherElement.add( node.detach() ); </code>
 365    *
 366    * @return the node that has been removed from its parent node if any and
 367    * its document if any.
 368    */
 369    Node detach();
 370   
 371    /**
 372    * <p>
 373    * <code>selectNodes</code> evaluates an XPath expression and returns the
 374    * result as a <code>List</code> of <code>Node</code> instances or
 375    * <code>String</code> instances depending on the XPath expression.
 376    * </p>
 377    *
 378    * @param xpathExpression
 379    * is the XPath expression to be evaluated
 380    *
 381    * @return the list of <code>Node</code> or <code>String</code>
 382    * instances depending on the XPath expression
 383    */
 384    List selectNodes(String xpathExpression);
 385   
 386    /**
 387    * <p>
 388    * <code>selectObject</code> evaluates an XPath expression and returns the
 389    * result as an {@link Object}. The object returned can either be a {@link
 390    * List} of one or more {@link Node}instances or a scalar object like a
 391    * {@link String}or a {@link Number}instance depending on the XPath
 392    * expression.
 393    * </p>
 394    *
 395    * @param xpathExpression
 396    * is the XPath expression to be evaluated
 397    *
 398    * @return the value of the XPath expression as a {@link List}of {@link
 399    * Node} instances, a {@link String}or a {@link Number}instance
 400    * depending on the XPath expression.
 401    */
 402    Object selectObject(String xpathExpression);
 403   
 404    /**
 405    * <p>
 406    * <code>selectNodes</code> evaluates an XPath expression then sorts the
 407    * results using a secondary XPath expression Returns a sorted
 408    * <code>List</code> of <code>Node</code> instances.
 409    * </p>
 410    *
 411    * @param xpathExpression
 412    * is the XPath expression to be evaluated
 413    * @param comparisonXPathExpression
 414    * is the XPath expression used to compare the results by for
 415    * sorting
 416    *
 417    * @return the list of <code>Node</code> instances sorted by the
 418    * comparisonXPathExpression
 419    */
 420    List selectNodes(String xpathExpression, String comparisonXPathExpression);
 421   
 422    /**
 423    * <p>
 424    * <code>selectNodes</code> evaluates an XPath expression then sorts the
 425    * results using a secondary XPath expression Returns a sorted
 426    * <code>List</code> of <code>Node</code> instances.
 427    * </p>
 428    *
 429    * @param xpathExpression
 430    * is the XPath expression to be evaluated
 431    * @param comparisonXPathExpression
 432    * is the XPath expression used to compare the results by for
 433    * sorting
 434    * @param removeDuplicates
 435    * if this parameter is true then duplicate values (using the
 436    * comparisonXPathExpression) are removed from the result List.
 437    *
 438    * @return the list of <code>Node</code> instances sorted by the
 439    * comparisonXPathExpression
 440    */
 441    List selectNodes(String xpathExpression, String comparisonXPathExpression,
 442    boolean removeDuplicates);
 443   
 444    /**
 445    * <p>
 446    * <code>selectSingleNode</code> evaluates an XPath expression and returns
 447    * the result as a single <code>Node</code> instance.
 448    * </p>
 449    *
 450    * @param xpathExpression
 451    * is the XPath expression to be evaluated
 452    *
 453    * @return the <code>Node</code> matching the XPath expression
 454    */
 455    Node selectSingleNode(String xpathExpression);
 456   
 457    /**
 458    * <p>
 459    * <code>valueOf</code> evaluates an XPath expression and returns the
 460    * textual representation of the results the XPath string-value of this
 461    * node. The string-value for a given node type is defined in the <a
 462    * href="http://www.w3.org/TR/xpath">XPath specification </a>.
 463    * </p>
 464    *
 465    * @param xpathExpression
 466    * is the XPath expression to be evaluated
 467    *
 468    * @return the string-value representation of the results of the XPath
 469    * expression
 470    */
 471    String valueOf(String xpathExpression);
 472   
 473    /**
 474    * <p>
 475    * <code>numberValueOf</code> evaluates an XPath expression and returns
 476    * the numeric value of the XPath expression if the XPath expression results
 477    * in a number, or null if the result is not a number.
 478    * </p>
 479    *
 480    * @param xpathExpression
 481    * is the XPath expression to be evaluated
 482    *
 483    * @return the numeric result of the XPath expression or null if the result
 484    * is not a number.
 485    */
 486    Number numberValueOf(String xpathExpression);
 487   
 488    /**
 489    * <p>
 490    * <code>matches</code> returns true if evaluating the given XPath
 491    * expression on this node returns a non-empty node set containing this
 492    * node.
 493    * </p>
 494    *
 495    * <p>
 496    * This method does not behave like the &lt;xsl:if&gt; element - if you want
 497    * that behaviour, to evaluate if an XPath expression matches something,
 498    * then you can use the following code to be equivalent...
 499    * </p>
 500    * <code>if ( node.selectSingleNode( "/some/path" ) != nulll )</code>
 501    *
 502    * @param xpathExpression
 503    * is an XPath expression
 504    *
 505    * @return true if this node is returned by the given XPath expression
 506    */
 507    boolean matches(String xpathExpression);
 508   
 509    /**
 510    * <p>
 511    * <code>createXPath</code> creates an XPath object for the given
 512    * xpathExpression. The XPath object allows the variable context to be
 513    * specified.
 514    * </p>
 515    *
 516    * @param xpathExpression
 517    * is the XPath expression to be evaluated
 518    *
 519    * @return an XPath object represeting the given expression
 520    *
 521    * @throws InvalidXPathException
 522    * if the XPath expression is invalid
 523    */
 524    XPath createXPath(String xpathExpression) throws InvalidXPathException;
 525   
 526    /**
 527    * <p>
 528    * <code>asXPathResult</code> returns a version of this node which is
 529    * capable of being an XPath result. The result of an XPath expression
 530    * should always support the parent relationship, whether the original XML
 531    * tree was singly or doubly linked. If the node does not support the parent
 532    * relationship then a new node will be created which is linked to its
 533    * parent and returned.
 534    * </p>
 535    *
 536    * @param parent
 537    * DOCUMENT ME!
 538    *
 539    * @return a <code>Node</code> which supports the parent relationship
 540    */
 541    Node asXPathResult(Element parent);
 542   
 543    /**
 544    * <p>
 545    * <code>accept</code> is the method used in the Visitor Pattern.
 546    * </p>
 547    *
 548    * @param visitor
 549    * is the visitor in the Visitor Pattern
 550    */
 551    void accept(Visitor visitor);
 552   
 553    /**
 554    * <p>
 555    * <code>clone</code> will return a deep clone or if this node is
 556    * read-only then clone will return the same instance.
 557    * </p>
 558    *
 559    * @return a deep clone of myself or myself if I am read only.
 560    */
 561    Object clone();
 562    }
 563   
 564    /*
 565    * Redistribution and use of this software and associated documentation
 566    * ("Software"), with or without modification, are permitted provided that the
 567    * following conditions are met:
 568    *
 569    * 1. Redistributions of source code must retain copyright statements and
 570    * notices. Redistributions must also contain a copy of this document.
 571    *
 572    * 2. Redistributions in binary form must reproduce the above copyright notice,
 573    * this list of conditions and the following disclaimer in the documentation
 574    * and/or other materials provided with the distribution.
 575    *
 576    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 577    * from this Software without prior written permission of MetaStuff, Ltd. For
 578    * written permission, please contact dom4j-info@metastuff.com.
 579    *
 580    * 4. Products derived from this Software may not be called "DOM4J" nor may
 581    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 582    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 583    *
 584    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 585    *
 586    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 587    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 588    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 589    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 590    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 591    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 592    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 593    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 594    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 595    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 596    * POSSIBILITY OF SUCH DAMAGE.
 597    *
 598    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 599    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dom/0000755000175000017500000000000012133227266016675 5ustar ebourgebourgdom4j-1.6.1/docs/clover/org/dom4j/dom/pkg-classes.html0000644000175000017500000000522310242117743021776 0ustar ebourgebourg dom4j - 1.6.1 org.dom4j.dom
Classes
DOMAttribute (2,9%)
DOMAttributeNodeMap (10,5%)
DOMCDATA (0%)
DOMComment (2,7%)
DOMDocument (22,7%)
DOMDocumentFactory (41,8%)
DOMDocumentType (0%)
DOMElement (24,1%)
DOMEntityReference (0%)
DOMNamespace (3,8%)
DOMNodeHelper (15,1%)
DOMNodeHelper.EmptyNodeList (0%)
DOMProcessingInstruction (2,9%)
DOMText (6%)
dom4j-1.6.1/docs/clover/org/dom4j/dom/DOMText.html0000644000175000017500000022441610242117744021056 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 264   Methods: 38
NCLOC: 154   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DOMText.java 0% 5,6% 7,9% 6%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dom;
 9   
 10    import org.dom4j.Element;
 11    import org.dom4j.Text;
 12    import org.dom4j.tree.DefaultText;
 13   
 14    import org.w3c.dom.DOMException;
 15    import org.w3c.dom.Document;
 16    import org.w3c.dom.NamedNodeMap;
 17    import org.w3c.dom.NodeList;
 18   
 19    /**
 20    * <p>
 21    * <code>DOMText</code> implements a Text node which supports the W3C DOM API.
 22    * </p>
 23    *
 24    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 25    * @version $Revision: 1.12 $
 26    */
 27    public class DOMText extends DefaultText implements org.w3c.dom.Text {
 28  307 public DOMText(String text) {
 29  307 super(text);
 30    }
 31   
 32  0 public DOMText(Element parent, String text) {
 33  0 super(parent, text);
 34    }
 35   
 36    // org.w3c.dom.Node interface
 37    // -------------------------------------------------------------------------
 38  0 public boolean supports(String feature, String version) {
 39  0 return DOMNodeHelper.supports(this, feature, version);
 40    }
 41   
 42  0 public String getNamespaceURI() {
 43  0 return DOMNodeHelper.getNamespaceURI(this);
 44    }
 45   
 46  0 public String getPrefix() {
 47  0 return DOMNodeHelper.getPrefix(this);
 48    }
 49   
 50  0 public void setPrefix(String prefix) throws DOMException {
 51  0 DOMNodeHelper.setPrefix(this, prefix);
 52    }
 53   
 54  0 public String getLocalName() {
 55  0 return DOMNodeHelper.getLocalName(this);
 56    }
 57   
 58  0 public String getNodeName() {
 59  0 return "#text";
 60    }
 61   
 62    // already part of API
 63    //
 64    // public short getNodeType();
 65  73 public String getNodeValue() throws DOMException {
 66  73 return DOMNodeHelper.getNodeValue(this);
 67    }
 68   
 69  0 public void setNodeValue(String nodeValue) throws DOMException {
 70  0 DOMNodeHelper.setNodeValue(this, nodeValue);
 71    }
 72   
 73  15 public org.w3c.dom.Node getParentNode() {
 74  15 return DOMNodeHelper.getParentNode(this);
 75    }
 76   
 77  0 public NodeList getChildNodes() {
 78  0 return DOMNodeHelper.getChildNodes(this);
 79    }
 80   
 81  0 public org.w3c.dom.Node getFirstChild() {
 82  0 return DOMNodeHelper.getFirstChild(this);
 83    }
 84   
 85  0 public org.w3c.dom.Node getLastChild() {
 86  0 return DOMNodeHelper.getLastChild(this);
 87    }
 88   
 89  0 public org.w3c.dom.Node getPreviousSibling() {
 90  0 return DOMNodeHelper.getPreviousSibling(this);
 91    }
 92   
 93  0 public org.w3c.dom.Node getNextSibling() {
 94  0 return DOMNodeHelper.getNextSibling(this);
 95    }
 96   
 97  0 public NamedNodeMap getAttributes() {
 98  0 return null;
 99    }
 100   
 101  0 public Document getOwnerDocument() {
 102  0 return DOMNodeHelper.getOwnerDocument(this);
 103    }
 104   
 105  0 public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
 106    org.w3c.dom.Node refChild) throws DOMException {
 107  0 checkNewChildNode(newChild);
 108   
 109  0 return DOMNodeHelper.insertBefore(this, newChild, refChild);
 110    }
 111   
 112  0 public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
 113    org.w3c.dom.Node oldChild) throws DOMException {
 114  0 checkNewChildNode(newChild);
 115   
 116  0 return DOMNodeHelper.replaceChild(this, newChild, oldChild);
 117    }
 118   
 119  0 public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
 120    throws DOMException {
 121  0 return DOMNodeHelper.removeChild(this, oldChild);
 122    }
 123   
 124  0 public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
 125    throws DOMException {
 126  0 checkNewChildNode(newChild);
 127   
 128  0 return DOMNodeHelper.appendChild(this, newChild);
 129    }
 130   
 131  0 private void checkNewChildNode(org.w3c.dom.Node newChild)
 132    throws DOMException {
 133  0 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
 134    "Text nodes cannot have children");
 135    }
 136   
 137  0 public boolean hasChildNodes() {
 138  0 return DOMNodeHelper.hasChildNodes(this);
 139    }
 140   
 141  0 public org.w3c.dom.Node cloneNode(boolean deep) {
 142  0 return DOMNodeHelper.cloneNode(this, deep);
 143    }
 144   
 145  0 public void normalize() {
 146  0 DOMNodeHelper.normalize(this);
 147    }
 148   
 149  0 public boolean isSupported(String feature, String version) {
 150  0 return DOMNodeHelper.isSupported(this, feature, version);
 151    }
 152   
 153  0 public boolean hasAttributes() {
 154  0 return DOMNodeHelper.hasAttributes(this);
 155    }
 156   
 157    // org.w3c.dom.CharacterData interface
 158    // -------------------------------------------------------------------------
 159  0 public String getData() throws DOMException {
 160  0 return DOMNodeHelper.getData(this);
 161    }
 162   
 163  0 public void setData(String data) throws DOMException {
 164  0 DOMNodeHelper.setData(this, data);
 165    }
 166   
 167  0 public int getLength() {
 168  0 return DOMNodeHelper.getLength(this);
 169    }
 170   
 171  0 public String substringData(int offset, int count) throws DOMException {
 172  0 return DOMNodeHelper.substringData(this, offset, count);
 173    }
 174   
 175  0 public void appendData(String arg) throws DOMException {
 176  0 DOMNodeHelper.appendData(this, arg);
 177    }
 178   
 179  0 public void insertData(int offset, String arg) throws DOMException {
 180  0 DOMNodeHelper.insertData(this, offset, arg);
 181    }
 182   
 183  0 public void deleteData(int offset, int count) throws DOMException {
 184  0 DOMNodeHelper.deleteData(this, offset, count);
 185    }
 186   
 187  0 public void replaceData(int offset, int count, String arg)
 188    throws DOMException {
 189  0 DOMNodeHelper.replaceData(this, offset, count, arg);
 190    }
 191   
 192    // org.w3c.dom.Text interface
 193    // -------------------------------------------------------------------------
 194  0 public org.w3c.dom.Text splitText(int offset) throws DOMException {
 195  0 if (isReadOnly()) {
 196  0 throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
 197    "CharacterData node is read only: " + this);
 198    } else {
 199  0 String text = getText();
 200  0 int length = (text != null) ? text.length() : 0;
 201   
 202  0 if ((offset < 0) || (offset >= length)) {
 203  0 throw new DOMException(DOMException.INDEX_SIZE_ERR,
 204    "No text at offset: " + offset);
 205    } else {
 206  0 String start = text.substring(0, offset);
 207  0 String rest = text.substring(offset);
 208  0 setText(start);
 209   
 210  0 Element parent = getParent();
 211  0 Text newText = createText(rest);
 212   
 213  0 if (parent != null) {
 214  0 parent.add(newText);
 215    }
 216   
 217  0 return DOMNodeHelper.asDOMText(newText);
 218    }
 219    }
 220    }
 221   
 222    // Implementation methods
 223    // -------------------------------------------------------------------------
 224  0 protected Text createText(String text) {
 225  0 return new DOMText(text);
 226    }
 227    }
 228   
 229    /*
 230    * Redistribution and use of this software and associated documentation
 231    * ("Software"), with or without modification, are permitted provided that the
 232    * following conditions are met:
 233    *
 234    * 1. Redistributions of source code must retain copyright statements and
 235    * notices. Redistributions must also contain a copy of this document.
 236    *
 237    * 2. Redistributions in binary form must reproduce the above copyright notice,
 238    * this list of conditions and the following disclaimer in the documentation
 239    * and/or other materials provided with the distribution.
 240    *
 241    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 242    * from this Software without prior written permission of MetaStuff, Ltd. For
 243    * written permission, please contact dom4j-info@metastuff.com.
 244    *
 245    * 4. Products derived from this Software may not be called "DOM4J" nor may
 246    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 247    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 248    *
 249    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 250    *
 251    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 252    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 253    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 254    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 255    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 256    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 257    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 258    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 259    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 260    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 261    * POSSIBILITY OF SUCH DAMAGE.
 262    *
 263    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 264    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dom/DOMElement.html0000644000175000017500000035353510242117677021535 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 429   Methods: 50
NCLOC: 279   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DOMElement.java 18,4% 25,2% 26% 24,1%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dom;
 9   
 10    import java.util.ArrayList;
 11    import java.util.List;
 12   
 13    import org.dom4j.Attribute;
 14    import org.dom4j.DocumentFactory;
 15    import org.dom4j.Namespace;
 16    import org.dom4j.QName;
 17    import org.dom4j.tree.DefaultElement;
 18   
 19    import org.w3c.dom.DOMException;
 20    import org.w3c.dom.Document;
 21    import org.w3c.dom.NamedNodeMap;
 22    import org.w3c.dom.Node;
 23    import org.w3c.dom.NodeList;
 24   
 25    /**
 26    * <p>
 27    * <code>DOMElement</code> implements an XML element which supports the W3C
 28    * DOM API.
 29    * </p>
 30    *
 31    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 32    * @version $Revision: 1.23 $
 33    */
 34    public class DOMElement extends DefaultElement implements org.w3c.dom.Element {
 35    /** The <code>DocumentFactory</code> instance used by default */
 36    private static final DocumentFactory DOCUMENT_FACTORY = DOMDocumentFactory
 37    .getInstance();
 38   
 39  0 public DOMElement(String name) {
 40  0 super(name);
 41    }
 42   
 43  151 public DOMElement(QName qname) {
 44  151 super(qname);
 45    }
 46   
 47  0 public DOMElement(QName qname, int attributeCount) {
 48  0 super(qname, attributeCount);
 49    }
 50   
 51  0 public DOMElement(String name, Namespace namespace) {
 52  0 super(name, namespace);
 53    }
 54   
 55    // org.w3c.dom.Node interface
 56    // -------------------------------------------------------------------------
 57  0 public boolean supports(String feature, String version) {
 58  0 return DOMNodeHelper.supports(this, feature, version);
 59    }
 60   
 61  5 public String getNamespaceURI() {
 62  5 return getQName().getNamespaceURI();
 63    }
 64   
 65  0 public String getPrefix() {
 66  0 return getQName().getNamespacePrefix();
 67    }
 68   
 69  0 public void setPrefix(String prefix) throws DOMException {
 70  0 DOMNodeHelper.setPrefix(this, prefix);
 71    }
 72   
 73  0 public String getLocalName() {
 74  0 return getQName().getName();
 75    }
 76   
 77  0 public String getNodeName() {
 78  0 return getName();
 79    }
 80   
 81    // already part of API
 82    //
 83    // public short getNodeType();
 84  0 public String getNodeValue() throws DOMException {
 85  0 return null;
 86    }
 87   
 88  0 public void setNodeValue(String nodeValue) throws DOMException {
 89    }
 90   
 91  15 public org.w3c.dom.Node getParentNode() {
 92  15 return DOMNodeHelper.getParentNode(this);
 93    }
 94   
 95  34 public NodeList getChildNodes() {
 96  34 return DOMNodeHelper.createNodeList(content());
 97    }
 98   
 99  0 public org.w3c.dom.Node getFirstChild() {
 100  0 return DOMNodeHelper.asDOMNode(node(0));
 101    }
 102   
 103  0 public org.w3c.dom.Node getLastChild() {
 104  0 return DOMNodeHelper.asDOMNode(node(nodeCount() - 1));
 105    }
 106   
 107  0 public org.w3c.dom.Node getPreviousSibling() {
 108  0 return DOMNodeHelper.getPreviousSibling(this);
 109    }
 110   
 111  0 public org.w3c.dom.Node getNextSibling() {
 112  0 return DOMNodeHelper.getNextSibling(this);
 113    }
 114   
 115  35 public NamedNodeMap getAttributes() {
 116  35 return new DOMAttributeNodeMap(this);
 117    }
 118   
 119  0 public Document getOwnerDocument() {
 120  0 return DOMNodeHelper.getOwnerDocument(this);
 121    }
 122   
 123  0 public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
 124    org.w3c.dom.Node refChild) throws DOMException {
 125  0 checkNewChildNode(newChild);
 126   
 127  0 return DOMNodeHelper.insertBefore(this, newChild, refChild);
 128    }
 129   
 130  2 public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
 131    org.w3c.dom.Node oldChild) throws DOMException {
 132  2 checkNewChildNode(newChild);
 133   
 134  2 return DOMNodeHelper.replaceChild(this, newChild, oldChild);
 135    }
 136   
 137  0 public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
 138    throws DOMException {
 139  0 return DOMNodeHelper.removeChild(this, oldChild);
 140    }
 141   
 142  26 public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
 143    throws DOMException {
 144  26 checkNewChildNode(newChild);
 145   
 146  26 return DOMNodeHelper.appendChild(this, newChild);
 147    }
 148   
 149  28 private void checkNewChildNode(org.w3c.dom.Node newChild)
 150    throws DOMException {
 151  28 final int nodeType = newChild.getNodeType();
 152   
 153  28 if (!((nodeType == Node.ELEMENT_NODE) || (nodeType == Node.TEXT_NODE)
 154    || (nodeType == Node.COMMENT_NODE)
 155    || (nodeType == Node.PROCESSING_INSTRUCTION_NODE)
 156    || (nodeType == Node.CDATA_SECTION_NODE)
 157    || (nodeType == Node.ENTITY_REFERENCE_NODE))) {
 158  0 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
 159    "Given node cannot be a child of element");
 160    }
 161    }
 162   
 163  0 public boolean hasChildNodes() {
 164  0 return nodeCount() > 0;
 165    }
 166   
 167  0 public org.w3c.dom.Node cloneNode(boolean deep) {
 168  0 return DOMNodeHelper.cloneNode(this, deep);
 169    }
 170   
 171  0 public boolean isSupported(String feature, String version) {
 172  0 return DOMNodeHelper.isSupported(this, feature, version);
 173    }
 174   
 175  0 public boolean hasAttributes() {
 176  0 return DOMNodeHelper.hasAttributes(this);
 177    }
 178   
 179    // org.w3c.dom.Element interface
 180    // -------------------------------------------------------------------------
 181  0 public String getTagName() {
 182  0 return getName();
 183    }
 184   
 185  0 public String getAttribute(String name) {
 186  0 String answer = attributeValue(name);
 187   
 188  0 return (answer != null) ? answer : "";
 189    }
 190   
 191  6 public void setAttribute(String name, String value) throws DOMException {
 192  6 addAttribute(name, value);
 193    }
 194   
 195  0 public void removeAttribute(String name) throws DOMException {
 196  0 Attribute attribute = attribute(name);
 197   
 198  0 if (attribute != null) {
 199  0 remove(attribute);
 200    }
 201    }
 202   
 203  0 public org.w3c.dom.Attr getAttributeNode(String name) {
 204  0 return DOMNodeHelper.asDOMAttr(attribute(name));
 205    }
 206   
 207  0 public org.w3c.dom.Attr setAttributeNode(org.w3c.dom.Attr newAttr)
 208    throws DOMException {
 209  0 if (this.isReadOnly()) {
 210  0 throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
 211    "No modification allowed");
 212    }
 213   
 214  0 Attribute attribute = attribute(newAttr);
 215   
 216  0 if (attribute != newAttr) {
 217  0 if (newAttr.getOwnerElement() != null) {
 218  0 throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR,
 219    "Attribute is already in use");
 220    }
 221   
 222  0 Attribute newAttribute = createAttribute(newAttr);
 223   
 224  0 if (attribute != null) {
 225  0 attribute.detach();
 226    }
 227   
 228  0 add(newAttribute);
 229    }
 230   
 231  0 return DOMNodeHelper.asDOMAttr(attribute);
 232    }
 233   
 234  0 public org.w3c.dom.Attr removeAttributeNode(org.w3c.dom.Attr oldAttr)
 235    throws DOMException {
 236  0 Attribute attribute = attribute(oldAttr);
 237   
 238  0 if (attribute != null) {
 239  0 attribute.detach();
 240   
 241  0 return DOMNodeHelper.asDOMAttr(attribute);
 242    } else {
 243  0 throw new DOMException(DOMException.NOT_FOUND_ERR,
 244    "No such attribute");
 245    }
 246    }
 247   
 248  0 public String getAttributeNS(String namespaceURI, String localName) {
 249  0 Attribute attribute = attribute(namespaceURI, localName);
 250   
 251  0 if (attribute != null) {
 252  0 String answer = attribute.getValue();
 253   
 254  0 if (answer != null) {
 255  0 return answer;
 256    }
 257    }
 258   
 259  0 return "";
 260    }
 261   
 262  4 public void setAttributeNS(String namespaceURI, String qualifiedName,
 263    String value) throws DOMException {
 264  4 Attribute attribute = attribute(namespaceURI, qualifiedName);
 265   
 266  4 if (attribute != null) {
 267  0 attribute.setValue(value);
 268    } else {
 269  4 QName qname = getQName(namespaceURI, qualifiedName);
 270  4 addAttribute(qname, value);
 271    }
 272    }
 273   
 274  0 public void removeAttributeNS(String namespaceURI, String localName)
 275    throws DOMException {
 276  0 Attribute attribute = attribute(namespaceURI, localName);
 277   
 278  0 if (attribute != null) {
 279  0 remove(attribute);
 280    }
 281    }
 282   
 283  0 public org.w3c.dom.Attr getAttributeNodeNS(String namespaceURI,
 284    String localName) {
 285  0 Attribute attribute = attribute(namespaceURI, localName);
 286   
 287  0 if (attribute != null) {
 288  0 DOMNodeHelper.asDOMAttr(attribute);
 289    }
 290   
 291  0 return null;
 292    }
 293   
 294  0 public org.w3c.dom.Attr setAttributeNodeNS(org.w3c.dom.Attr newAttr)
 295    throws DOMException {
 296  0 Attribute attribute = attribute(newAttr.getNamespaceURI(), newAttr
 297    .getLocalName());
 298   
 299  0 if (attribute != null) {
 300  0 attribute.setValue(newAttr.getValue());
 301    } else {
 302  0 attribute = createAttribute(newAttr);
 303  0 add(attribute);
 304    }
 305   
 306  0 return DOMNodeHelper.asDOMAttr(attribute);
 307    }
 308   
 309  0 public NodeList getElementsByTagName(String name) {
 310  0 ArrayList list = new ArrayList();
 311  0 DOMNodeHelper.appendElementsByTagName(list, this, name);
 312   
 313  0 return DOMNodeHelper.createNodeList(list);
 314    }
 315   
 316  0 public NodeList getElementsByTagNameNS(String namespace, String lName) {
 317  0 ArrayList list = new ArrayList();
 318  0 DOMNodeHelper.appendElementsByTagNameNS(list, this, namespace, lName);
 319   
 320  0 return DOMNodeHelper.createNodeList(list);
 321    }
 322   
 323  0 public boolean hasAttribute(String name) {
 324  0 return attribute(name) != null;
 325    }
 326   
 327  0 public boolean hasAttributeNS(String namespaceURI, String localName) {
 328  0 return attribute(namespaceURI, localName) != null;
 329    }
 330   
 331    // Implementation methods
 332    // -------------------------------------------------------------------------
 333  547 protected DocumentFactory getDocumentFactory() {
 334  547 DocumentFactory factory = getQName().getDocumentFactory();
 335   
 336  547 return (factory != null) ? factory : DOCUMENT_FACTORY;
 337    }
 338   
 339  0 protected Attribute attribute(org.w3c.dom.Attr attr) {
 340  0 return attribute(DOCUMENT_FACTORY.createQName(attr.getLocalName(), attr
 341    .getPrefix(), attr.getNamespaceURI()));
 342    }
 343   
 344  4 protected Attribute attribute(String namespaceURI, String localName) {
 345  4 List attributes = attributeList();
 346  4 int size = attributes.size();
 347   
 348  4 for (int i = 0; i < size; i++) {
 349  3 Attribute attribute = (Attribute) attributes.get(i);
 350   
 351  3 if (localName.equals(attribute.getName())
 352    && (((namespaceURI == null || namespaceURI.length() == 0)
 353    && ((attribute.getNamespaceURI() == null)
 354    || (attribute.getNamespaceURI().length() == 0)))
 355    || ((namespaceURI != null) && namespaceURI
 356    .equals(attribute.getNamespaceURI())))) {
 357  0 return attribute;
 358    }
 359    }
 360   
 361  4 return null;
 362    }
 363   
 364  0 protected Attribute createAttribute(org.w3c.dom.Attr newAttr) {
 365  0 QName qname = null;
 366  0 String name = newAttr.getLocalName();
 367   
 368  0 if (name != null) {
 369  0 String prefix = newAttr.getPrefix();
 370  0 String uri = newAttr.getNamespaceURI();
 371  0 qname = getDocumentFactory().createQName(name, prefix, uri);
 372    } else {
 373  0 name = newAttr.getName();
 374  0 qname = getDocumentFactory().createQName(name);
 375    }
 376   
 377  0 return new DOMAttribute(qname, newAttr.getValue());
 378    }
 379   
 380  4 protected QName getQName(String namespace, String qualifiedName) {
 381  4 int index = qualifiedName.indexOf(':');
 382  4 String prefix = "";
 383  4 String localName = qualifiedName;
 384   
 385  4 if (index >= 0) {
 386  0 prefix = qualifiedName.substring(0, index);
 387  0 localName = qualifiedName.substring(index + 1);
 388    }
 389   
 390  4 return getDocumentFactory().createQName(localName, prefix, namespace);
 391    }
 392    }
 393   
 394    /*
 395    * Redistribution and use of this software and associated documentation
 396    * ("Software"), with or without modification, are permitted provided that the
 397    * following conditions are met:
 398    *
 399    * 1. Redistributions of source code must retain copyright statements and
 400    * notices. Redistributions must also contain a copy of this document.
 401    *
 402    * 2. Redistributions in binary form must reproduce the above copyright notice,
 403    * this list of conditions and the following disclaimer in the documentation
 404    * and/or other materials provided with the distribution.
 405    *
 406    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 407    * from this Software without prior written permission of MetaStuff, Ltd. For
 408    * written permission, please contact dom4j-info@metastuff.com.
 409    *
 410    * 4. Products derived from this Software may not be called "DOM4J" nor may
 411    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 412    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 413    *
 414    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 415    *
 416    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 417    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 418    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 419    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 420    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 421    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 422    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 423    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 424    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 425    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 426    * POSSIBILITY OF SUCH DAMAGE.
 427    *
 428    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 429    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dom/DOMNamespace.html0000644000175000017500000014522410242117704022021 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 180   Methods: 26
NCLOC: 91   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DOMNamespace.java - 3,8% 3,8% 3,8%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dom;
 9   
 10    import org.dom4j.Element;
 11    import org.dom4j.tree.DefaultNamespace;
 12   
 13    import org.w3c.dom.DOMException;
 14    import org.w3c.dom.Document;
 15    import org.w3c.dom.NamedNodeMap;
 16    import org.w3c.dom.NodeList;
 17   
 18    /**
 19    * <p>
 20    * <code>DOMNamespace</code> implements a Namespace that is compatable with
 21    * the DOM API.
 22    * </p>
 23    *
 24    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 25    * @version $Revision: 1.10 $
 26    */
 27    public class DOMNamespace extends DefaultNamespace implements org.w3c.dom.Node {
 28  159 public DOMNamespace(String prefix, String uri) {
 29  159 super(prefix, uri);
 30    }
 31   
 32  0 public DOMNamespace(Element parent, String prefix, String uri) {
 33  0 super(parent, prefix, uri);
 34    }
 35   
 36    // org.w3c.dom.Node interface
 37    // -------------------------------------------------------------------------
 38  0 public boolean supports(String feature, String version) {
 39  0 return DOMNodeHelper.supports(this, feature, version);
 40    }
 41   
 42  0 public String getNamespaceURI() {
 43  0 return DOMNodeHelper.getNamespaceURI(this);
 44    }
 45   
 46    // public String getPrefix() {
 47    // return DOMNodeHelper.getPrefix(this);
 48    // }
 49  0 public void setPrefix(String prefix) throws DOMException {
 50  0 DOMNodeHelper.setPrefix(this, prefix);
 51    }
 52   
 53  0 public String getLocalName() {
 54  0 return DOMNodeHelper.getLocalName(this);
 55    }
 56   
 57  0 public String getNodeName() {
 58  0 return getName();
 59    }
 60   
 61    // already part of API
 62    //
 63    // public short getNodeType();
 64  0 public String getNodeValue() throws DOMException {
 65  0 return DOMNodeHelper.getNodeValue(this);
 66    }
 67   
 68  0 public void setNodeValue(String nodeValue) throws DOMException {
 69  0 DOMNodeHelper.setNodeValue(this, nodeValue);
 70    }
 71   
 72  0 public org.w3c.dom.Node getParentNode() {
 73  0 return DOMNodeHelper.getParentNode(this);
 74    }
 75   
 76  0 public NodeList getChildNodes() {
 77  0 return DOMNodeHelper.getChildNodes(this);
 78    }
 79   
 80  0 public org.w3c.dom.Node getFirstChild() {
 81  0 return DOMNodeHelper.getFirstChild(this);
 82    }
 83   
 84  0 public org.w3c.dom.Node getLastChild() {
 85  0 return DOMNodeHelper.getLastChild(this);
 86    }
 87   
 88  0 public org.w3c.dom.Node getPreviousSibling() {
 89  0 return DOMNodeHelper.getPreviousSibling(this);
 90    }
 91   
 92  0 public org.w3c.dom.Node getNextSibling() {
 93  0 return DOMNodeHelper.getNextSibling(this);
 94    }
 95   
 96  0 public NamedNodeMap getAttributes() {
 97  0 return DOMNodeHelper.getAttributes(this);
 98    }
 99   
 100  0 public Document getOwnerDocument() {
 101  0 return DOMNodeHelper.getOwnerDocument(this);
 102    }
 103   
 104  0 public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
 105    org.w3c.dom.Node refChild) throws DOMException {
 106  0 return DOMNodeHelper.insertBefore(this, newChild, refChild);
 107    }
 108   
 109  0 public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
 110    org.w3c.dom.Node oldChild) throws DOMException {
 111  0 return DOMNodeHelper.replaceChild(this, newChild, oldChild);
 112    }
 113   
 114  0 public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
 115    throws DOMException {
 116  0 return DOMNodeHelper.removeChild(this, oldChild);
 117    }
 118   
 119  0 public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
 120    throws DOMException {
 121  0 return DOMNodeHelper.appendChild(this, newChild);
 122    }
 123   
 124  0 public boolean hasChildNodes() {
 125  0 return DOMNodeHelper.hasChildNodes(this);
 126    }
 127   
 128  0 public org.w3c.dom.Node cloneNode(boolean deep) {
 129  0 return DOMNodeHelper.cloneNode(this, deep);
 130    }
 131   
 132  0 public void normalize() {
 133  0 DOMNodeHelper.normalize(this);
 134    }
 135   
 136  0 public boolean isSupported(String feature, String version) {
 137  0 return DOMNodeHelper.isSupported(this, feature, version);
 138    }
 139   
 140  0 public boolean hasAttributes() {
 141  0 return DOMNodeHelper.hasAttributes(this);
 142    }
 143    }
 144   
 145    /*
 146    * Redistribution and use of this software and associated documentation
 147    * ("Software"), with or without modification, are permitted provided that the
 148    * following conditions are met:
 149    *
 150    * 1. Redistributions of source code must retain copyright statements and
 151    * notices. Redistributions must also contain a copy of this document.
 152    *
 153    * 2. Redistributions in binary form must reproduce the above copyright notice,
 154    * this list of conditions and the following disclaimer in the documentation
 155    * and/or other materials provided with the distribution.
 156    *
 157    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 158    * from this Software without prior written permission of MetaStuff, Ltd. For
 159    * written permission, please contact dom4j-info@metastuff.com.
 160    *
 161    * 4. Products derived from this Software may not be called "DOM4J" nor may
 162    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 163    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 164    *
 165    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 166    *
 167    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 168    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 169    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 170    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 171    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 172    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 173    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 174    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 175    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 176    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 177    * POSSIBILITY OF SUCH DAMAGE.
 178    *
 179    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 180    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dom/DOMProcessingInstruction.html0000644000175000017500000017164310242117554024512 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 219   Methods: 31
NCLOC: 118   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DOMProcessingInstruction.java 0% 2,8% 3,2% 2,9%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dom;
 9   
 10    import java.util.Map;
 11   
 12    import org.dom4j.Element;
 13    import org.dom4j.tree.DefaultProcessingInstruction;
 14   
 15    import org.w3c.dom.DOMException;
 16    import org.w3c.dom.Document;
 17    import org.w3c.dom.NamedNodeMap;
 18    import org.w3c.dom.NodeList;
 19   
 20    /**
 21    * <p>
 22    * <code>DOMProcessingInstruction</code> implements a ProcessingInstruction
 23    * node which supports the W3C DOM API.
 24    * </p>
 25    *
 26    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 27    * @version $Revision: 1.12 $
 28    */
 29    public class DOMProcessingInstruction extends DefaultProcessingInstruction
 30    implements org.w3c.dom.ProcessingInstruction {
 31  0 public DOMProcessingInstruction(String target, Map values) {
 32  0 super(target, values);
 33    }
 34   
 35  12 public DOMProcessingInstruction(String target, String values) {
 36  12 super(target, values);
 37    }
 38   
 39  0 public DOMProcessingInstruction(Element parent, String target, String val) {
 40  0 super(parent, target, val);
 41    }
 42   
 43    // org.w3c.dom.Node interface
 44    // -------------------------------------------------------------------------
 45  0 public boolean supports(String feature, String version) {
 46  0 return DOMNodeHelper.supports(this, feature, version);
 47    }
 48   
 49  0 public String getNamespaceURI() {
 50  0 return DOMNodeHelper.getNamespaceURI(this);
 51    }
 52   
 53  0 public String getPrefix() {
 54  0 return DOMNodeHelper.getPrefix(this);
 55    }
 56   
 57  0 public void setPrefix(String prefix) throws DOMException {
 58  0 DOMNodeHelper.setPrefix(this, prefix);
 59    }
 60   
 61  0 public String getLocalName() {
 62  0 return DOMNodeHelper.getLocalName(this);
 63    }
 64   
 65  0 public String getNodeName() {
 66  0 return getName();
 67    }
 68   
 69    // already part of API
 70    //
 71    // public short getNodeType();
 72  0 public String getNodeValue() throws DOMException {
 73  0 return DOMNodeHelper.getNodeValue(this);
 74    }
 75   
 76  0 public void setNodeValue(String nodeValue) throws DOMException {
 77  0 DOMNodeHelper.setNodeValue(this, nodeValue);
 78    }
 79   
 80  0 public org.w3c.dom.Node getParentNode() {
 81  0 return DOMNodeHelper.getParentNode(this);
 82    }
 83   
 84  0 public NodeList getChildNodes() {
 85  0 return DOMNodeHelper.getChildNodes(this);
 86    }
 87   
 88  0 public org.w3c.dom.Node getFirstChild() {
 89  0 return DOMNodeHelper.getFirstChild(this);
 90    }
 91   
 92  0 public org.w3c.dom.Node getLastChild() {
 93  0 return DOMNodeHelper.getLastChild(this);
 94    }
 95   
 96  0 public org.w3c.dom.Node getPreviousSibling() {
 97  0 return DOMNodeHelper.getPreviousSibling(this);
 98    }
 99   
 100  0 public org.w3c.dom.Node getNextSibling() {
 101  0 return DOMNodeHelper.getNextSibling(this);
 102    }
 103   
 104  0 public NamedNodeMap getAttributes() {
 105  0 return null;
 106    }
 107   
 108  0 public Document getOwnerDocument() {
 109  0 return DOMNodeHelper.getOwnerDocument(this);
 110    }
 111   
 112  0 public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
 113    org.w3c.dom.Node refChild) throws DOMException {
 114  0 checkNewChildNode(newChild);
 115   
 116  0 return DOMNodeHelper.insertBefore(this, newChild, refChild);
 117    }
 118   
 119  0 public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
 120    org.w3c.dom.Node oldChild) throws DOMException {
 121  0 checkNewChildNode(newChild);
 122   
 123  0 return DOMNodeHelper.replaceChild(this, newChild, oldChild);
 124    }
 125   
 126  0 public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
 127    throws DOMException {
 128  0 return DOMNodeHelper.removeChild(this, oldChild);
 129    }
 130   
 131  0 public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
 132    throws DOMException {
 133  0 checkNewChildNode(newChild);
 134   
 135  0 return DOMNodeHelper.appendChild(this, newChild);
 136    }
 137   
 138  0 private void checkNewChildNode(org.w3c.dom.Node newChild)
 139    throws DOMException {
 140  0 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
 141    "PI nodes cannot have children");
 142    }
 143   
 144  0 public boolean hasChildNodes() {
 145  0 return DOMNodeHelper.hasChildNodes(this);
 146    }
 147   
 148  0 public org.w3c.dom.Node cloneNode(boolean deep) {
 149  0 return DOMNodeHelper.cloneNode(this, deep);
 150    }
 151   
 152  0 public void normalize() {
 153  0 DOMNodeHelper.normalize(this);
 154    }
 155   
 156  0 public boolean isSupported(String feature, String version) {
 157  0 return DOMNodeHelper.isSupported(this, feature, version);
 158    }
 159   
 160  0 public boolean hasAttributes() {
 161  0 return DOMNodeHelper.hasAttributes(this);
 162    }
 163   
 164    // org.w3c.dom.ProcessingInstruction interface
 165    // -------------------------------------------------------------------------
 166    // public String getTarget();
 167  0 public String getData() {
 168  0 return getText();
 169    }
 170   
 171  0 public void setData(String data) throws DOMException {
 172  0 if (isReadOnly()) {
 173  0 throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
 174    "This ProcessingInstruction is read only");
 175    } else {
 176  0 setText(data);
 177    }
 178    }
 179   
 180    // Implementation methods
 181    // -------------------------------------------------------------------------
 182    }
 183   
 184    /*
 185    * Redistribution and use of this software and associated documentation
 186    * ("Software"), with or without modification, are permitted provided that the
 187    * following conditions are met:
 188    *
 189    * 1. Redistributions of source code must retain copyright statements and
 190    * notices. Redistributions must also contain a copy of this document.
 191    *
 192    * 2. Redistributions in binary form must reproduce the above copyright notice,
 193    * this list of conditions and the following disclaimer in the documentation
 194    * and/or other materials provided with the distribution.
 195    *
 196    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 197    * from this Software without prior written permission of MetaStuff, Ltd. For
 198    * written permission, please contact dom4j-info@metastuff.com.
 199    *
 200    * 4. Products derived from this Software may not be called "DOM4J" nor may
 201    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 202    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 203    *
 204    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 205    *
 206    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 207    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 208    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 209    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 210    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 211    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 212    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 213    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 214    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 215    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 216    * POSSIBILITY OF SUCH DAMAGE.
 217    *
 218    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 219    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dom/pkg-summary.html0000644000175000017500000003540510242117713022040 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
package stats: LOC: 3.495   Methods: 438
NCLOC: 2.065   Classes: 14
Files: 13  
 
 Package Conditionals Statements Methods TOTAL
org.dom4j.dom 11,1% 13,7% 11,6% 12,7%
coverage coverage
 
 Classes Conditionals Statements Methods TOTAL
DOMCDATA 0% 0% 0% 0%
coverage
DOMDocumentType - 0% 0% 0%
coverage
DOMEntityReference 0% 0% 0% 0%
coverage
DOMNodeHelper.EmptyNodeList - 0% 0% 0%
coverage
DOMComment - 2,6% 2,8% 2,7%
coverage coverage
DOMAttribute 0% 2,8% 3,2% 2,9%
coverage coverage
DOMProcessingInstruction 0% 2,8% 3,2% 2,9%
coverage coverage
DOMNamespace - 3,8% 3,8% 3,8%
coverage coverage
DOMText 0% 5,6% 7,9% 6%
coverage coverage
DOMAttributeNodeMap 0% 10% 20% 10,5%
coverage coverage
DOMNodeHelper 11% 15,6% 22,2% 15,1%
coverage coverage
DOMDocument 33,3% 22,2% 22% 22,7%
coverage coverage
DOMElement 18,4% 25,2% 26% 24,1%
coverage coverage
DOMDocumentFactory 0% 46,5% 44,4% 41,8%
coverage coverage
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dom/DOMAttribute.html0000644000175000017500000017147610242117760022102 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 219   Methods: 31
NCLOC: 116   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DOMAttribute.java 0% 2,8% 3,2% 2,9%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dom;
 9   
 10    import org.dom4j.Element;
 11    import org.dom4j.QName;
 12    import org.dom4j.tree.DefaultAttribute;
 13   
 14    import org.w3c.dom.DOMException;
 15    import org.w3c.dom.Document;
 16    import org.w3c.dom.NamedNodeMap;
 17    import org.w3c.dom.NodeList;
 18   
 19    /**
 20    * <p>
 21    * <code>DOMAttribute</code> implements a doubly linked attribute which
 22    * supports the W3C DOM API.
 23    * </p>
 24    *
 25    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 26    * @version $Revision: 1.14 $
 27    */
 28    public class DOMAttribute extends DefaultAttribute implements org.w3c.dom.Attr {
 29  0 public DOMAttribute(QName qname) {
 30  0 super(qname);
 31    }
 32   
 33  114 public DOMAttribute(QName qname, String value) {
 34  114 super(qname, value);
 35    }
 36   
 37  0 public DOMAttribute(Element parent, QName qname, String value) {
 38  0 super(parent, qname, value);
 39    }
 40   
 41    // org.w3c.dom.Node interface
 42    // -------------------------------------------------------------------------
 43  0 public boolean supports(String feature, String version) {
 44  0 return DOMNodeHelper.supports(this, feature, version);
 45    }
 46   
 47  0 public String getNamespaceURI() {
 48  0 return getQName().getNamespaceURI();
 49    }
 50   
 51  0 public String getPrefix() {
 52  0 return getQName().getNamespacePrefix();
 53    }
 54   
 55  0 public void setPrefix(String prefix) throws DOMException {
 56  0 DOMNodeHelper.setPrefix(this, prefix);
 57    }
 58   
 59  0 public String getLocalName() {
 60  0 return getQName().getName();
 61    }
 62   
 63  0 public String getNodeName() {
 64  0 return getName();
 65    }
 66   
 67    // already part of API
 68    //
 69    // public short getNodeType();
 70  0 public String getNodeValue() throws DOMException {
 71  0 return DOMNodeHelper.getNodeValue(this);
 72    }
 73   
 74  0 public void setNodeValue(String nodeValue) throws DOMException {
 75  0 DOMNodeHelper.setNodeValue(this, nodeValue);
 76    }
 77   
 78  0 public org.w3c.dom.Node getParentNode() {
 79    // Per http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-637646024
 80    // and the NIST conformance tests, Attr.getParentNode() should always
 81    // return null
 82  0 return null;
 83    }
 84   
 85  0 public NodeList getChildNodes() {
 86  0 return DOMNodeHelper.getChildNodes(this);
 87    }
 88   
 89  0 public org.w3c.dom.Node getFirstChild() {
 90  0 return DOMNodeHelper.getFirstChild(this);
 91    }
 92   
 93  0 public org.w3c.dom.Node getLastChild() {
 94  0 return DOMNodeHelper.getLastChild(this);
 95    }
 96   
 97  0 public org.w3c.dom.Node getPreviousSibling() {
 98  0 return DOMNodeHelper.getPreviousSibling(this);
 99    }
 100   
 101  0 public org.w3c.dom.Node getNextSibling() {
 102  0 return DOMNodeHelper.getNextSibling(this);
 103    }
 104   
 105  0 public NamedNodeMap getAttributes() {
 106  0 return null;
 107    }
 108   
 109  0 public Document getOwnerDocument() {
 110  0 return DOMNodeHelper.getOwnerDocument(this);
 111    }
 112   
 113  0 public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
 114    org.w3c.dom.Node refChild) throws DOMException {
 115  0 checkNewChildNode(newChild);
 116   
 117  0 return DOMNodeHelper.insertBefore(this, newChild, refChild);
 118    }
 119   
 120  0 public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
 121    org.w3c.dom.Node oldChild) throws DOMException {
 122  0 checkNewChildNode(newChild);
 123   
 124  0 return DOMNodeHelper.replaceChild(this, newChild, oldChild);
 125    }
 126   
 127  0 public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
 128    throws DOMException {
 129  0 return DOMNodeHelper.removeChild(this, oldChild);
 130    }
 131   
 132  0 public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
 133    throws DOMException {
 134  0 checkNewChildNode(newChild);
 135   
 136  0 return DOMNodeHelper.appendChild(this, newChild);
 137    }
 138   
 139  0 private void checkNewChildNode(org.w3c.dom.Node newChild)
 140    throws DOMException {
 141  0 final int nodeType = newChild.getNodeType();
 142   
 143  0 if (!((nodeType == org.w3c.dom.Node.TEXT_NODE)
 144    || (nodeType == org.w3c.dom.Node.ENTITY_REFERENCE_NODE))) {
 145  0 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
 146    "The node cannot be a child of attribute");
 147    }
 148    }
 149   
 150  0 public boolean hasChildNodes() {
 151  0 return DOMNodeHelper.hasChildNodes(this);
 152    }
 153   
 154  0 public org.w3c.dom.Node cloneNode(boolean deep) {
 155  0 return DOMNodeHelper.cloneNode(this, deep);
 156    }
 157   
 158  0 public void normalize() {
 159  0 DOMNodeHelper.normalize(this);
 160    }
 161   
 162  0 public boolean isSupported(String feature, String version) {
 163  0 return DOMNodeHelper.isSupported(this, feature, version);
 164    }
 165   
 166  0 public boolean hasAttributes() {
 167  0 return DOMNodeHelper.hasAttributes(this);
 168    }
 169   
 170    // org.w3c.dom.Attr interface
 171    // -------------------------------------------------------------------------
 172    // public String getName();
 173  0 public boolean getSpecified() {
 174  0 return true;
 175    }
 176   
 177    // public String getValue();
 178    // public void setValue(String value) throws DOMException;
 179  0 public org.w3c.dom.Element getOwnerElement() {
 180  0 return DOMNodeHelper.asDOMElement(getParent());
 181    }
 182    }
 183   
 184    /*
 185    * Redistribution and use of this software and associated documentation
 186    * ("Software"), with or without modification, are permitted provided that the
 187    * following conditions are met:
 188    *
 189    * 1. Redistributions of source code must retain copyright statements and
 190    * notices. Redistributions must also contain a copy of this document.
 191    *
 192    * 2. Redistributions in binary form must reproduce the above copyright notice,
 193    * this list of conditions and the following disclaimer in the documentation
 194    * and/or other materials provided with the distribution.
 195    *
 196    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 197    * from this Software without prior written permission of MetaStuff, Ltd. For
 198    * written permission, please contact dom4j-info@metastuff.com.
 199    *
 200    * 4. Products derived from this Software may not be called "DOM4J" nor may
 201    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 202    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 203    *
 204    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 205    *
 206    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 207    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 208    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 209    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 210    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 211    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 212    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 213    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 214    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 215    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 216    * POSSIBILITY OF SUCH DAMAGE.
 217    *
 218    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 219    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dom/DOMCDATA.html0000644000175000017500000022454510242117756020754 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 265   Methods: 38
NCLOC: 154   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DOMCDATA.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dom;
 9   
 10    import org.dom4j.CDATA;
 11    import org.dom4j.Element;
 12    import org.dom4j.tree.DefaultCDATA;
 13   
 14    import org.w3c.dom.DOMException;
 15    import org.w3c.dom.Document;
 16    import org.w3c.dom.NamedNodeMap;
 17    import org.w3c.dom.NodeList;
 18   
 19    /**
 20    * <p>
 21    * <code>DOMCDATA</code> implements a CDATA Section which supports the W3C DOM
 22    * API.
 23    * </p>
 24    *
 25    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 26    * @version $Revision: 1.12 $
 27    */
 28    public class DOMCDATA extends DefaultCDATA implements org.w3c.dom.CDATASection {
 29  0 public DOMCDATA(String text) {
 30  0 super(text);
 31    }
 32   
 33  0 public DOMCDATA(Element parent, String text) {
 34  0 super(parent, text);
 35    }
 36   
 37    // org.w3c.dom.Node interface
 38    // -------------------------------------------------------------------------
 39  0 public boolean supports(String feature, String version) {
 40  0 return DOMNodeHelper.supports(this, feature, version);
 41    }
 42   
 43  0 public String getNamespaceURI() {
 44  0 return DOMNodeHelper.getNamespaceURI(this);
 45    }
 46   
 47  0 public String getPrefix() {
 48  0 return DOMNodeHelper.getPrefix(this);
 49    }
 50   
 51  0 public void setPrefix(String prefix) throws DOMException {
 52  0 DOMNodeHelper.setPrefix(this, prefix);
 53    }
 54   
 55  0 public String getLocalName() {
 56  0 return DOMNodeHelper.getLocalName(this);
 57    }
 58   
 59  0 public String getNodeName() {
 60  0 return "#cdata-section";
 61    }
 62   
 63    // already part of API
 64    //
 65    // public short getNodeType();
 66  0 public String getNodeValue() throws DOMException {
 67  0 return DOMNodeHelper.getNodeValue(this);
 68    }
 69   
 70  0 public void setNodeValue(String nodeValue) throws DOMException {
 71  0 DOMNodeHelper.setNodeValue(this, nodeValue);
 72    }
 73   
 74  0 public org.w3c.dom.Node getParentNode() {
 75  0 return DOMNodeHelper.getParentNode(this);
 76    }
 77   
 78  0 public NodeList getChildNodes() {
 79  0 return DOMNodeHelper.getChildNodes(this);
 80    }
 81   
 82  0 public org.w3c.dom.Node getFirstChild() {
 83  0 return DOMNodeHelper.getFirstChild(this);
 84    }
 85   
 86  0 public org.w3c.dom.Node getLastChild() {
 87  0 return DOMNodeHelper.getLastChild(this);
 88    }
 89   
 90  0 public org.w3c.dom.Node getPreviousSibling() {
 91  0 return DOMNodeHelper.getPreviousSibling(this);
 92    }
 93   
 94  0 public org.w3c.dom.Node getNextSibling() {
 95  0 return DOMNodeHelper.getNextSibling(this);
 96    }
 97   
 98  0 public NamedNodeMap getAttributes() {
 99  0 return null;
 100    }
 101   
 102  0 public Document getOwnerDocument() {
 103  0 return DOMNodeHelper.getOwnerDocument(this);
 104    }
 105   
 106  0 public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
 107    org.w3c.dom.Node refChild) throws DOMException {
 108  0 checkNewChildNode(newChild);
 109   
 110  0 return DOMNodeHelper.insertBefore(this, newChild, refChild);
 111    }
 112   
 113  0 public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
 114    org.w3c.dom.Node oldChild) throws DOMException {
 115  0 checkNewChildNode(newChild);
 116   
 117  0 return DOMNodeHelper.replaceChild(this, newChild, oldChild);
 118    }
 119   
 120  0 public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
 121    throws DOMException {
 122  0 return DOMNodeHelper.removeChild(this, oldChild);
 123    }
 124   
 125  0 public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
 126    throws DOMException {
 127  0 checkNewChildNode(newChild);
 128   
 129  0 return DOMNodeHelper.appendChild(this, newChild);
 130    }
 131   
 132  0 private void checkNewChildNode(org.w3c.dom.Node newChild)
 133    throws DOMException {
 134  0 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
 135    "CDATASection nodes cannot have children");
 136    }
 137   
 138  0 public boolean hasChildNodes() {
 139  0 return DOMNodeHelper.hasChildNodes(this);
 140    }
 141   
 142  0 public org.w3c.dom.Node cloneNode(boolean deep) {
 143  0 return DOMNodeHelper.cloneNode(this, deep);
 144    }
 145   
 146  0 public void normalize() {
 147  0 DOMNodeHelper.normalize(this);
 148    }
 149   
 150  0 public boolean isSupported(String feature, String version) {
 151  0 return DOMNodeHelper.isSupported(this, feature, version);
 152    }
 153   
 154  0 public boolean hasAttributes() {
 155  0 return DOMNodeHelper.hasAttributes(this);
 156    }
 157   
 158    // org.w3c.dom.CharacterData interface
 159    // -------------------------------------------------------------------------
 160  0 public String getData() throws DOMException {
 161  0 return DOMNodeHelper.getData(this);
 162    }
 163   
 164  0 public void setData(String data) throws DOMException {
 165  0 DOMNodeHelper.setData(this, data);
 166    }
 167   
 168  0 public int getLength() {
 169  0 return DOMNodeHelper.getLength(this);
 170    }
 171   
 172  0 public String substringData(int offset, int count) throws DOMException {
 173  0 return DOMNodeHelper.substringData(this, offset, count);
 174    }
 175   
 176  0 public void appendData(String arg) throws DOMException {
 177  0 DOMNodeHelper.appendData(this, arg);
 178    }
 179   
 180  0 public void insertData(int offset, String arg) throws DOMException {
 181  0 DOMNodeHelper.insertData(this, offset, arg);
 182    }
 183   
 184  0 public void deleteData(int offset, int count) throws DOMException {
 185  0 DOMNodeHelper.deleteData(this, offset, count);
 186    }
 187   
 188  0 public void replaceData(int offset, int count, String arg)
 189    throws DOMException {
 190  0 DOMNodeHelper.replaceData(this, offset, count, arg);
 191    }
 192   
 193    // org.w3c.dom.Text interface
 194    // -------------------------------------------------------------------------
 195  0 public org.w3c.dom.Text splitText(int offset) throws DOMException {
 196  0 if (isReadOnly()) {
 197  0 throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
 198    "CharacterData node is read only: " + this);
 199    } else {
 200  0 String text = getText();
 201  0 int length = (text != null) ? text.length() : 0;
 202   
 203  0 if ((offset < 0) || (offset >= length)) {
 204  0 throw new DOMException(DOMException.INDEX_SIZE_ERR,
 205    "No text at offset: " + offset);
 206    } else {
 207  0 String start = text.substring(0, offset);
 208  0 String rest = text.substring(offset);
 209  0 setText(start);
 210   
 211  0 Element parent = getParent();
 212  0 CDATA newText = createCDATA(rest);
 213   
 214  0 if (parent != null) {
 215  0 parent.add(newText);
 216    }
 217   
 218  0 return DOMNodeHelper.asDOMText(newText);
 219    }
 220    }
 221    }
 222   
 223    // Implementation methods
 224    // -------------------------------------------------------------------------
 225  0 protected CDATA createCDATA(String text) {
 226  0 return new DOMCDATA(text);
 227    }
 228    }
 229   
 230    /*
 231    * Redistribution and use of this software and associated documentation
 232    * ("Software"), with or without modification, are permitted provided that the
 233    * following conditions are met:
 234    *
 235    * 1. Redistributions of source code must retain copyright statements and
 236    * notices. Redistributions must also contain a copy of this document.
 237    *
 238    * 2. Redistributions in binary form must reproduce the above copyright notice,
 239    * this list of conditions and the following disclaimer in the documentation
 240    * and/or other materials provided with the distribution.
 241    *
 242    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 243    * from this Software without prior written permission of MetaStuff, Ltd. For
 244    * written permission, please contact dom4j-info@metastuff.com.
 245    *
 246    * 4. Products derived from this Software may not be called "DOM4J" nor may
 247    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 248    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 249    *
 250    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 251    *
 252    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 253    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 254    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 255    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 256    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 257    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 258    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 259    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 260    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 261    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 262    * POSSIBILITY OF SUCH DAMAGE.
 263    *
 264    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 265    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dom/DOMEntityReference.html0000644000175000017500000016227610242117737023234 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 206   Methods: 29
NCLOC: 113   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DOMEntityReference.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dom;
 9   
 10    import org.dom4j.Element;
 11    import org.dom4j.tree.DefaultEntity;
 12   
 13    import org.w3c.dom.DOMException;
 14    import org.w3c.dom.Document;
 15    import org.w3c.dom.NamedNodeMap;
 16    import org.w3c.dom.NodeList;
 17   
 18    /**
 19    * <p>
 20    * <code>DOMEntity</code> implements a Entity node which supports the W3C DOM
 21    * API.
 22    * </p>
 23    *
 24    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 25    * @version $Revision: 1.12 $
 26    */
 27    public class DOMEntityReference extends DefaultEntity implements
 28    org.w3c.dom.EntityReference {
 29  0 public DOMEntityReference(String name) {
 30  0 super(name);
 31    }
 32   
 33  0 public DOMEntityReference(String name, String text) {
 34  0 super(name, text);
 35    }
 36   
 37  0 public DOMEntityReference(Element parent, String name, String text) {
 38  0 super(parent, name, text);
 39    }
 40   
 41    // org.w3c.dom.Node interface
 42    // -------------------------------------------------------------------------
 43  0 public boolean supports(String feature, String version) {
 44  0 return DOMNodeHelper.supports(this, feature, version);
 45    }
 46   
 47  0 public String getNamespaceURI() {
 48  0 return DOMNodeHelper.getNamespaceURI(this);
 49    }
 50   
 51  0 public String getPrefix() {
 52  0 return DOMNodeHelper.getPrefix(this);
 53    }
 54   
 55  0 public void setPrefix(String prefix) throws DOMException {
 56  0 DOMNodeHelper.setPrefix(this, prefix);
 57    }
 58   
 59  0 public String getLocalName() {
 60  0 return DOMNodeHelper.getLocalName(this);
 61    }
 62   
 63  0 public String getNodeName() {
 64  0 return getName();
 65    }
 66   
 67    // already part of API
 68    //
 69    // public short getNodeType();
 70  0 public String getNodeValue() throws DOMException {
 71  0 return null;
 72    }
 73   
 74  0 public void setNodeValue(String nodeValue) throws DOMException {
 75    }
 76   
 77  0 public org.w3c.dom.Node getParentNode() {
 78  0 return DOMNodeHelper.getParentNode(this);
 79    }
 80   
 81  0 public NodeList getChildNodes() {
 82  0 return DOMNodeHelper.getChildNodes(this);
 83    }
 84   
 85  0 public org.w3c.dom.Node getFirstChild() {
 86  0 return DOMNodeHelper.getFirstChild(this);
 87    }
 88   
 89  0 public org.w3c.dom.Node getLastChild() {
 90  0 return DOMNodeHelper.getLastChild(this);
 91    }
 92   
 93  0 public org.w3c.dom.Node getPreviousSibling() {
 94  0 return DOMNodeHelper.getPreviousSibling(this);
 95    }
 96   
 97  0 public org.w3c.dom.Node getNextSibling() {
 98  0 return DOMNodeHelper.getNextSibling(this);
 99    }
 100   
 101  0 public NamedNodeMap getAttributes() {
 102  0 return null;
 103    }
 104   
 105  0 public Document getOwnerDocument() {
 106  0 return DOMNodeHelper.getOwnerDocument(this);
 107    }
 108   
 109  0 public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
 110    org.w3c.dom.Node refChild) throws DOMException {
 111  0 checkNewChildNode(newChild);
 112   
 113  0 return DOMNodeHelper.insertBefore(this, newChild, refChild);
 114    }
 115   
 116  0 public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
 117    org.w3c.dom.Node oldChild) throws DOMException {
 118  0 checkNewChildNode(newChild);
 119   
 120  0 return DOMNodeHelper.replaceChild(this, newChild, oldChild);
 121    }
 122   
 123  0 public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
 124    throws DOMException {
 125  0 return DOMNodeHelper.removeChild(this, oldChild);
 126    }
 127   
 128  0 public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
 129    throws DOMException {
 130  0 checkNewChildNode(newChild);
 131   
 132  0 return DOMNodeHelper.appendChild(this, newChild);
 133    }
 134   
 135  0 private void checkNewChildNode(org.w3c.dom.Node newChild)
 136    throws DOMException {
 137  0 final int nodeType = newChild.getNodeType();
 138   
 139  0 if (!((nodeType == org.w3c.dom.Node.ELEMENT_NODE)
 140    || (nodeType == org.w3c.dom.Node.TEXT_NODE)
 141    || (nodeType == org.w3c.dom.Node.COMMENT_NODE)
 142    || (nodeType == org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE)
 143    || (nodeType == org.w3c.dom.Node.CDATA_SECTION_NODE)
 144    || (nodeType == org.w3c.dom.Node.ENTITY_REFERENCE_NODE))) {
 145  0 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
 146    "Given node cannot be a child of an entity " + "reference");
 147    }
 148    }
 149   
 150  0 public boolean hasChildNodes() {
 151  0 return DOMNodeHelper.hasChildNodes(this);
 152    }
 153   
 154  0 public org.w3c.dom.Node cloneNode(boolean deep) {
 155  0 return DOMNodeHelper.cloneNode(this, deep);
 156    }
 157   
 158  0 public void normalize() {
 159  0 DOMNodeHelper.normalize(this);
 160    }
 161   
 162  0 public boolean isSupported(String feature, String version) {
 163  0 return DOMNodeHelper.isSupported(this, feature, version);
 164    }
 165   
 166  0 public boolean hasAttributes() {
 167  0 return DOMNodeHelper.hasAttributes(this);
 168    }
 169    }
 170   
 171    /*
 172    * Redistribution and use of this software and associated documentation
 173    * ("Software"), with or without modification, are permitted provided that the
 174    * following conditions are met:
 175    *
 176    * 1. Redistributions of source code must retain copyright statements and
 177    * notices. Redistributions must also contain a copy of this document.
 178    *
 179    * 2. Redistributions in binary form must reproduce the above copyright notice,
 180    * this list of conditions and the following disclaimer in the documentation
 181    * and/or other materials provided with the distribution.
 182    *
 183    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 184    * from this Software without prior written permission of MetaStuff, Ltd. For
 185    * written permission, please contact dom4j-info@metastuff.com.
 186    *
 187    * 4. Products derived from this Software may not be called "DOM4J" nor may
 188    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 189    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 190    *
 191    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 192    *
 193    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 194    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 195    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 196    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 197    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 198    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 199    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 200    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 201    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 202    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 203    * POSSIBILITY OF SUCH DAMAGE.
 204    *
 205    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 206    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dom/DOMDocumentFactory.html0000644000175000017500000016737610242117722023247 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 216   Methods: 18
NCLOC: 122   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DOMDocumentFactory.java 0% 46,5% 44,4% 41,8%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dom;
 9   
 10    import java.util.Map;
 11   
 12    import org.dom4j.Attribute;
 13    import org.dom4j.CDATA;
 14    import org.dom4j.Comment;
 15    import org.dom4j.Document;
 16    import org.dom4j.DocumentFactory;
 17    import org.dom4j.DocumentType;
 18    import org.dom4j.Element;
 19    import org.dom4j.Entity;
 20    import org.dom4j.Namespace;
 21    import org.dom4j.ProcessingInstruction;
 22    import org.dom4j.QName;
 23    import org.dom4j.Text;
 24    import org.dom4j.util.SingletonStrategy;
 25    import org.w3c.dom.DOMException;
 26   
 27    /**
 28    * <p>
 29    * <code>DOMDocumentFactory</code> is a factory of DOM4J objects which
 30    * implement the W3C DOM API.
 31    * </p>
 32    *
 33    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 34    * @version $Revision: 1.21 $
 35    */
 36    public class DOMDocumentFactory extends DocumentFactory implements
 37    org.w3c.dom.DOMImplementation {
 38   
 39    /** The Singleton instance */
 40    private static SingletonStrategy singleton = null;
 41   
 42    static {
 43  3 try {
 44  3 String defaultSingletonClass = "org.dom4j.util.SimpleSingleton";
 45  3 Class clazz = null;
 46  3 try {
 47  3 String singletonClass = defaultSingletonClass;
 48  3 singletonClass = System.getProperty(
 49    "org.dom4j.dom.DOMDocumentFactory.singleton.strategy",
 50    singletonClass);
 51  3 clazz = Class.forName(singletonClass);
 52    } catch (Exception exc1) {
 53  0 try {
 54  0 String singletonClass = defaultSingletonClass;
 55  0 clazz = Class.forName(singletonClass);
 56    } catch (Exception exc2) {
 57    }
 58    }
 59  3 singleton = (SingletonStrategy) clazz.newInstance();
 60  3 singleton.setSingletonClassName(DOMDocumentFactory.class.getName());
 61    } catch (Exception exc3) {
 62    }
 63    }
 64   
 65    /**
 66    * <p>
 67    * Access to the singleton instance of this factory.
 68    * </p>
 69    *
 70    * @return the default singleon instance
 71    */
 72  12 public static DocumentFactory getInstance() {
 73  12 DOMDocumentFactory fact = (DOMDocumentFactory) singleton.instance();
 74  12 return fact;
 75    }
 76   
 77    // Factory methods
 78  6 public Document createDocument() {
 79  6 DOMDocument answer = new DOMDocument();
 80  6 answer.setDocumentFactory(this);
 81   
 82  6 return answer;
 83    }
 84   
 85  0 public DocumentType createDocType(String name, String publicId,
 86    String systemId) {
 87  0 return new DOMDocumentType(name, publicId, systemId);
 88    }
 89   
 90  151 public Element createElement(QName qname) {
 91  151 return new DOMElement(qname);
 92    }
 93   
 94  0 public Element createElement(QName qname, int attributeCount) {
 95  0 return new DOMElement(qname, attributeCount);
 96    }
 97   
 98  114 public Attribute createAttribute(Element owner, QName qname, String value) {
 99  114 return new DOMAttribute(qname, value);
 100    }
 101   
 102  0 public CDATA createCDATA(String text) {
 103  0 return new DOMCDATA(text);
 104    }
 105   
 106  12 public Comment createComment(String text) {
 107  12 return new DOMComment(text);
 108    }
 109   
 110  307 public Text createText(String text) {
 111  307 return new DOMText(text);
 112    }
 113   
 114  0 public Entity createEntity(String name) {
 115  0 return new DOMEntityReference(name);
 116    }
 117   
 118  0 public Entity createEntity(String name, String text) {
 119  0 return new DOMEntityReference(name, text);
 120    }
 121   
 122  159 public Namespace createNamespace(String prefix, String uri) {
 123  159 return new DOMNamespace(prefix, uri);
 124    }
 125   
 126  12 public ProcessingInstruction createProcessingInstruction(String target,
 127    String data) {
 128  12 return new DOMProcessingInstruction(target, data);
 129    }
 130   
 131  0 public ProcessingInstruction createProcessingInstruction(String target,
 132    Map data) {
 133  0 return new DOMProcessingInstruction(target, data);
 134    }
 135   
 136    // org.w3c.dom.DOMImplementation interface
 137  0 public boolean hasFeature(String feat, String version) {
 138  0 if ("XML".equalsIgnoreCase(feat) || "Core".equalsIgnoreCase(feat)) {
 139  0 return ((version == null) || (version.length() == 0)
 140    || "1.0".equals(version) || "2.0".equals(version));
 141    }
 142   
 143  0 return false;
 144    }
 145   
 146  0 public org.w3c.dom.DocumentType createDocumentType(String qualifiedName,
 147    String publicId, String systemId) throws DOMException {
 148  0 return new DOMDocumentType(qualifiedName, publicId, systemId);
 149    }
 150   
 151  0 public org.w3c.dom.Document createDocument(String namespaceURI,
 152    String qualifiedName, org.w3c.dom.DocumentType docType)
 153    throws org.w3c.dom.DOMException {
 154  0 DOMDocument document;
 155   
 156  0 if (docType != null) {
 157  0 DOMDocumentType documentType = asDocumentType(docType);
 158  0 document = new DOMDocument(documentType);
 159    } else {
 160  0 document = new DOMDocument();
 161    }
 162   
 163  0 document.addElement(createQName(qualifiedName, namespaceURI));
 164   
 165  0 return document;
 166    }
 167   
 168    // Implementation methods
 169  0 protected DOMDocumentType asDocumentType(org.w3c.dom.DocumentType docType) {
 170  0 if (docType instanceof DOMDocumentType) {
 171  0 return (DOMDocumentType) docType;
 172    } else {
 173  0 return new DOMDocumentType(docType.getName(),
 174    docType.getPublicId(), docType.getSystemId());
 175    }
 176    }
 177    }
 178   
 179   
 180   
 181    /*
 182    * Redistribution and use of this software and associated documentation
 183    * ("Software"), with or without modification, are permitted provided that the
 184    * following conditions are met:
 185    *
 186    * 1. Redistributions of source code must retain copyright statements and
 187    * notices. Redistributions must also contain a copy of this document.
 188    *
 189    * 2. Redistributions in binary form must reproduce the above copyright notice,
 190    * this list of conditions and the following disclaimer in the documentation
 191    * and/or other materials provided with the distribution.
 192    *
 193    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 194    * from this Software without prior written permission of MetaStuff, Ltd. For
 195    * written permission, please contact dom4j-info@metastuff.com.
 196    *
 197    * 4. Products derived from this Software may not be called "DOM4J" nor may
 198    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 199    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 200    *
 201    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 202    *
 203    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 204    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 205    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 206    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 207    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 208    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 209    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 210    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 211    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 212    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 213    * POSSIBILITY OF SUCH DAMAGE.
 214    *
 215    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 216    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dom/DOMAttributeNodeMap.html0000644000175000017500000011147510242117617023340 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 129   Methods: 10
NCLOC: 58   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DOMAttributeNodeMap.java 0% 10% 20% 10,5%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dom;
 9   
 10    import org.w3c.dom.Attr;
 11    import org.w3c.dom.DOMException;
 12    import org.w3c.dom.Node;
 13   
 14    /**
 15    * <p>
 16    * <code>DOMAttributeNodeMap</code> implements a W3C NameNodeMap for the
 17    * attributes of an element.
 18    * </p>
 19    *
 20    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 21    * @version $Revision: 1.8 $
 22    */
 23    public class DOMAttributeNodeMap implements org.w3c.dom.NamedNodeMap {
 24    private DOMElement element;
 25   
 26  35 public DOMAttributeNodeMap(DOMElement element) {
 27  35 this.element = element;
 28    }
 29   
 30    // org.w3c.dom.NamedNodeMap interface
 31    // -------------------------------------------------------------------------
 32  0 public void foo() throws DOMException {
 33  0 DOMNodeHelper.notSupported();
 34    }
 35   
 36  0 public Node getNamedItem(String name) {
 37  0 return element.getAttributeNode(name);
 38    }
 39   
 40  0 public Node setNamedItem(Node arg) throws DOMException {
 41  0 if (arg instanceof Attr) {
 42  0 return element.setAttributeNode((org.w3c.dom.Attr) arg);
 43    } else {
 44  0 throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
 45    "Node is not an Attr: " + arg);
 46    }
 47    }
 48   
 49  0 public Node removeNamedItem(String name) throws DOMException {
 50  0 org.w3c.dom.Attr attr = element.getAttributeNode(name);
 51   
 52  0 if (attr == null) {
 53  0 throw new DOMException(DOMException.NOT_FOUND_ERR,
 54    "No attribute named " + name);
 55    }
 56   
 57  0 return element.removeAttributeNode(attr);
 58    }
 59   
 60  0 public Node item(int index) {
 61  0 return DOMNodeHelper.asDOMAttr(element.attribute(index));
 62    }
 63   
 64  35 public int getLength() {
 65  35 return element.attributeCount();
 66    }
 67   
 68  0 public Node getNamedItemNS(String namespaceURI, String localName) {
 69  0 return element.getAttributeNodeNS(namespaceURI, localName);
 70    }
 71   
 72  0 public Node setNamedItemNS(Node arg) throws DOMException {
 73  0 if (arg instanceof Attr) {
 74  0 return element.setAttributeNodeNS((org.w3c.dom.Attr) arg);
 75    } else {
 76  0 throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
 77    "Node is not an Attr: " + arg);
 78    }
 79    }
 80   
 81  0 public Node removeNamedItemNS(String namespaceURI, String localName)
 82    throws DOMException {
 83  0 org.w3c.dom.Attr attr = element.getAttributeNodeNS(namespaceURI,
 84    localName);
 85   
 86  0 if (attr != null) {
 87  0 return element.removeAttributeNode(attr);
 88    }
 89   
 90  0 return attr;
 91    }
 92    }
 93   
 94    /*
 95    * Redistribution and use of this software and associated documentation
 96    * ("Software"), with or without modification, are permitted provided that the
 97    * following conditions are met:
 98    *
 99    * 1. Redistributions of source code must retain copyright statements and
 100    * notices. Redistributions must also contain a copy of this document.
 101    *
 102    * 2. Redistributions in binary form must reproduce the above copyright notice,
 103    * this list of conditions and the following disclaimer in the documentation
 104    * and/or other materials provided with the distribution.
 105    *
 106    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 107    * from this Software without prior written permission of MetaStuff, Ltd. For
 108    * written permission, please contact dom4j-info@metastuff.com.
 109    *
 110    * 4. Products derived from this Software may not be called "DOM4J" nor may
 111    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 112    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 113    *
 114    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 115    *
 116    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 117    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 118    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 119    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 120    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 121    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 122    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 123    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 124    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 125    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 126    * POSSIBILITY OF SUCH DAMAGE.
 127    *
 128    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 129    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dom/DOMComment.html0000644000175000017500000017767210242117713021543 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 227   Methods: 36
NCLOC: 127   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DOMComment.java - 2,6% 2,8% 2,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dom;
 9   
 10    import org.dom4j.Element;
 11    import org.dom4j.tree.DefaultComment;
 12   
 13    import org.w3c.dom.DOMException;
 14    import org.w3c.dom.Document;
 15    import org.w3c.dom.NamedNodeMap;
 16    import org.w3c.dom.NodeList;
 17   
 18    /**
 19    * <p>
 20    * <code>DOMText</code> implements a Text node which supports the W3C DOM API.
 21    * </p>
 22    *
 23    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 24    * @version $Revision: 1.12 $
 25    */
 26    public class DOMComment extends DefaultComment implements org.w3c.dom.Comment {
 27  12 public DOMComment(String text) {
 28  12 super(text);
 29    }
 30   
 31  0 public DOMComment(Element parent, String text) {
 32  0 super(parent, text);
 33    }
 34   
 35    // org.w3c.dom.Node interface
 36    // -------------------------------------------------------------------------
 37  0 public boolean supports(String feature, String version) {
 38  0 return DOMNodeHelper.supports(this, feature, version);
 39    }
 40   
 41  0 public String getNamespaceURI() {
 42  0 return DOMNodeHelper.getNamespaceURI(this);
 43    }
 44   
 45  0 public String getPrefix() {
 46  0 return DOMNodeHelper.getPrefix(this);
 47    }
 48   
 49  0 public void setPrefix(String prefix) throws DOMException {
 50  0 DOMNodeHelper.setPrefix(this, prefix);
 51    }
 52   
 53  0 public String getLocalName() {
 54  0 return DOMNodeHelper.getLocalName(this);
 55    }
 56   
 57  0 public String getNodeName() {
 58  0 return "#comment";
 59    }
 60   
 61    // already part of API
 62    //
 63    // public short getNodeType();
 64  0 public String getNodeValue() throws DOMException {
 65  0 return DOMNodeHelper.getNodeValue(this);
 66    }
 67   
 68  0 public void setNodeValue(String nodeValue) throws DOMException {
 69  0 DOMNodeHelper.setNodeValue(this, nodeValue);
 70    }
 71   
 72  0 public org.w3c.dom.Node getParentNode() {
 73  0 return DOMNodeHelper.getParentNode(this);
 74    }
 75   
 76  0 public NodeList getChildNodes() {
 77  0 return DOMNodeHelper.getChildNodes(this);
 78    }
 79   
 80  0 public org.w3c.dom.Node getFirstChild() {
 81  0 return DOMNodeHelper.getFirstChild(this);
 82    }
 83   
 84  0 public org.w3c.dom.Node getLastChild() {
 85  0 return DOMNodeHelper.getLastChild(this);
 86    }
 87   
 88  0 public org.w3c.dom.Node getPreviousSibling() {
 89  0 return DOMNodeHelper.getPreviousSibling(this);
 90    }
 91   
 92  0 public org.w3c.dom.Node getNextSibling() {
 93  0 return DOMNodeHelper.getNextSibling(this);
 94    }
 95   
 96  0 public NamedNodeMap getAttributes() {
 97  0 return null;
 98    }
 99   
 100  0 public Document getOwnerDocument() {
 101  0 return DOMNodeHelper.getOwnerDocument(this);
 102    }
 103   
 104  0 public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
 105    org.w3c.dom.Node refChild) throws DOMException {
 106  0 checkNewChildNode(newChild);
 107   
 108  0 return DOMNodeHelper.insertBefore(this, newChild, refChild);
 109    }
 110   
 111  0 public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
 112    org.w3c.dom.Node oldChild) throws DOMException {
 113  0 checkNewChildNode(newChild);
 114   
 115  0 return DOMNodeHelper.replaceChild(this, newChild, oldChild);
 116    }
 117   
 118  0 public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
 119    throws DOMException {
 120  0 return DOMNodeHelper.removeChild(this, oldChild);
 121    }
 122   
 123  0 public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
 124    throws DOMException {
 125  0 checkNewChildNode(newChild);
 126   
 127  0 return DOMNodeHelper.appendChild(this, newChild);
 128    }
 129   
 130  0 private void checkNewChildNode(org.w3c.dom.Node newChild)
 131    throws DOMException {
 132  0 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
 133    "Comment nodes cannot have children");
 134    }
 135   
 136  0 public boolean hasChildNodes() {
 137  0 return DOMNodeHelper.hasChildNodes(this);
 138    }
 139   
 140  0 public org.w3c.dom.Node cloneNode(boolean deep) {
 141  0 return DOMNodeHelper.cloneNode(this, deep);
 142    }
 143   
 144  0 public void normalize() {
 145  0 DOMNodeHelper.normalize(this);
 146    }
 147   
 148  0 public boolean isSupported(String feature, String version) {
 149  0 return DOMNodeHelper.isSupported(this, feature, version);
 150    }
 151   
 152  0 public boolean hasAttributes() {
 153  0 return DOMNodeHelper.hasAttributes(this);
 154    }
 155   
 156    // org.w3c.dom.CharacterData interface
 157    // -------------------------------------------------------------------------
 158  0 public String getData() throws DOMException {
 159  0 return DOMNodeHelper.getData(this);
 160    }
 161   
 162  0 public void setData(String data) throws DOMException {
 163  0 DOMNodeHelper.setData(this, data);
 164    }
 165   
 166  0 public int getLength() {
 167  0 return DOMNodeHelper.getLength(this);
 168    }
 169   
 170  0 public String substringData(int offset, int count) throws DOMException {
 171  0 return DOMNodeHelper.substringData(this, offset, count);
 172    }
 173   
 174  0 public void appendData(String arg) throws DOMException {
 175  0 DOMNodeHelper.appendData(this, arg);
 176    }
 177   
 178  0 public void insertData(int offset, String arg) throws DOMException {
 179  0 DOMNodeHelper.insertData(this, offset, arg);
 180    }
 181   
 182  0 public void deleteData(int offset, int count) throws DOMException {
 183  0 DOMNodeHelper.deleteData(this, offset, count);
 184    }
 185   
 186  0 public void replaceData(int offset, int count, String arg)
 187    throws DOMException {
 188  0 DOMNodeHelper.replaceData(this, offset, count, arg);
 189    }
 190    }
 191   
 192    /*
 193    * Redistribution and use of this software and associated documentation
 194    * ("Software"), with or without modification, are permitted provided that the
 195    * following conditions are met:
 196    *
 197    * 1. Redistributions of source code must retain copyright statements and
 198    * notices. Redistributions must also contain a copy of this document.
 199    *
 200    * 2. Redistributions in binary form must reproduce the above copyright notice,
 201    * this list of conditions and the following disclaimer in the documentation
 202    * and/or other materials provided with the distribution.
 203    *
 204    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 205    * from this Software without prior written permission of MetaStuff, Ltd. For
 206    * written permission, please contact dom4j-info@metastuff.com.
 207    *
 208    * 4. Products derived from this Software may not be called "DOM4J" nor may
 209    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 210    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 211    *
 212    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 213    *
 214    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 215    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 216    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 217    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 218    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 219    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 220    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 221    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 222    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 223    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 224    * POSSIBILITY OF SUCH DAMAGE.
 225    *
 226    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 227    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dom/DOMNodeHelper.html0000644000175000017500000050361710242117556022163 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 583   Methods: 47
NCLOC: 402   Classes: 2
 
 Source file Conditionals Statements Methods TOTAL
DOMNodeHelper.java 11% 15,4% 21,3% 14,9%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dom;
 9   
 10    import java.util.List;
 11   
 12    import org.dom4j.Branch;
 13    import org.dom4j.CharacterData;
 14    import org.dom4j.Document;
 15    import org.dom4j.DocumentType;
 16    import org.dom4j.Element;
 17    import org.dom4j.Node;
 18   
 19    import org.w3c.dom.DOMException;
 20    import org.w3c.dom.NamedNodeMap;
 21    import org.w3c.dom.NodeList;
 22   
 23    /**
 24    * <p>
 25    * <code>DOMNodeHelper</code> contains a collection of utility methods for use
 26    * across Node implementations.
 27    * </p>
 28    *
 29    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 30    * @version $Revision: 1.20 $
 31    */
 32    public class DOMNodeHelper {
 33    public static final NodeList EMPTY_NODE_LIST = new EmptyNodeList();
 34   
 35  0 protected DOMNodeHelper() {
 36    }
 37   
 38    // Node API
 39    // -------------------------------------------------------------------------
 40  0 public static boolean supports(Node node, String feature, String version) {
 41  0 return false;
 42    }
 43   
 44  0 public static String getNamespaceURI(Node node) {
 45  0 return null;
 46    }
 47   
 48  0 public static String getPrefix(Node node) {
 49  0 return null;
 50    }
 51   
 52  0 public static String getLocalName(Node node) {
 53  0 return null;
 54    }
 55   
 56  0 public static void setPrefix(Node node, String prefix) throws DOMException {
 57  0 notSupported();
 58    }
 59   
 60  73 public static String getNodeValue(Node node) throws DOMException {
 61  73 return node.getText();
 62    }
 63   
 64  0 public static void setNodeValue(Node node, String nodeValue)
 65    throws DOMException {
 66  0 node.setText(nodeValue);
 67    }
 68   
 69  30 public static org.w3c.dom.Node getParentNode(Node node) {
 70  30 return asDOMNode(node.getParent());
 71    }
 72   
 73  0 public static NodeList getChildNodes(Node node) {
 74  0 return EMPTY_NODE_LIST;
 75    }
 76   
 77  0 public static org.w3c.dom.Node getFirstChild(Node node) {
 78  0 return null;
 79    }
 80   
 81  0 public static org.w3c.dom.Node getLastChild(Node node) {
 82  0 return null;
 83    }
 84   
 85  0 public static org.w3c.dom.Node getPreviousSibling(Node node) {
 86  0 Element parent = node.getParent();
 87   
 88  0 if (parent != null) {
 89  0 int index = parent.indexOf(node);
 90   
 91  0 if (index > 0) {
 92  0 Node previous = parent.node(index - 1);
 93   
 94  0 return asDOMNode(previous);
 95    }
 96    }
 97   
 98  0 return null;
 99    }
 100   
 101  0 public static org.w3c.dom.Node getNextSibling(Node node) {
 102  0 Element parent = node.getParent();
 103   
 104  0 if (parent != null) {
 105  0 int index = parent.indexOf(node);
 106   
 107  0 if (index >= 0) {
 108  0 if (++index < parent.nodeCount()) {
 109  0 Node next = parent.node(index);
 110   
 111  0 return asDOMNode(next);
 112    }
 113    }
 114    }
 115   
 116  0 return null;
 117    }
 118   
 119  0 public static NamedNodeMap getAttributes(Node node) {
 120  0 return null;
 121    }
 122   
 123  0 public static org.w3c.dom.Document getOwnerDocument(Node node) {
 124  0 return asDOMDocument(node.getDocument());
 125    }
 126   
 127  0 public static org.w3c.dom.Node insertBefore(Node node,
 128    org.w3c.dom.Node newChild, org.w3c.dom.Node refChild)
 129    throws DOMException {
 130  0 if (node instanceof Branch) {
 131  0 Branch branch = (Branch) node;
 132  0 List list = branch.content();
 133  0 int index = list.indexOf(refChild);
 134   
 135  0 if (index < 0) {
 136  0 branch.add((Node) newChild);
 137    } else {
 138  0 list.add(index, newChild);
 139    }
 140   
 141  0 return newChild;
 142    } else {
 143  0 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
 144    "Children not allowed for this node: " + node);
 145    }
 146    }
 147   
 148  2 public static org.w3c.dom.Node replaceChild(Node node,
 149    org.w3c.dom.Node newChild, org.w3c.dom.Node oldChild)
 150    throws DOMException {
 151  2 if (node instanceof Branch) {
 152  2 Branch branch = (Branch) node;
 153  2 List list = branch.content();
 154  2 int index = list.indexOf(oldChild);
 155   
 156  2 if (index < 0) {
 157  1 throw new DOMException(DOMException.NOT_FOUND_ERR,
 158    "Tried to replace a non existing child " + "for node: "
 159    + node);
 160    }
 161   
 162  1 list.set(index, newChild);
 163   
 164  1 return oldChild;
 165    } else {
 166  0 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
 167    "Children not allowed for this node: " + node);
 168    }
 169    }
 170   
 171  0 public static org.w3c.dom.Node removeChild(Node node,
 172    org.w3c.dom.Node oldChild) throws DOMException {
 173  0 if (node instanceof Branch) {
 174  0 Branch branch = (Branch) node;
 175  0 branch.remove((Node) oldChild);
 176   
 177  0 return oldChild;
 178    }
 179   
 180  0 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
 181    "Children not allowed for this node: " + node);
 182    }
 183   
 184  30 public static org.w3c.dom.Node appendChild(Node node,
 185    org.w3c.dom.Node newChild) throws DOMException {
 186  30 if (node instanceof Branch) {
 187  30 Branch branch = (Branch) node;
 188  30 org.w3c.dom.Node previousParent = newChild.getParentNode();
 189   
 190  30 if (previousParent != null) {
 191  0 previousParent.removeChild(newChild);
 192    }
 193   
 194  30 branch.add((Node) newChild);
 195   
 196  30 return newChild;
 197    }
 198   
 199  0 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
 200    "Children not allowed for this node: " + node);
 201    }
 202   
 203  0 public static boolean hasChildNodes(Node node) {
 204  0 return false;
 205    }
 206   
 207  1 public static org.w3c.dom.Node cloneNode(Node node, boolean deep) {
 208  1 return asDOMNode((Node) node.clone());
 209    }
 210   
 211  0 public static void normalize(Node node) {
 212  0 notSupported();
 213    }
 214   
 215  0 public static boolean isSupported(Node n, String feature, String version) {
 216  0 return false;
 217    }
 218   
 219  0 public static boolean hasAttributes(Node node) {
 220  0 if ((node != null) && node instanceof Element) {
 221  0 return ((Element) node).attributeCount() > 0;
 222    } else {
 223  0 return false;
 224    }
 225    }
 226   
 227    // CharacterData API
 228    // -------------------------------------------------------------------------
 229  0 public static String getData(CharacterData charData) throws DOMException {
 230  0 return charData.getText();
 231    }
 232   
 233  0 public static void setData(CharacterData charData, String data)
 234    throws DOMException {
 235  0 charData.setText(data);
 236    }
 237   
 238  0 public static int getLength(CharacterData charData) {
 239  0 String text = charData.getText();
 240   
 241  0 return (text != null) ? text.length() : 0;
 242    }
 243   
 244  0 public static String substringData(CharacterData charData, int offset,
 245    int count) throws DOMException {
 246  0 if (count < 0) {
 247  0 throw new DOMException(DOMException.INDEX_SIZE_ERR,
 248    "Illegal value for count: " + count);
 249    }
 250   
 251  0 String text = charData.getText();
 252  0 int length = (text != null) ? text.length() : 0;
 253   
 254  0 if ((offset < 0) || (offset >= length)) {
 255  0 throw new DOMException(DOMException.INDEX_SIZE_ERR,
 256    "No text at offset: " + offset);
 257    }
 258   
 259  0 if ((offset + count) > length) {
 260  0 return text.substring(offset);
 261    }
 262   
 263  0 return text.substring(offset, offset + count);
 264    }
 265   
 266  0 public static void appendData(CharacterData charData, String arg)
 267    throws DOMException {
 268  0 if (charData.isReadOnly()) {
 269  0 throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
 270    "CharacterData node is read only: " + charData);
 271    } else {
 272  0 String text = charData.getText();
 273   
 274  0 if (text == null) {
 275  0 charData.setText(text);
 276    } else {
 277  0 charData.setText(text + arg);
 278    }
 279    }
 280    }
 281   
 282  0 public static void insertData(CharacterData data, int offset, String arg)
 283    throws DOMException {
 284  0 if (data.isReadOnly()) {
 285  0 throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
 286    "CharacterData node is read only: " + data);
 287    } else {
 288  0 String text = data.getText();
 289   
 290  0 if (text == null) {
 291  0 data.setText(arg);
 292    } else {
 293  0 int length = text.length();
 294   
 295  0 if ((offset < 0) || (offset > length)) {
 296  0 throw new DOMException(DOMException.INDEX_SIZE_ERR,
 297    "No text at offset: " + offset);
 298    } else {
 299  0 StringBuffer buffer = new StringBuffer(text);
 300  0 buffer.insert(offset, arg);
 301  0 data.setText(buffer.toString());
 302    }
 303    }
 304    }
 305    }
 306   
 307  0 public static void deleteData(CharacterData charData, int offset, int count)
 308    throws DOMException {
 309  0 if (charData.isReadOnly()) {
 310  0 throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
 311    "CharacterData node is read only: " + charData);
 312    } else {
 313  0 if (count < 0) {
 314  0 throw new DOMException(DOMException.INDEX_SIZE_ERR,
 315    "Illegal value for count: " + count);
 316    }
 317   
 318  0 String text = charData.getText();
 319   
 320  0 if (text != null) {
 321  0 int length = text.length();
 322   
 323  0 if ((offset < 0) || (offset >= length)) {
 324  0 throw new DOMException(DOMException.INDEX_SIZE_ERR,
 325    "No text at offset: " + offset);
 326    } else {
 327  0 StringBuffer buffer = new StringBuffer(text);
 328  0 buffer.delete(offset, offset + count);
 329  0 charData.setText(buffer.toString());
 330    }
 331    }
 332    }
 333    }
 334   
 335  0 public static void replaceData(CharacterData charData, int offset,
 336    int count, String arg) throws DOMException {
 337  0 if (charData.isReadOnly()) {
 338  0 throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
 339    "CharacterData node is read only: " + charData);
 340    } else {
 341  0 if (count < 0) {
 342  0 throw new DOMException(DOMException.INDEX_SIZE_ERR,
 343    "Illegal value for count: " + count);
 344    }
 345   
 346  0 String text = charData.getText();
 347   
 348  0 if (text != null) {
 349  0 int length = text.length();
 350   
 351  0 if ((offset < 0) || (offset >= length)) {
 352  0 throw new DOMException(DOMException.INDEX_SIZE_ERR,
 353    "No text at offset: " + offset);
 354    } else {
 355  0 StringBuffer buffer = new StringBuffer(text);
 356  0 buffer.replace(offset, offset + count, arg);
 357  0 charData.setText(buffer.toString());
 358    }
 359    }
 360    }
 361    }
 362   
 363    // Branch API
 364    // -------------------------------------------------------------------------
 365  0 public static void appendElementsByTagName(List list, Branch parent,
 366    String name) {
 367  0 final boolean isStar = "*".equals(name);
 368   
 369  0 for (int i = 0, size = parent.nodeCount(); i < size; i++) {
 370  0 Node node = parent.node(i);
 371   
 372  0 if (node instanceof Element) {
 373  0 Element element = (Element) node;
 374   
 375  0 if (isStar || name.equals(element.getName())) {
 376  0 list.add(element);
 377    }
 378   
 379  0 appendElementsByTagName(list, element, name);
 380    }
 381    }
 382    }
 383   
 384  0 public static void appendElementsByTagNameNS(List list, Branch parent,
 385    String namespace, String localName) {
 386  0 final boolean isStarNS = "*".equals(namespace);
 387  0 final boolean isStar = "*".equals(localName);
 388   
 389  0 for (int i = 0, size = parent.nodeCount(); i < size; i++) {
 390  0 Node node = parent.node(i);
 391   
 392  0 if (node instanceof Element) {
 393  0 Element element = (Element) node;
 394   
 395  0 if ((isStarNS
 396    || (((namespace == null)
 397    || (namespace.length() == 0)) && ((element
 398    .getNamespaceURI() == null) || (element
 399    .getNamespaceURI().length() == 0)))
 400    || ((namespace != null) && namespace
 401    .equals(element.getNamespaceURI())))
 402    && (isStar || localName.equals(element.getName()))) {
 403  0 list.add(element);
 404    }
 405   
 406  0 appendElementsByTagNameNS(list, element, namespace, localName);
 407    }
 408    }
 409    }
 410   
 411    // Helper methods
 412    // -------------------------------------------------------------------------
 413  34 public static NodeList createNodeList(final List list) {
 414  34 return new NodeList() {
 415  112 public org.w3c.dom.Node item(int index) {
 416  112 if (index >= getLength()) {
 417    /*
 418    * From the NodeList specification: If index is greater than
 419    * or equal to the number of nodes in the list, this returns
 420    * null.
 421    */
 422  0 return null;
 423    } else {
 424  112 return DOMNodeHelper.asDOMNode((Node) list.get(index));
 425    }
 426    }
 427   
 428  145 public int getLength() {
 429  145 return list.size();
 430    }
 431    };
 432    }
 433   
 434  143 public static org.w3c.dom.Node asDOMNode(Node node) {
 435  143 if (node == null) {
 436  30 return null;
 437    }
 438   
 439  113 if (node instanceof org.w3c.dom.Node) {
 440  113 return (org.w3c.dom.Node) node;
 441    } else {
 442    // Use DOMWriter?
 443  0 System.out.println("Cannot convert: " + node
 444    + " into a W3C DOM Node");
 445  0 notSupported();
 446   
 447  0 return null;
 448    }
 449    }
 450   
 451  0 public static org.w3c.dom.Document asDOMDocument(Document document) {
 452  0 if (document == null) {
 453  0 return null;
 454    }
 455   
 456  0 if (document instanceof org.w3c.dom.Document) {
 457  0 return (org.w3c.dom.Document) document;
 458    } else {
 459    // Use DOMWriter?
 460  0 notSupported();
 461   
 462  0 return null;
 463    }
 464    }
 465   
 466  0 public static org.w3c.dom.DocumentType asDOMDocumentType(DocumentType dt) {
 467  0 if (dt == null) {
 468  0 return null;
 469    }
 470   
 471  0 if (dt instanceof org.w3c.dom.DocumentType) {
 472  0 return (org.w3c.dom.DocumentType) dt;
 473    } else {
 474    // Use DOMWriter?
 475  0 notSupported();
 476   
 477  0 return null;
 478    }
 479    }
 480   
 481  0 public static org.w3c.dom.Text asDOMText(CharacterData text) {
 482  0 if (text == null) {
 483  0 return null;
 484    }
 485   
 486  0 if (text instanceof org.w3c.dom.Text) {
 487  0 return (org.w3c.dom.Text) text;
 488    } else {
 489    // Use DOMWriter?
 490  0 notSupported();
 491   
 492  0 return null;
 493    }
 494    }
 495   
 496  3 public static org.w3c.dom.Element asDOMElement(Node element) {
 497  3 if (element == null) {
 498  0 return null;
 499    }
 500   
 501  3 if (element instanceof org.w3c.dom.Element) {
 502  3 return (org.w3c.dom.Element) element;
 503    } else {
 504    // Use DOMWriter?
 505  0 notSupported();
 506   
 507  0 return null;
 508    }
 509    }
 510   
 511  0 public static org.w3c.dom.Attr asDOMAttr(Node attribute) {
 512  0 if (attribute == null) {
 513  0 return null;
 514    }
 515   
 516  0 if (attribute instanceof org.w3c.dom.Attr) {
 517  0 return (org.w3c.dom.Attr) attribute;
 518    } else {
 519    // Use DOMWriter?
 520  0 notSupported();
 521   
 522  0 return null;
 523    }
 524    }
 525   
 526    /**
 527    * Called when a method has not been implemented yet
 528    *
 529    * @throws DOMException
 530    * DOCUMENT ME!
 531    */
 532  0 public static void notSupported() {
 533  0 throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
 534    "Not supported yet");
 535    }
 536   
 537    public static class EmptyNodeList implements NodeList {
 538  0 public org.w3c.dom.Node item(int index) {
 539  0 return null;
 540    }
 541   
 542  0 public int getLength() {
 543  0 return 0;
 544    }
 545    }
 546    }
 547   
 548    /*
 549    * Redistribution and use of this software and associated documentation
 550    * ("Software"), with or without modification, are permitted provided that the
 551    * following conditions are met:
 552    *
 553    * 1. Redistributions of source code must retain copyright statements and
 554    * notices. Redistributions must also contain a copy of this document.
 555    *
 556    * 2. Redistributions in binary form must reproduce the above copyright notice,
 557    * this list of conditions and the following disclaimer in the documentation
 558    * and/or other materials provided with the distribution.
 559    *
 560    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 561    * from this Software without prior written permission of MetaStuff, Ltd. For
 562    * written permission, please contact dom4j-info@metastuff.com.
 563    *
 564    * 4. Products derived from this Software may not be called "DOM4J" nor may
 565    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 566    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 567    *
 568    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 569    *
 570    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 571    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 572    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 573    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 574    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 575    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 576    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 577    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 578    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 579    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 580    * POSSIBILITY OF SUCH DAMAGE.
 581    *
 582    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 583    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dom/DOMDocumentType.html0000644000175000017500000017010410242117761022543 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 217   Methods: 34
NCLOC: 118   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DOMDocumentType.java - 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dom;
 9   
 10    import org.dom4j.tree.DefaultDocumentType;
 11   
 12    import org.w3c.dom.DOMException;
 13    import org.w3c.dom.Document;
 14    import org.w3c.dom.NamedNodeMap;
 15    import org.w3c.dom.NodeList;
 16   
 17    /**
 18    * <p>
 19    * <code>DOMDocumentType</code> implements a DocumentType node which supports
 20    * the W3C DOM API.
 21    * </p>
 22    *
 23    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 24    * @version $Revision: 1.11 $
 25    */
 26    public class DOMDocumentType extends DefaultDocumentType implements
 27    org.w3c.dom.DocumentType {
 28  0 public DOMDocumentType() {
 29    }
 30   
 31  0 public DOMDocumentType(String elementName, String systemID) {
 32  0 super(elementName, systemID);
 33    }
 34   
 35  0 public DOMDocumentType(String name, String publicID, String systemID) {
 36  0 super(name, publicID, systemID);
 37    }
 38   
 39    // org.w3c.dom.Node interface
 40    // -------------------------------------------------------------------------
 41  0 public boolean supports(String feature, String version) {
 42  0 return DOMNodeHelper.supports(this, feature, version);
 43    }
 44   
 45  0 public String getNamespaceURI() {
 46  0 return DOMNodeHelper.getNamespaceURI(this);
 47    }
 48   
 49  0 public String getPrefix() {
 50  0 return DOMNodeHelper.getPrefix(this);
 51    }
 52   
 53  0 public void setPrefix(String prefix) throws DOMException {
 54  0 DOMNodeHelper.setPrefix(this, prefix);
 55    }
 56   
 57  0 public String getLocalName() {
 58  0 return DOMNodeHelper.getLocalName(this);
 59    }
 60   
 61  0 public String getNodeName() {
 62  0 return getName();
 63    }
 64   
 65    // already part of API
 66    //
 67    // public short getNodeType();
 68  0 public String getNodeValue() throws DOMException {
 69  0 return null;
 70    }
 71   
 72  0 public void setNodeValue(String nodeValue) throws DOMException {
 73    }
 74   
 75  0 public org.w3c.dom.Node getParentNode() {
 76  0 return DOMNodeHelper.getParentNode(this);
 77    }
 78   
 79  0 public NodeList getChildNodes() {
 80  0 return DOMNodeHelper.getChildNodes(this);
 81    }
 82   
 83  0 public org.w3c.dom.Node getFirstChild() {
 84  0 return DOMNodeHelper.getFirstChild(this);
 85    }
 86   
 87  0 public org.w3c.dom.Node getLastChild() {
 88  0 return DOMNodeHelper.getLastChild(this);
 89    }
 90   
 91  0 public org.w3c.dom.Node getPreviousSibling() {
 92  0 return DOMNodeHelper.getPreviousSibling(this);
 93    }
 94   
 95  0 public org.w3c.dom.Node getNextSibling() {
 96  0 return DOMNodeHelper.getNextSibling(this);
 97    }
 98   
 99  0 public NamedNodeMap getAttributes() {
 100  0 return null;
 101    }
 102   
 103  0 public Document getOwnerDocument() {
 104  0 return DOMNodeHelper.getOwnerDocument(this);
 105    }
 106   
 107  0 public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
 108    org.w3c.dom.Node refChild) throws DOMException {
 109  0 checkNewChildNode(newChild);
 110   
 111  0 return DOMNodeHelper.insertBefore(this, newChild, refChild);
 112    }
 113   
 114  0 public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
 115    org.w3c.dom.Node oldChild) throws DOMException {
 116  0 checkNewChildNode(newChild);
 117   
 118  0 return DOMNodeHelper.replaceChild(this, newChild, oldChild);
 119    }
 120   
 121  0 public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
 122    throws DOMException {
 123  0 return DOMNodeHelper.removeChild(this, oldChild);
 124    }
 125   
 126  0 public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
 127    throws DOMException {
 128  0 checkNewChildNode(newChild);
 129   
 130  0 return DOMNodeHelper.appendChild(this, newChild);
 131    }
 132   
 133  0 private void checkNewChildNode(org.w3c.dom.Node newChild)
 134    throws DOMException {
 135  0 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
 136    "DocumentType nodes cannot have children");
 137    }
 138   
 139  0 public boolean hasChildNodes() {
 140  0 return DOMNodeHelper.hasChildNodes(this);
 141    }
 142   
 143  0 public org.w3c.dom.Node cloneNode(boolean deep) {
 144  0 return DOMNodeHelper.cloneNode(this, deep);
 145    }
 146   
 147  0 public void normalize() {
 148  0 DOMNodeHelper.normalize(this);
 149    }
 150   
 151  0 public boolean isSupported(String feature, String version) {
 152  0 return DOMNodeHelper.isSupported(this, feature, version);
 153    }
 154   
 155  0 public boolean hasAttributes() {
 156  0 return DOMNodeHelper.hasAttributes(this);
 157    }
 158   
 159    // org.w3c.dom.DocumentType interface
 160    // -------------------------------------------------------------------------
 161  0 public NamedNodeMap getEntities() {
 162  0 return null;
 163    }
 164   
 165  0 public NamedNodeMap getNotations() {
 166  0 return null;
 167    }
 168   
 169  0 public String getPublicId() {
 170  0 return getPublicID();
 171    }
 172   
 173  0 public String getSystemId() {
 174  0 return getSystemID();
 175    }
 176   
 177  0 public String getInternalSubset() {
 178  0 return getElementName();
 179    }
 180    }
 181   
 182    /*
 183    * Redistribution and use of this software and associated documentation
 184    * ("Software"), with or without modification, are permitted provided that the
 185    * following conditions are met:
 186    *
 187    * 1. Redistributions of source code must retain copyright statements and
 188    * notices. Redistributions must also contain a copy of this document.
 189    *
 190    * 2. Redistributions in binary form must reproduce the above copyright notice,
 191    * this list of conditions and the following disclaimer in the documentation
 192    * and/or other materials provided with the distribution.
 193    *
 194    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 195    * from this Software without prior written permission of MetaStuff, Ltd. For
 196    * written permission, please contact dom4j-info@metastuff.com.
 197    *
 198    * 4. Products derived from this Software may not be called "DOM4J" nor may
 199    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 200    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 201    *
 202    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 203    *
 204    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 205    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 206    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 207    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 208    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 209    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 210    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 211    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 212    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 213    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 214    * POSSIBILITY OF SUCH DAMAGE.
 215    *
 216    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 217    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dom/DOMDocument.html0000644000175000017500000027360510242117764021716 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 341   Methods: 50
NCLOC: 213   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DOMDocument.java 33,3% 22,2% 22% 22,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dom;
 9   
 10    import java.util.ArrayList;
 11   
 12    import org.dom4j.DocumentFactory;
 13    import org.dom4j.QName;
 14    import org.dom4j.tree.DefaultDocument;
 15   
 16    import org.w3c.dom.Attr;
 17    import org.w3c.dom.CDATASection;
 18    import org.w3c.dom.DOMException;
 19    import org.w3c.dom.Document;
 20    import org.w3c.dom.EntityReference;
 21    import org.w3c.dom.NamedNodeMap;
 22    import org.w3c.dom.NodeList;
 23    import org.w3c.dom.ProcessingInstruction;
 24   
 25    /**
 26    * <p>
 27    * <code>DOMDocument</code> implements an XML document which supports the W3C
 28    * DOM API.
 29    * </p>
 30    *
 31    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 32    * @version $Revision: 1.17 $
 33    */
 34    public class DOMDocument extends DefaultDocument implements Document {
 35    /** The <code>DocumentFactory</code> instance used by default */
 36    private static final DOMDocumentFactory DOCUMENT_FACTORY
 37    = (DOMDocumentFactory) DOMDocumentFactory.getInstance();
 38   
 39  8 public DOMDocument() {
 40  8 init();
 41    }
 42   
 43  2 public DOMDocument(String name) {
 44  2 super(name);
 45  2 init();
 46    }
 47   
 48  0 public DOMDocument(DOMElement rootElement) {
 49  0 super(rootElement);
 50  0 init();
 51    }
 52   
 53  0 public DOMDocument(DOMDocumentType docType) {
 54  0 super(docType);
 55  0 init();
 56    }
 57   
 58  0 public DOMDocument(DOMElement rootElement, DOMDocumentType docType) {
 59  0 super(rootElement, docType);
 60  0 init();
 61    }
 62   
 63  0 public DOMDocument(String name, DOMElement rootElement,
 64    DOMDocumentType docType) {
 65  0 super(name, rootElement, docType);
 66  0 init();
 67    }
 68   
 69  10 private void init() {
 70  10 setDocumentFactory(DOCUMENT_FACTORY);
 71    }
 72   
 73    // org.w3c.dom.Node interface
 74    // -------------------------------------------------------------------------
 75  0 public boolean supports(String feature, String version) {
 76  0 return DOMNodeHelper.supports(this, feature, version);
 77    }
 78   
 79  0 public String getNamespaceURI() {
 80  0 return DOMNodeHelper.getNamespaceURI(this);
 81    }
 82   
 83  0 public String getPrefix() {
 84  0 return DOMNodeHelper.getPrefix(this);
 85    }
 86   
 87  0 public void setPrefix(String prefix) throws DOMException {
 88  0 DOMNodeHelper.setPrefix(this, prefix);
 89    }
 90   
 91  0 public String getLocalName() {
 92  0 return DOMNodeHelper.getLocalName(this);
 93    }
 94   
 95  0 public String getNodeName() {
 96  0 return "#document";
 97    }
 98   
 99    // already part of API
 100    //
 101    // public short getNodeType();
 102  0 public String getNodeValue() throws DOMException {
 103  0 return null;
 104    }
 105   
 106  0 public void setNodeValue(String nodeValue) throws DOMException {
 107    }
 108   
 109  0 public org.w3c.dom.Node getParentNode() {
 110  0 return DOMNodeHelper.getParentNode(this);
 111    }
 112   
 113  0 public NodeList getChildNodes() {
 114  0 return DOMNodeHelper.createNodeList(content());
 115    }
 116   
 117  0 public org.w3c.dom.Node getFirstChild() {
 118  0 return DOMNodeHelper.asDOMNode(node(0));
 119    }
 120   
 121  0 public org.w3c.dom.Node getLastChild() {
 122  0 return DOMNodeHelper.asDOMNode(node(nodeCount() - 1));
 123    }
 124   
 125  0 public org.w3c.dom.Node getPreviousSibling() {
 126  0 return DOMNodeHelper.getPreviousSibling(this);
 127    }
 128   
 129  0 public org.w3c.dom.Node getNextSibling() {
 130  0 return DOMNodeHelper.getNextSibling(this);
 131    }
 132   
 133  0 public NamedNodeMap getAttributes() {
 134  0 return null;
 135    }
 136   
 137  0 public org.w3c.dom.Document getOwnerDocument() {
 138  0 return null;
 139    }
 140   
 141  0 public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
 142    org.w3c.dom.Node refChild) throws DOMException {
 143  0 checkNewChildNode(newChild);
 144   
 145  0 return DOMNodeHelper.insertBefore(this, newChild, refChild);
 146    }
 147   
 148  0 public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
 149    org.w3c.dom.Node oldChild) throws DOMException {
 150  0 checkNewChildNode(newChild);
 151   
 152  0 return DOMNodeHelper.replaceChild(this, newChild, oldChild);
 153    }
 154   
 155  0 public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
 156    throws DOMException {
 157  0 return DOMNodeHelper.removeChild(this, oldChild);
 158    }
 159   
 160  4 public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
 161    throws DOMException {
 162  4 checkNewChildNode(newChild);
 163   
 164  4 return DOMNodeHelper.appendChild(this, newChild);
 165    }
 166   
 167  4 private void checkNewChildNode(org.w3c.dom.Node newChild)
 168    throws DOMException {
 169  4 final int nodeType = newChild.getNodeType();
 170   
 171  4 if (!((nodeType == org.w3c.dom.Node.ELEMENT_NODE)
 172    || (nodeType == org.w3c.dom.Node.COMMENT_NODE)
 173    || (nodeType == org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE)
 174    || (nodeType == org.w3c.dom.Node.DOCUMENT_TYPE_NODE))) {
 175  0 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
 176    "Given node cannot be a child of document");
 177    }
 178    }
 179   
 180  0 public boolean hasChildNodes() {
 181  0 return nodeCount() > 0;
 182    }
 183   
 184  1 public org.w3c.dom.Node cloneNode(boolean deep) {
 185  1 return DOMNodeHelper.cloneNode(this, deep);
 186    }
 187   
 188  0 public boolean isSupported(String feature, String version) {
 189  0 return DOMNodeHelper.isSupported(this, feature, version);
 190    }
 191   
 192  0 public boolean hasAttributes() {
 193  0 return DOMNodeHelper.hasAttributes(this);
 194    }
 195   
 196    // org.w3c.dom.Document interface
 197    // -------------------------------------------------------------------------
 198  0 public NodeList getElementsByTagName(String name) {
 199  0 ArrayList list = new ArrayList();
 200  0 DOMNodeHelper.appendElementsByTagName(list, this, name);
 201   
 202  0 return DOMNodeHelper.createNodeList(list);
 203    }
 204   
 205  0 public NodeList getElementsByTagNameNS(String namespace, String name) {
 206  0 ArrayList list = new ArrayList();
 207  0 DOMNodeHelper.appendElementsByTagNameNS(list, this, namespace, name);
 208   
 209  0 return DOMNodeHelper.createNodeList(list);
 210    }
 211   
 212  0 public org.w3c.dom.DocumentType getDoctype() {
 213  0 return DOMNodeHelper.asDOMDocumentType(getDocType());
 214    }
 215   
 216  0 public org.w3c.dom.DOMImplementation getImplementation() {
 217  0 if (getDocumentFactory() instanceof org.w3c.dom.DOMImplementation) {
 218  0 return (org.w3c.dom.DOMImplementation) getDocumentFactory();
 219    } else {
 220  0 return DOCUMENT_FACTORY;
 221    }
 222    }
 223   
 224  3 public org.w3c.dom.Element getDocumentElement() {
 225  3 return DOMNodeHelper.asDOMElement(getRootElement());
 226    }
 227   
 228  7 public org.w3c.dom.Element createElement(String name) throws DOMException {
 229  7 return (org.w3c.dom.Element) getDocumentFactory().createElement(name);
 230    }
 231   
 232  0 public org.w3c.dom.DocumentFragment createDocumentFragment() {
 233  0 DOMNodeHelper.notSupported();
 234   
 235  0 return null;
 236    }
 237   
 238  15 public org.w3c.dom.Text createTextNode(String data) {
 239  15 return (org.w3c.dom.Text) getDocumentFactory().createText(data);
 240    }
 241   
 242  0 public org.w3c.dom.Comment createComment(String data) {
 243  0 return (org.w3c.dom.Comment) getDocumentFactory().createComment(data);
 244    }
 245   
 246  0 public CDATASection createCDATASection(String data) throws DOMException {
 247  0 return (CDATASection) getDocumentFactory().createCDATA(data);
 248    }
 249   
 250  0 public ProcessingInstruction createProcessingInstruction(String target,
 251    String data) throws DOMException {
 252  0 return (ProcessingInstruction) getDocumentFactory()
 253    .createProcessingInstruction(target, data);
 254    }
 255   
 256  0 public Attr createAttribute(String name) throws DOMException {
 257  0 QName qname = getDocumentFactory().createQName(name);
 258   
 259  0 return (Attr) getDocumentFactory().createAttribute(null, qname, "");
 260    }
 261   
 262  0 public EntityReference createEntityReference(String name)
 263    throws DOMException {
 264  0 return (EntityReference) getDocumentFactory().createEntity(name, null);
 265    }
 266   
 267  0 public org.w3c.dom.Node importNode(org.w3c.dom.Node importedNode,
 268    boolean deep) throws DOMException {
 269  0 DOMNodeHelper.notSupported();
 270   
 271  0 return null;
 272    }
 273   
 274  10 public org.w3c.dom.Element createElementNS(String namespaceURI,
 275    String qualifiedName) throws DOMException {
 276  10 QName qname = getDocumentFactory().createQName(qualifiedName,
 277    namespaceURI);
 278   
 279  10 return (org.w3c.dom.Element) getDocumentFactory().createElement(qname);
 280    }
 281   
 282  0 public org.w3c.dom.Attr createAttributeNS(String namespaceURI,
 283    String qualifiedName) throws DOMException {
 284  0 QName qname = getDocumentFactory().createQName(qualifiedName,
 285    namespaceURI);
 286   
 287  0 return (org.w3c.dom.Attr) getDocumentFactory().createAttribute(null,
 288    qname, null);
 289    }
 290   
 291  0 public org.w3c.dom.Element getElementById(String elementId) {
 292  0 return DOMNodeHelper.asDOMElement(elementByID(elementId));
 293    }
 294   
 295    // Implementation methods
 296    // -------------------------------------------------------------------------
 297  64 protected DocumentFactory getDocumentFactory() {
 298  64 if (super.getDocumentFactory() == null) {
 299  0 return DOCUMENT_FACTORY;
 300    } else {
 301  64 return super.getDocumentFactory();
 302    }
 303    }
 304    }
 305   
 306    /*
 307    * Redistribution and use of this software and associated documentation
 308    * ("Software"), with or without modification, are permitted provided that the
 309    * following conditions are met:
 310    *
 311    * 1. Redistributions of source code must retain copyright statements and
 312    * notices. Redistributions must also contain a copy of this document.
 313    *
 314    * 2. Redistributions in binary form must reproduce the above copyright notice,
 315    * this list of conditions and the following disclaimer in the documentation
 316    * and/or other materials provided with the distribution.
 317    *
 318    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 319    * from this Software without prior written permission of MetaStuff, Ltd. For
 320    * written permission, please contact dom4j-info@metastuff.com.
 321    *
 322    * 4. Products derived from this Software may not be called "DOM4J" nor may
 323    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 324    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 325    *
 326    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 327    *
 328    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 329    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 330    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 331    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 332    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 333    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 334    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 335    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 336    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 337    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 338    * POSSIBILITY OF SUCH DAMAGE.
 339    *
 340    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 341    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/Text.html0000644000175000017500000004201510242117600017717 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 56   Methods: 0
NCLOC: 3   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
Text.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    /**
 11    * <p>
 12    * <code>Text</code> defines an XML Text node.
 13    * </p>
 14    *
 15    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 16    * @version $Revision: 1.7 $
 17    */
 18    public interface Text extends CharacterData {
 19    }
 20   
 21    /*
 22    * Redistribution and use of this software and associated documentation
 23    * ("Software"), with or without modification, are permitted provided that the
 24    * following conditions are met:
 25    *
 26    * 1. Redistributions of source code must retain copyright statements and
 27    * notices. Redistributions must also contain a copy of this document.
 28    *
 29    * 2. Redistributions in binary form must reproduce the above copyright notice,
 30    * this list of conditions and the following disclaimer in the documentation
 31    * and/or other materials provided with the distribution.
 32    *
 33    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 34    * from this Software without prior written permission of MetaStuff, Ltd. For
 35    * written permission, please contact dom4j-info@metastuff.com.
 36    *
 37    * 4. Products derived from this Software may not be called "DOM4J" nor may
 38    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 39    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 40    *
 41    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 42    *
 43    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 44    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 45    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 46    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 47    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 48    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 49    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 50    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 51    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 52    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 53    * POSSIBILITY OF SUCH DAMAGE.
 54    *
 55    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 56    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/rule/0000755000175000017500000000000012133227266017065 5ustar ebourgebourgdom4j-1.6.1/docs/clover/org/dom4j/rule/pkg-classes.html0000644000175000017500000000264710242117732022173 0ustar ebourgebourg dom4j - 1.6.1 org.dom4j.rule
Classes
Mode (45,1%)
NullAction (0%)
Rule (54,1%)
RuleManager (63,6%)
RuleSet (68,8%)
Stylesheet (41,2%)
dom4j-1.6.1/docs/clover/org/dom4j/rule/Stylesheet.html0000644000175000017500000026170710242117727022120 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 334   Methods: 20
NCLOC: 118   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
Stylesheet.java 32,1% 44,4% 45% 41,2%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.rule;
 9   
 10    import java.util.Iterator;
 11    import java.util.List;
 12   
 13    import org.dom4j.Document;
 14    import org.dom4j.Element;
 15    import org.dom4j.Node;
 16    import org.dom4j.XPath;
 17   
 18    /**
 19    * <p>
 20    * <code>Stylesheet</code> implements an XSLT stylesheet such that rules can
 21    * be added to the stylesheet and the stylesheet can be applied to a source
 22    * document or node.
 23    * </p>
 24    *
 25    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 26    * @version $Revision: 1.14 $
 27    */
 28    public class Stylesheet {
 29    private RuleManager ruleManager = new RuleManager();
 30   
 31    /** Holds value of property mode. */
 32    private String modeName;
 33   
 34    /**
 35    * Creates a new empty stylesheet.
 36    */
 37  5 public Stylesheet() {
 38    }
 39   
 40    /**
 41    * Add a rule to this stylesheet.
 42    *
 43    * @param rule
 44    * the rule to add
 45    */
 46  14 public void addRule(Rule rule) {
 47  14 ruleManager.addRule(rule);
 48    }
 49   
 50    /**
 51    * Removes the specified rule from this stylesheet.
 52    *
 53    * @param rule
 54    * the rule to remove
 55    */
 56  0 public void removeRule(Rule rule) {
 57  0 ruleManager.removeRule(rule);
 58    }
 59   
 60    /**
 61    * Runs this stylesheet on the given input which should be either a Node or
 62    * a List of Node objects.
 63    *
 64    * @param input
 65    * the input to run this stylesheet on
 66    *
 67    * @throws Exception
 68    * if something goes wrong
 69    */
 70  0 public void run(Object input) throws Exception {
 71  0 run(input, this.modeName);
 72    }
 73   
 74  0 public void run(Object input, String mode) throws Exception {
 75  0 if (input instanceof Node) {
 76  0 run((Node) input, mode);
 77  0 } else if (input instanceof List) {
 78  0 run((List) input, mode);
 79    }
 80    }
 81   
 82  0 public void run(List list) throws Exception {
 83  0 run(list, this.modeName);
 84    }
 85   
 86  0 public void run(List list, String mode) throws Exception {
 87  0 for (int i = 0, size = list.size(); i < size; i++) {
 88  0 Object object = list.get(i);
 89   
 90  0 if (object instanceof Node) {
 91  0 run((Node) object, mode);
 92    }
 93    }
 94    }
 95   
 96  2 public void run(Node node) throws Exception {
 97  2 run(node, this.modeName);
 98    }
 99   
 100  2 public void run(Node node, String mode) throws Exception {
 101  2 Mode mod = ruleManager.getMode(mode);
 102  2 mod.fireRule(node);
 103    }
 104   
 105    /**
 106    * Processes the result of the xpath expression. The xpath expression is
 107    * evaluated against the provided input object.
 108    *
 109    * @param input
 110    * the input object
 111    * @param xpath
 112    * the xpath expression
 113    * @throws Exception
 114    * if something goes wrong
 115    */
 116  1 public void applyTemplates(Object input, XPath xpath) throws Exception {
 117  1 applyTemplates(input, xpath, this.modeName);
 118    }
 119   
 120    /**
 121    * Processes the result of the xpath expression in the given mode. The xpath
 122    * expression is evaluated against the provided input object.
 123    *
 124    * @param input
 125    * the input object
 126    * @param xpath
 127    * the xpath expression
 128    * @param mode
 129    * the mode
 130    * @throws Exception
 131    * if something goes wrong
 132    */
 133  1 public void applyTemplates(Object input, XPath xpath, String mode)
 134    throws Exception {
 135  1 Mode mod = ruleManager.getMode(mode);
 136   
 137  1 List list = xpath.selectNodes(input);
 138  1 Iterator it = list.iterator();
 139  1 while (it.hasNext()) {
 140  2 Node current = (Node) it.next();
 141  2 mod.fireRule(current);
 142    }
 143    }
 144   
 145    /**
 146    * Processes the result of the xpath expression. The xpath expression is
 147    * evaluated against the provided input object.
 148    *
 149    * @param input
 150    * the input object
 151    * @param xpath
 152    * the xpath expression
 153    * @throws Exception
 154    * if something goes wrong
 155    * @deprecated Use {@link Stylesheet#applyTemplates(Object, XPath)}instead.
 156    */
 157  0 public void applyTemplates(Object input, org.jaxen.XPath xpath)
 158    throws Exception {
 159  0 applyTemplates(input, xpath, this.modeName);
 160    }
 161   
 162    /**
 163    * Processes the result of the xpath expression in the given mode. The xpath
 164    * expression is evaluated against the provided input object.
 165    *
 166    * @param input
 167    * the input object
 168    * @param xpath
 169    * the xpath expression
 170    * @param mode
 171    * the mode
 172    * @throws Exception
 173    * if something goes wrong
 174    * @deprecated Use {@link Stylesheet#applyTemplates(Object, XPath, String)}
 175    * instead.
 176    */
 177  0 public void applyTemplates(Object input, org.jaxen.XPath xpath, String mode)
 178    throws Exception {
 179  0 Mode mod = ruleManager.getMode(mode);
 180   
 181  0 List list = xpath.selectNodes(input);
 182  0 Iterator it = list.iterator();
 183  0 while (it.hasNext()) {
 184  0 Node current = (Node) it.next();
 185  0 mod.fireRule(current);
 186    }
 187    }
 188   
 189    /**
 190    * If input is a <code>Node</code>, this will processes all of the
 191    * children of that node. If input is a <code>List</code> of
 192    * <code>Nodes</code>s, these nodes will be iterated and all children of
 193    * each node will be processed.
 194    *
 195    * @param input
 196    * the input object, this can either be a <code>Node</code> or
 197    * a <code>List</code>
 198    * @throws Exception
 199    * if something goes wrong
 200    */
 201  8 public void applyTemplates(Object input) throws Exception {
 202  8 applyTemplates(input, this.modeName);
 203    }
 204   
 205    /**
 206    * Processes the input object in the given mode. If input is a
 207    * <code>Node</code>, this will processes all of the children of that
 208    * node. If input is a <code>List</code> of <code>Nodes</code>s, these
 209    * nodes will be iterated and all children of each node will be processed.
 210    *
 211    * @param input
 212    * the input object, this can either be a <code>Node</code> or
 213    * a <code>List</code>
 214    * @param mode
 215    * the mode
 216    * @throws Exception
 217    * if something goes wrong
 218    */
 219  8 public void applyTemplates(Object input, String mode) throws Exception {
 220  8 Mode mod = ruleManager.getMode(mode);
 221   
 222  8 if (input instanceof Element) {
 223    // iterate through all children
 224  7 Element element = (Element) input;
 225  7 for (int i = 0, size = element.nodeCount(); i < size; i++) {
 226  10 Node node = element.node(i);
 227  10 mod.fireRule(node);
 228    }
 229  1 } else if (input instanceof Document) {
 230    // iterate through all children
 231  1 Document document = (Document) input;
 232  1 for (int i = 0, size = document.nodeCount(); i < size; i++) {
 233  1 Node node = document.node(i);
 234  1 mod.fireRule(node);
 235    }
 236  0 } else if (input instanceof List) {
 237  0 List list = (List) input;
 238   
 239  0 for (int i = 0, size = list.size(); i < size; i++) {
 240  0 Object object = list.get(i);
 241   
 242  0 if (object instanceof Element) {
 243  0 applyTemplates((Element) object, mode);
 244  0 } else if (object instanceof Document) {
 245  0 applyTemplates((Document) object, mode);
 246    }
 247    }
 248    }
 249    }
 250   
 251  0 public void clear() {
 252  0 ruleManager.clear();
 253    }
 254   
 255    // Properties
 256    // -------------------------------------------------------------------------
 257   
 258    /**
 259    * DOCUMENT ME!
 260    *
 261    * @return the name of the mode the stylesheet uses by default
 262    */
 263  0 public String getModeName() {
 264  0 return modeName;
 265    }
 266   
 267    /**
 268    * Sets the name of the mode that the stylesheet uses by default.
 269    *
 270    * @param modeName
 271    * DOCUMENT ME!
 272    */
 273  0 public void setModeName(String modeName) {
 274  0 this.modeName = modeName;
 275    }
 276   
 277    /**
 278    * DOCUMENT ME!
 279    *
 280    * @return the default value-of action which is used in the default rules
 281    * for the pattern "text()|&#64;"
 282    */
 283  0 public Action getValueOfAction() {
 284  0 return ruleManager.getValueOfAction();
 285    }
 286   
 287    /**
 288    * Sets the default value-of action which is used in the default rules for
 289    * the pattern "text()|&#64;"
 290    *
 291    * @param valueOfAction
 292    * DOCUMENT ME!
 293    */
 294  4 public void setValueOfAction(Action valueOfAction) {
 295  4 ruleManager.setValueOfAction(valueOfAction);
 296    }
 297    }
 298   
 299    /*
 300    * Redistribution and use of this software and associated documentation
 301    * ("Software"), with or without modification, are permitted provided that the
 302    * following conditions are met:
 303    *
 304    * 1. Redistributions of source code must retain copyright statements and
 305    * notices. Redistributions must also contain a copy of this document.
 306    *
 307    * 2. Redistributions in binary form must reproduce the above copyright notice,
 308    * this list of conditions and the following disclaimer in the documentation
 309    * and/or other materials provided with the distribution.
 310    *
 311    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 312    * from this Software without prior written permission of MetaStuff, Ltd. For
 313    * written permission, please contact dom4j-info@metastuff.com.
 314    *
 315    * 4. Products derived from this Software may not be called "DOM4J" nor may
 316    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 317    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 318    *
 319    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 320    *
 321    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 322    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 323    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 324    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 325    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 326    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 327    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 328    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 329    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 330    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 331    * POSSIBILITY OF SUCH DAMAGE.
 332    *
 333    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 334    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/rule/Action.html0000644000175000017500000004371210242117740021171 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 60   Methods: 0
NCLOC: 5   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
Action.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.rule;
 9   
 10    import org.dom4j.Node;
 11   
 12    /**
 13    * <p>
 14    * <code>Action</code> represents some default action which should occur when
 15    * a rule matches a node in the XSLT processing model.
 16    * </p>
 17    *
 18    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 19    * @version $Revision: 1.7 $
 20    */
 21    public interface Action {
 22    void run(Node node) throws Exception;
 23    }
 24   
 25    /*
 26    * Redistribution and use of this software and associated documentation
 27    * ("Software"), with or without modification, are permitted provided that the
 28    * following conditions are met:
 29    *
 30    * 1. Redistributions of source code must retain copyright statements and
 31    * notices. Redistributions must also contain a copy of this document.
 32    *
 33    * 2. Redistributions in binary form must reproduce the above copyright notice,
 34    * this list of conditions and the following disclaimer in the documentation
 35    * and/or other materials provided with the distribution.
 36    *
 37    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 38    * from this Software without prior written permission of MetaStuff, Ltd. For
 39    * written permission, please contact dom4j-info@metastuff.com.
 40    *
 41    * 4. Products derived from this Software may not be called "DOM4J" nor may
 42    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 43    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 44    *
 45    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 46    *
 47    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 48    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 49    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 50    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 51    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 52    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 53    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 54    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 55    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 56    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 57    * POSSIBILITY OF SUCH DAMAGE.
 58    *
 59    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 60    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/rule/Pattern.html0000644000175000017500000010160110242117751021363 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 125   Methods: 0
NCLOC: 14   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
Pattern.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.rule;
 9   
 10    import org.dom4j.Node;
 11    import org.dom4j.NodeFilter;
 12   
 13    /**
 14    * <p>
 15    * <code>Pattern</code> defines the behaviour for pattern in the XSLT
 16    * processing model.
 17    * </p>
 18    *
 19    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 20    * @version $Revision: 1.6 $
 21    */
 22    public interface Pattern extends NodeFilter {
 23    // These node numbers are compatable with DOM4J's Node types
 24   
 25    /** Matches any node */
 26    short ANY_NODE = 0;
 27   
 28    /** Matches no nodes */
 29    short NONE = 9999;
 30   
 31    /** Count of the number of node types */
 32    short NUMBER_OF_TYPES = Node.UNKNOWN_NODE;
 33   
 34    /**
 35    * According to the <a href="http://www.w3.org/TR/xslt11/#conflict">spec
 36    * </a> we should return 0.5 if we cannot determine the priority
 37    */
 38    double DEFAULT_PRIORITY = 0.5;
 39   
 40    /**
 41    * DOCUMENT ME!
 42    *
 43    * @param node
 44    * DOCUMENT ME!
 45    *
 46    * @return true if the pattern matches the given DOM4J node.
 47    */
 48    boolean matches(Node node);
 49   
 50    /**
 51    * Returns the default resolution policy of the pattern according to the <a
 52    * href="http://www.w3.org/TR/xslt11/#conflict"> XSLT conflict resolution
 53    * spec </a>.
 54    *
 55    * @return DOCUMENT ME!
 56    */
 57    double getPriority();
 58   
 59    /**
 60    * If this pattern is a union pattern then this method should return an
 61    * array of patterns which describe the union pattern, which should contain
 62    * more than one pattern. Otherwise this method should return null.
 63    *
 64    * @return an array of the patterns which make up this union pattern or null
 65    * if this pattern is not a union pattern
 66    */
 67    Pattern[] getUnionPatterns();
 68   
 69    /**
 70    * DOCUMENT ME!
 71    *
 72    * @return the type of node the pattern matches which by default should
 73    * return ANY_NODE if it can match any kind of node.
 74    */
 75    short getMatchType();
 76   
 77    /**
 78    * For patterns which only match an ATTRIBUTE_NODE or an ELEMENT_NODE then
 79    * this pattern may return the name of the element or attribute it matches.
 80    * This allows a more efficient rule matching algorithm to be performed,
 81    * rather than a brute force approach of evaluating every pattern for a
 82    * given Node.
 83    *
 84    * @return the name of the element or attribute this pattern matches or null
 85    * if this pattern matches any or more than one name.
 86    */
 87    String getMatchesNodeName();
 88    }
 89   
 90    /*
 91    * Redistribution and use of this software and associated documentation
 92    * ("Software"), with or without modification, are permitted provided that the
 93    * following conditions are met:
 94    *
 95    * 1. Redistributions of source code must retain copyright statements and
 96    * notices. Redistributions must also contain a copy of this document.
 97    *
 98    * 2. Redistributions in binary form must reproduce the above copyright notice,
 99    * this list of conditions and the following disclaimer in the documentation
 100    * and/or other materials provided with the distribution.
 101    *
 102    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 103    * from this Software without prior written permission of MetaStuff, Ltd. For
 104    * written permission, please contact dom4j-info@metastuff.com.
 105    *
 106    * 4. Products derived from this Software may not be called "DOM4J" nor may
 107    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 108    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 109    *
 110    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 111    *
 112    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 113    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 114    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 115    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 116    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 117    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 118    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 119    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 120    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 121    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 122    * POSSIBILITY OF SUCH DAMAGE.
 123    *
 124    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 125    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/rule/pkg-summary.html0000644000175000017500000002127310242117703022225 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
package stats: LOC: 1.592   Methods: 76
NCLOC: 557   Classes: 8
Files: 8  
 
 Package Conditionals Statements Methods TOTAL
org.dom4j.rule 41,3% 52,7% 59,2% 50,4%
coverage coverage
 
 Classes Conditionals Statements Methods TOTAL
NullAction - - 0% 0%
coverage
Stylesheet 32,1% 44,4% 45% 41,2%
coverage coverage
Mode 39,2% 47,3% 70% 45,1%
coverage coverage
Rule 50% 52,1% 60% 54,1%
coverage coverage
RuleManager 44,4% 67,4% 76,9% 63,6%
coverage coverage
RuleSet 83,3% 68,4% 57,1% 68,8%
coverage coverage
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/rule/RuleSet.html0000644000175000017500000011415110242117730021332 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 138   Methods: 7
NCLOC: 44   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
RuleSet.java 83,3% 68,4% 57,1% 68,8%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.rule;
 9   
 10    import java.util.ArrayList;
 11    import java.util.Collections;
 12   
 13    import org.dom4j.Node;
 14   
 15    /**
 16    * <p>
 17    * <code>RuleSet</code> manages a set of rules which are sorted in order of
 18    * relevance according to the XSLT defined conflict resolution policy. This
 19    * makes finding the correct rule for a DOM4J Node using the XSLT processing
 20    * model efficient as the rules can be evaluated in order of priority.
 21    * </p>
 22    *
 23    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 24    * @version $Revision: 1.10 $
 25    */
 26    public class RuleSet {
 27    /** An unordered list of Rule objects */
 28    private ArrayList rules = new ArrayList();
 29   
 30    /** A lazily evaluated and cached array of rules sorted */
 31    private Rule[] ruleArray;
 32   
 33  14 public RuleSet() {
 34    }
 35   
 36  0 public String toString() {
 37  0 return super.toString() + " [RuleSet: " + rules + " ]";
 38    }
 39   
 40    /**
 41    * Performs an XSLT processing model match for the rule which matches the
 42    * given Node the best.
 43    *
 44    * @param node
 45    * is the DOM4J Node to match against
 46    *
 47    * @return the matching Rule or no rule if none matched
 48    */
 49  28 public Rule getMatchingRule(Node node) {
 50  28 Rule[] matches = getRuleArray();
 51   
 52  49 for (int i = matches.length - 1; i >= 0; i--) {
 53  49 Rule rule = matches[i];
 54   
 55  49 if (rule.matches(node)) {
 56  28 return rule;
 57    }
 58    }
 59   
 60  0 return null;
 61    }
 62   
 63  28 public void addRule(Rule rule) {
 64  28 rules.add(rule);
 65  28 ruleArray = null;
 66    }
 67   
 68  0 public void removeRule(Rule rule) {
 69  0 rules.remove(rule);
 70  0 ruleArray = null;
 71    }
 72   
 73    /**
 74    * Adds all the rules to this RuleSet from the given other rule set.
 75    *
 76    * @param that
 77    * DOCUMENT ME!
 78    */
 79  0 public void addAll(RuleSet that) {
 80  0 rules.addAll(that.rules);
 81  0 ruleArray = null;
 82    }
 83   
 84    /**
 85    * Returns an array of sorted rules.
 86    *
 87    * @return the rules as a sorted array in ascending precendence so that the
 88    * rules at the end of the array should be used first
 89    */
 90  28 protected Rule[] getRuleArray() {
 91  28 if (ruleArray == null) {
 92  8 Collections.sort(rules);
 93   
 94  8 int size = rules.size();
 95  8 ruleArray = new Rule[size];
 96  8 rules.toArray(ruleArray);
 97    }
 98   
 99  28 return ruleArray;
 100    }
 101    }
 102   
 103    /*
 104    * Redistribution and use of this software and associated documentation
 105    * ("Software"), with or without modification, are permitted provided that the
 106    * following conditions are met:
 107    *
 108    * 1. Redistributions of source code must retain copyright statements and
 109    * notices. Redistributions must also contain a copy of this document.
 110    *
 111    * 2. Redistributions in binary form must reproduce the above copyright notice,
 112    * this list of conditions and the following disclaimer in the documentation
 113    * and/or other materials provided with the distribution.
 114    *
 115    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 116    * from this Software without prior written permission of MetaStuff, Ltd. For
 117    * written permission, please contact dom4j-info@metastuff.com.
 118    *
 119    * 4. Products derived from this Software may not be called "DOM4J" nor may
 120    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 121    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 122    *
 123    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 124    *
 125    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 126    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 127    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 128    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 129    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 130    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 131    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 132    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 133    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 134    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 135    * POSSIBILITY OF SUCH DAMAGE.
 136    *
 137    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 138    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/rule/RuleManager.html0000644000175000017500000017645610242117733022174 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 235   Methods: 13
NCLOC: 95   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
RuleManager.java 44,4% 67,4% 76,9% 63,6%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.rule;
 9   
 10    import java.util.HashMap;
 11   
 12    import org.dom4j.Document;
 13    import org.dom4j.Element;
 14    import org.dom4j.Node;
 15    import org.dom4j.rule.pattern.NodeTypePattern;
 16   
 17    /**
 18    * <p>
 19    * <code>RuleManager</code> manages a set of rules such that a rule can be
 20    * found for a given DOM4J Node using the XSLT processing model.
 21    * </p>
 22    *
 23    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 24    * @version $Revision: 1.9 $
 25    */
 26    public class RuleManager {
 27    /** Map of modes indexed by mode */
 28    private HashMap modes = new HashMap();
 29   
 30    /**
 31    * A counter so that rules can be ordered by the order in which they were
 32    * added to the rule base
 33    */
 34    private int appearenceCount;
 35   
 36    /** Holds value of property valueOfAction. */
 37    private Action valueOfAction;
 38   
 39  5 public RuleManager() {
 40    }
 41   
 42    /**
 43    * DOCUMENT ME!
 44    *
 45    * @param modeName
 46    * DOCUMENT ME!
 47    *
 48    * @return the Mode instance for the given mode name. If one does not exist
 49    * then it will be created.
 50    */
 51  25 public Mode getMode(String modeName) {
 52  25 Mode mode = (Mode) modes.get(modeName);
 53   
 54  25 if (mode == null) {
 55  4 mode = createMode();
 56  4 modes.put(modeName, mode);
 57    }
 58   
 59  25 return mode;
 60    }
 61   
 62  14 public void addRule(Rule rule) {
 63  14 rule.setAppearenceCount(++appearenceCount);
 64   
 65  14 Mode mode = getMode(rule.getMode());
 66  14 Rule[] childRules = rule.getUnionRules();
 67   
 68  14 if (childRules != null) {
 69  0 for (int i = 0, size = childRules.length; i < size; i++) {
 70  0 mode.addRule(childRules[i]);
 71    }
 72    } else {
 73  14 mode.addRule(rule);
 74    }
 75    }
 76   
 77  0 public void removeRule(Rule rule) {
 78  0 Mode mode = getMode(rule.getMode());
 79  0 Rule[] childRules = rule.getUnionRules();
 80   
 81  0 if (childRules != null) {
 82  0 for (int i = 0, size = childRules.length; i < size; i++) {
 83  0 mode.removeRule(childRules[i]);
 84    }
 85    } else {
 86  0 mode.removeRule(rule);
 87    }
 88    }
 89   
 90    /**
 91    * Performs an XSLT processing model match for the rule which matches the
 92    * given Node the best.
 93    *
 94    * @param modeName
 95    * is the name of the mode associated with the rule if any
 96    * @param node
 97    * is the DOM4J Node to match against
 98    *
 99    * @return the matching Rule or no rule if none matched
 100    */
 101  0 public Rule getMatchingRule(String modeName, Node node) {
 102  0 Mode mode = (Mode) modes.get(modeName);
 103   
 104  0 if (mode != null) {
 105  0 return mode.getMatchingRule(node);
 106    } else {
 107  0 System.out.println("Warning: No Mode for mode: " + mode);
 108   
 109  0 return null;
 110    }
 111    }
 112   
 113  0 public void clear() {
 114  0 modes.clear();
 115  0 appearenceCount = 0;
 116    }
 117   
 118    // Properties
 119    // -------------------------------------------------------------------------
 120   
 121    /**
 122    * DOCUMENT ME!
 123    *
 124    * @return the default value-of action which is used in the default rules
 125    * for the pattern "text()|&#64;"
 126    */
 127  4 public Action getValueOfAction() {
 128  4 return valueOfAction;
 129    }
 130   
 131    /**
 132    * Sets the default value-of action which is used in the default rules for
 133    * the pattern "text()|&#64;"
 134    *
 135    * @param valueOfAction
 136    * DOCUMENT ME!
 137    */
 138  4 public void setValueOfAction(Action valueOfAction) {
 139  4 this.valueOfAction = valueOfAction;
 140    }
 141   
 142    // Implementation methods
 143    // -------------------------------------------------------------------------
 144   
 145    /**
 146    * A factory method to return a new {@link Mode}instance which should add
 147    * the necessary default rules
 148    *
 149    * @return DOCUMENT ME!
 150    */
 151  4 protected Mode createMode() {
 152  4 Mode mode = new Mode();
 153  4 addDefaultRules(mode);
 154   
 155  4 return mode;
 156    }
 157   
 158    /**
 159    * Adds the default stylesheet rules to the given {@link Mode}instance
 160    *
 161    * @param mode
 162    * DOCUMENT ME!
 163    */
 164  4 protected void addDefaultRules(final Mode mode) {
 165    // add an apply templates rule
 166  4 Action applyTemplates = new Action() {
 167  6 public void run(Node node) throws Exception {
 168  6 if (node instanceof Element) {
 169  5 mode.applyTemplates((Element) node);
 170  1 } else if (node instanceof Document) {
 171  1 mode.applyTemplates((Document) node);
 172    }
 173    }
 174    };
 175   
 176  4 Action valueOf = getValueOfAction();
 177   
 178  4 addDefaultRule(mode, NodeTypePattern.ANY_DOCUMENT, applyTemplates);
 179  4 addDefaultRule(mode, NodeTypePattern.ANY_ELEMENT, applyTemplates);
 180   
 181  4 if (valueOf != null) {
 182  3 addDefaultRule(mode, NodeTypePattern.ANY_ATTRIBUTE, valueOf);
 183  3 addDefaultRule(mode, NodeTypePattern.ANY_TEXT, valueOf);
 184    }
 185    }
 186   
 187  14 protected void addDefaultRule(Mode mode, Pattern pattern, Action action) {
 188  14 Rule rule = createDefaultRule(pattern, action);
 189  14 mode.addRule(rule);
 190    }
 191   
 192  14 protected Rule createDefaultRule(Pattern pattern, Action action) {
 193  14 Rule rule = new Rule(pattern, action);
 194  14 rule.setImportPrecedence(-1);
 195   
 196  14 return rule;
 197    }
 198    }
 199   
 200    /*
 201    * Redistribution and use of this software and associated documentation
 202    * ("Software"), with or without modification, are permitted provided that the
 203    * following conditions are met:
 204    *
 205    * 1. Redistributions of source code must retain copyright statements and
 206    * notices. Redistributions must also contain a copy of this document.
 207    *
 208    * 2. Redistributions in binary form must reproduce the above copyright notice,
 209    * this list of conditions and the following disclaimer in the documentation
 210    * and/or other materials provided with the distribution.
 211    *
 212    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 213    * from this Software without prior written permission of MetaStuff, Ltd. For
 214    * written permission, please contact dom4j-info@metastuff.com.
 215    *
 216    * 4. Products derived from this Software may not be called "DOM4J" nor may
 217    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 218    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 219    *
 220    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 221    *
 222    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 223    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 224    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 225    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 226    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 227    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 228    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 229    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 230    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 231    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 232    * POSSIBILITY OF SUCH DAMAGE.
 233    *
 234    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 235    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/rule/pattern/0000755000175000017500000000000012133227266020542 5ustar ebourgebourgdom4j-1.6.1/docs/clover/org/dom4j/rule/pattern/pkg-classes.html0000644000175000017500000000175710242117755023656 0ustar ebourgebourg dom4j - 1.6.1 org.dom4j.rule.pattern
Classes
DefaultPattern (0%)
NodeTypePattern (83,3%)
dom4j-1.6.1/docs/clover/org/dom4j/rule/pattern/pkg-summary.html0000644000175000017500000001313010242117722023674 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
package stats: LOC: 199   Methods: 12
NCLOC: 61   Classes: 2
Files: 2  
 
 Package Conditionals Statements Methods TOTAL
org.dom4j.rule.pattern - 41,7% 41,7% 41,7%
coverage coverage
 
 Classes Conditionals Statements Methods TOTAL
DefaultPattern - 0% 0% 0%
coverage
NodeTypePattern - 83,3% 83,3% 83,3%
coverage coverage
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/rule/pattern/DefaultPattern.html0000644000175000017500000006366710242117666024375 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 90   Methods: 6
NCLOC: 25   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DefaultPattern.java - 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.rule.pattern;
 9   
 10    import org.dom4j.Node;
 11    import org.dom4j.NodeFilter;
 12    import org.dom4j.rule.Pattern;
 13   
 14    /**
 15    * <p>
 16    * <code>DefaultPattern</code> a default implementation of Pattern which can
 17    * take any XPath implementation or NodeFilter for defining the pattern.
 18    * <b>WARNING </b> this implementation causes a worst case, brute force XSLT
 19    * rule evaluation to be performed. Wherever possible the methods {@link
 20    * #getPriority}, {@link #getMatchType}and {@link #getMatchesNodeName}should
 21    * be overloaded to allow more rule filtering to occur.
 22    * </p>
 23    *
 24    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 25    * @version $Revision: 1.6 $
 26    */
 27    public class DefaultPattern implements Pattern {
 28    private NodeFilter filter;
 29   
 30  0 public DefaultPattern(NodeFilter filter) {
 31  0 this.filter = filter;
 32    }
 33   
 34  0 public boolean matches(Node node) {
 35  0 return filter.matches(node);
 36    }
 37   
 38  0 public double getPriority() {
 39  0 return Pattern.DEFAULT_PRIORITY;
 40    }
 41   
 42  0 public Pattern[] getUnionPatterns() {
 43  0 return null;
 44    }
 45   
 46  0 public short getMatchType() {
 47  0 return ANY_NODE;
 48    }
 49   
 50  0 public String getMatchesNodeName() {
 51  0 return null;
 52    }
 53    }
 54   
 55    /*
 56    * Redistribution and use of this software and associated documentation
 57    * ("Software"), with or without modification, are permitted provided that the
 58    * following conditions are met:
 59    *
 60    * 1. Redistributions of source code must retain copyright statements and
 61    * notices. Redistributions must also contain a copy of this document.
 62    *
 63    * 2. Redistributions in binary form must reproduce the above copyright notice,
 64    * this list of conditions and the following disclaimer in the documentation
 65    * and/or other materials provided with the distribution.
 66    *
 67    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 68    * from this Software without prior written permission of MetaStuff, Ltd. For
 69    * written permission, please contact dom4j-info@metastuff.com.
 70    *
 71    * 4. Products derived from this Software may not be called "DOM4J" nor may
 72    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 73    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 74    *
 75    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 76    *
 77    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 78    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 79    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 80    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 81    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 82    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 83    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 84    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 85    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 86    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 87    * POSSIBILITY OF SUCH DAMAGE.
 88    *
 89    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 90    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/rule/pattern/NodeTypePattern.html0000644000175000017500000007513510242117550024521 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 109   Methods: 6
NCLOC: 36   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
NodeTypePattern.java - 83,3% 83,3% 83,3%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.rule.pattern;
 9   
 10    import org.dom4j.Node;
 11    import org.dom4j.rule.Pattern;
 12   
 13    /**
 14    * <p>
 15    * <code>NodeTypePattern</code> implements a Pattern which matches any node of
 16    * the given node type.
 17    * </p>
 18    *
 19    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 20    * @version $Revision: 1.7 $
 21    */
 22    public class NodeTypePattern implements Pattern {
 23    /** A pattern which matches any Attribute node */
 24    public static final NodeTypePattern ANY_ATTRIBUTE = new NodeTypePattern(
 25    Node.ATTRIBUTE_NODE);
 26   
 27    /** A pattern which matches any Comment node */
 28    public static final NodeTypePattern ANY_COMMENT = new NodeTypePattern(
 29    Node.COMMENT_NODE);
 30   
 31    /** A pattern which matches any Document node */
 32    public static final NodeTypePattern ANY_DOCUMENT = new NodeTypePattern(
 33    Node.DOCUMENT_NODE);
 34   
 35    /** A pattern which matches any Element node */
 36    public static final NodeTypePattern ANY_ELEMENT = new NodeTypePattern(
 37    Node.ELEMENT_NODE);
 38   
 39    /** A pattern which matches any ProcessingInstruction node */
 40    public static final NodeTypePattern ANY_PROCESSING_INSTRUCTION =
 41    new NodeTypePattern(Node.PROCESSING_INSTRUCTION_NODE);
 42   
 43    /** A pattern which matches any Text node */
 44    public static final NodeTypePattern ANY_TEXT = new NodeTypePattern(
 45    Node.TEXT_NODE);
 46   
 47    private short nodeType;
 48   
 49  6 public NodeTypePattern(short nodeType) {
 50  6 this.nodeType = nodeType;
 51    }
 52   
 53  20 public boolean matches(Node node) {
 54  20 return node.getNodeType() == nodeType;
 55    }
 56   
 57  14 public double getPriority() {
 58  14 return Pattern.DEFAULT_PRIORITY;
 59    }
 60   
 61  0 public Pattern[] getUnionPatterns() {
 62  0 return null;
 63    }
 64   
 65  14 public short getMatchType() {
 66  14 return nodeType;
 67    }
 68   
 69  14 public String getMatchesNodeName() {
 70  14 return null;
 71    }
 72    }
 73   
 74    /*
 75    * Redistribution and use of this software and associated documentation
 76    * ("Software"), with or without modification, are permitted provided that the
 77    * following conditions are met:
 78    *
 79    * 1. Redistributions of source code must retain copyright statements and
 80    * notices. Redistributions must also contain a copy of this document.
 81    *
 82    * 2. Redistributions in binary form must reproduce the above copyright notice,
 83    * this list of conditions and the following disclaimer in the documentation
 84    * and/or other materials provided with the distribution.
 85    *
 86    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 87    * from this Software without prior written permission of MetaStuff, Ltd. For
 88    * written permission, please contact dom4j-info@metastuff.com.
 89    *
 90    * 4. Products derived from this Software may not be called "DOM4J" nor may
 91    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 92    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 93    *
 94    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 95    *
 96    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 97    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 98    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 99    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 100    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 101    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 102    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 103    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 104    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 105    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 106    * POSSIBILITY OF SUCH DAMAGE.
 107    *
 108    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 109    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/rule/Mode.html0000644000175000017500000025003610242117734020642 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 306   Methods: 10
NCLOC: 159   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
Mode.java 39,2% 47,3% 70% 45,1%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.rule;
 9   
 10    import java.util.HashMap;
 11    import java.util.Map;
 12   
 13    import org.dom4j.Attribute;
 14    import org.dom4j.Document;
 15    import org.dom4j.Element;
 16    import org.dom4j.Node;
 17   
 18    /**
 19    * <p>
 20    * <code>Mode</code> manages a number of RuleSet instances for the mode in a
 21    * stylesheet. It is responsible for finding the correct rule for a given DOM4J
 22    * Node using the XSLT processing model uses the smallest possible RuleSet to
 23    * reduce the number of Rule evaluations.
 24    * </p>
 25    *
 26    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 27    * @version $Revision: 1.9 $
 28    */
 29    public class Mode {
 30    private RuleSet[] ruleSets = new RuleSet[Pattern.NUMBER_OF_TYPES];
 31   
 32    /** Map of exact (local) element names to RuleSet instances */
 33    private Map elementNameRuleSets;
 34   
 35    /** Map of exact (local) attribute names to RuleSet instances */
 36    private Map attributeNameRuleSets;
 37   
 38  4 public Mode() {
 39    }
 40   
 41    /**
 42    * Runs the actions associated with the given node
 43    *
 44    * @param node
 45    * DOCUMENT ME!
 46    *
 47    * @throws Exception
 48    * DOCUMENT ME!
 49    */
 50  30 public void fireRule(Node node) throws Exception {
 51  30 if (node != null) {
 52  30 Rule rule = getMatchingRule(node);
 53   
 54  30 if (rule != null) {
 55  28 Action action = rule.getAction();
 56   
 57  28 if (action != null) {
 58  28 action.run(node);
 59    }
 60    }
 61    }
 62    }
 63   
 64  5 public void applyTemplates(Element element) throws Exception {
 65  5 for (int i = 0, size = element.attributeCount(); i < size; i++) {
 66  1 Attribute attribute = element.attribute(i);
 67  1 fireRule(attribute);
 68    }
 69   
 70  5 for (int i = 0, size = element.nodeCount(); i < size; i++) {
 71  13 Node node = element.node(i);
 72  13 fireRule(node);
 73    }
 74    }
 75   
 76  1 public void applyTemplates(Document document) throws Exception {
 77  1 for (int i = 0, size = document.nodeCount(); i < size; i++) {
 78  1 Node node = document.node(i);
 79  1 fireRule(node);
 80    }
 81    }
 82   
 83  28 public void addRule(Rule rule) {
 84  28 int matchType = rule.getMatchType();
 85  28 String name = rule.getMatchesNodeName();
 86   
 87  28 if (name != null) {
 88  0 if (matchType == Node.ELEMENT_NODE) {
 89  0 elementNameRuleSets = addToNameMap(elementNameRuleSets, name,
 90    rule);
 91  0 } else if (matchType == Node.ATTRIBUTE_NODE) {
 92  0 attributeNameRuleSets = addToNameMap(attributeNameRuleSets,
 93    name, rule);
 94    }
 95    }
 96   
 97  28 if (matchType >= Pattern.NUMBER_OF_TYPES) {
 98  0 matchType = Pattern.ANY_NODE;
 99    }
 100   
 101  28 if (matchType == Pattern.ANY_NODE) {
 102    // add rule to all other RuleSets if they exist
 103  0 for (int i = 1, size = ruleSets.length; i < size; i++) {
 104  0 RuleSet ruleSet = ruleSets[i];
 105   
 106  0 if (ruleSet != null) {
 107  0 ruleSet.addRule(rule);
 108    }
 109    }
 110    }
 111   
 112  28 getRuleSet(matchType).addRule(rule);
 113    }
 114   
 115  0 public void removeRule(Rule rule) {
 116  0 int matchType = rule.getMatchType();
 117  0 String name = rule.getMatchesNodeName();
 118   
 119  0 if (name != null) {
 120  0 if (matchType == Node.ELEMENT_NODE) {
 121  0 removeFromNameMap(elementNameRuleSets, name, rule);
 122  0 } else if (matchType == Node.ATTRIBUTE_NODE) {
 123  0 removeFromNameMap(attributeNameRuleSets, name, rule);
 124    }
 125    }
 126   
 127  0 if (matchType >= Pattern.NUMBER_OF_TYPES) {
 128  0 matchType = Pattern.ANY_NODE;
 129    }
 130   
 131  0 getRuleSet(matchType).removeRule(rule);
 132   
 133  0 if (matchType != Pattern.ANY_NODE) {
 134  0 getRuleSet(Pattern.ANY_NODE).removeRule(rule);
 135    }
 136    }
 137   
 138    /**
 139    * Performs an XSLT processing model match for the rule which matches the
 140    * given Node the best.
 141    *
 142    * @param node
 143    * is the DOM4J Node to match against
 144    *
 145    * @return the matching Rule or no rule if none matched
 146    */
 147  30 public Rule getMatchingRule(Node node) {
 148  30 int matchType = node.getNodeType();
 149   
 150  30 if (matchType == Node.ELEMENT_NODE) {
 151  12 if (elementNameRuleSets != null) {
 152  0 String name = node.getName();
 153  0 RuleSet ruleSet = (RuleSet) elementNameRuleSets.get(name);
 154   
 155  0 if (ruleSet != null) {
 156  0 Rule answer = ruleSet.getMatchingRule(node);
 157   
 158  0 if (answer != null) {
 159  0 return answer;
 160    }
 161    }
 162    }
 163  18 } else if (matchType == Node.ATTRIBUTE_NODE) {
 164  1 if (attributeNameRuleSets != null) {
 165  0 String name = node.getName();
 166  0 RuleSet ruleSet = (RuleSet) attributeNameRuleSets.get(name);
 167   
 168  0 if (ruleSet != null) {
 169  0 Rule answer = ruleSet.getMatchingRule(node);
 170   
 171  0 if (answer != null) {
 172  0 return answer;
 173    }
 174    }
 175    }
 176    }
 177   
 178  30 if ((matchType < 0) || (matchType >= ruleSets.length)) {
 179  0 matchType = Pattern.ANY_NODE;
 180    }
 181   
 182  30 Rule answer = null;
 183  30 RuleSet ruleSet = ruleSets[matchType];
 184   
 185  30 if (ruleSet != null) {
 186    // try rules that match this kind of node first
 187  28 answer = ruleSet.getMatchingRule(node);
 188    }
 189   
 190  30 if ((answer == null) && (matchType != Pattern.ANY_NODE)) {
 191    // try general rules that match any kind of node
 192  2 ruleSet = ruleSets[Pattern.ANY_NODE];
 193   
 194  2 if (ruleSet != null) {
 195  0 answer = ruleSet.getMatchingRule(node);
 196    }
 197    }
 198   
 199  30 return answer;
 200    }
 201   
 202    /**
 203    * DOCUMENT ME!
 204    *
 205    * @param matchType
 206    * DOCUMENT ME!
 207    *
 208    * @return the RuleSet for the given matching type. This method will never
 209    * return null, a new instance will be created.
 210    */
 211  28 protected RuleSet getRuleSet(int matchType) {
 212  28 RuleSet ruleSet = ruleSets[matchType];
 213   
 214  28 if (ruleSet == null) {
 215  14 ruleSet = new RuleSet();
 216  14 ruleSets[matchType] = ruleSet;
 217   
 218    // add the patterns that match any node
 219  14 if (matchType != Pattern.ANY_NODE) {
 220  14 RuleSet allRules = ruleSets[Pattern.ANY_NODE];
 221   
 222  14 if (allRules != null) {
 223  0 ruleSet.addAll(allRules);
 224    }
 225    }
 226    }
 227   
 228  28 return ruleSet;
 229    }
 230   
 231    /**
 232    * Adds the Rule to a RuleSet for the given name.
 233    *
 234    * @param map
 235    * DOCUMENT ME!
 236    * @param name
 237    * DOCUMENT ME!
 238    * @param rule
 239    * DOCUMENT ME!
 240    *
 241    * @return the Map (which will be created if the given map was null
 242    */
 243  0 protected Map addToNameMap(Map map, String name, Rule rule) {
 244  0 if (map == null) {
 245  0 map = new HashMap();
 246    }
 247   
 248  0 RuleSet ruleSet = (RuleSet) map.get(name);
 249   
 250  0 if (ruleSet == null) {
 251  0 ruleSet = new RuleSet();
 252  0 map.put(name, ruleSet);
 253    }
 254   
 255  0 ruleSet.addRule(rule);
 256   
 257  0 return map;
 258    }
 259   
 260  0 protected void removeFromNameMap(Map map, String name, Rule rule) {
 261  0 if (map != null) {
 262  0 RuleSet ruleSet = (RuleSet) map.get(name);
 263   
 264  0 if (ruleSet != null) {
 265  0 ruleSet.removeRule(rule);
 266    }
 267    }
 268    }
 269    }
 270   
 271    /*
 272    * Redistribution and use of this software and associated documentation
 273    * ("Software"), with or without modification, are permitted provided that the
 274    * following conditions are met:
 275    *
 276    * 1. Redistributions of source code must retain copyright statements and
 277    * notices. Redistributions must also contain a copy of this document.
 278    *
 279    * 2. Redistributions in binary form must reproduce the above copyright notice,
 280    * this list of conditions and the following disclaimer in the documentation
 281    * and/or other materials provided with the distribution.
 282    *
 283    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 284    * from this Software without prior written permission of MetaStuff, Ltd. For
 285    * written permission, please contact dom4j-info@metastuff.com.
 286    *
 287    * 4. Products derived from this Software may not be called "DOM4J" nor may
 288    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 289    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 290    *
 291    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 292    *
 293    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 294    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 295    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 296    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 297    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 298    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 299    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 300    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 301    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 302    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 303    * POSSIBILITY OF SUCH DAMAGE.
 304    *
 305    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 306    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/rule/Rule.html0000644000175000017500000025550610242117743020674 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 331   Methods: 25
NCLOC: 115   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
Rule.java 50% 52,1% 60% 54,1%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.rule;
 9   
 10    import org.dom4j.Node;
 11   
 12    /**
 13    * <p>
 14    * <code>Rule</code> matches against DOM4J Node so that some action can be
 15    * performed such as in the XSLT processing model.
 16    * </p>
 17    *
 18    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 19    * @version $Revision: 1.7 $
 20    */
 21    public class Rule implements Comparable {
 22    /** Holds value of property mode. */
 23    private String mode;
 24   
 25    /** Holds value of property importPrecedence. */
 26    private int importPrecedence;
 27   
 28    /** Holds value of property priority. */
 29    private double priority;
 30   
 31    /** Holds value of property appearenceCount. */
 32    private int appearenceCount;
 33   
 34    /** Holds value of property pattern. */
 35    private Pattern pattern;
 36   
 37    /** Holds value of property action. */
 38    private Action action;
 39   
 40  0 public Rule() {
 41  0 this.priority = Pattern.DEFAULT_PRIORITY;
 42    }
 43   
 44  32 public Rule(Pattern pattern) {
 45  32 this.pattern = pattern;
 46  32 this.priority = pattern.getPriority();
 47    }
 48   
 49  28 public Rule(Pattern pattern, Action action) {
 50  28 this(pattern);
 51  28 this.action = action;
 52    }
 53   
 54    /**
 55    * Constructs a new Rule with the same instance data as the given rule but a
 56    * different pattern.
 57    *
 58    * @param that
 59    * DOCUMENT ME!
 60    * @param pattern
 61    * DOCUMENT ME!
 62    */
 63  0 public Rule(Rule that, Pattern pattern) {
 64  0 this.mode = that.mode;
 65  0 this.importPrecedence = that.importPrecedence;
 66  0 this.priority = that.priority;
 67  0 this.appearenceCount = that.appearenceCount;
 68  0 this.action = that.action;
 69  0 this.pattern = pattern;
 70    }
 71   
 72  0 public boolean equals(Object that) {
 73  0 if (that instanceof Rule) {
 74  0 return compareTo((Rule) that) == 0;
 75    }
 76   
 77  0 return false;
 78    }
 79   
 80  2 public int hashCode() {
 81  2 return importPrecedence + appearenceCount;
 82    }
 83   
 84  11 public int compareTo(Object that) {
 85  11 if (that instanceof Rule) {
 86  11 return compareTo((Rule) that);
 87    }
 88   
 89  0 return getClass().getName().compareTo(that.getClass().getName());
 90    }
 91   
 92    /**
 93    * Compares two rules in XSLT processing model order assuming that the modes
 94    * are equal.
 95    *
 96    * @param that
 97    * DOCUMENT ME!
 98    *
 99    * @return DOCUMENT ME!
 100    */
 101  12 public int compareTo(Rule that) {
 102  12 int answer = this.importPrecedence - that.importPrecedence;
 103   
 104  12 if (answer == 0) {
 105  9 answer = (int) Math.round(this.priority - that.priority);
 106   
 107  9 if (answer == 0) {
 108  7 answer = this.appearenceCount - that.appearenceCount;
 109    }
 110    }
 111   
 112  12 return answer;
 113    }
 114   
 115  2 public String toString() {
 116  2 return super.toString() + "[ pattern: " + getPattern() + " action: "
 117    + getAction() + " ]";
 118    }
 119   
 120    /**
 121    * DOCUMENT ME!
 122    *
 123    * @param node
 124    * DOCUMENT ME!
 125    *
 126    * @return true if the pattern matches the given DOM4J node.
 127    */
 128  52 public final boolean matches(Node node) {
 129  52 return pattern.matches(node);
 130    }
 131   
 132    /**
 133    * If this rule contains a union pattern then this method should return an
 134    * array of Rules which describe the union rule, which should contain more
 135    * than one rule. Otherwise this method should return null.
 136    *
 137    * @return an array of the rules which make up this union rule or null if
 138    * this rule is not a union rule
 139    */
 140  14 public Rule[] getUnionRules() {
 141  14 Pattern[] patterns = pattern.getUnionPatterns();
 142   
 143  14 if (patterns == null) {
 144  14 return null;
 145    }
 146   
 147  0 int size = patterns.length;
 148  0 Rule[] answer = new Rule[size];
 149   
 150  0 for (int i = 0; i < size; i++) {
 151  0 answer[i] = new Rule(this, patterns[i]);
 152    }
 153   
 154  0 return answer;
 155    }
 156   
 157    /**
 158    * DOCUMENT ME!
 159    *
 160    * @return the type of node the pattern matches which by default should
 161    * return ANY_NODE if it can match any kind of node.
 162    */
 163  28 public final short getMatchType() {
 164  28 return pattern.getMatchType();
 165    }
 166   
 167    /**
 168    * For patterns which only match an ATTRIBUTE_NODE or an ELEMENT_NODE then
 169    * this pattern may return the name of the element or attribute it matches.
 170    * This allows a more efficient rule matching algorithm to be performed,
 171    * rather than a brute force approach of evaluating every pattern for a
 172    * given Node.
 173    *
 174    * @return the name of the element or attribute this pattern matches or null
 175    * if this pattern matches any or more than one name.
 176    */
 177  28 public final String getMatchesNodeName() {
 178  28 return pattern.getMatchesNodeName();
 179    }
 180   
 181    /**
 182    * Getter for property mode.
 183    *
 184    * @return Value of property mode.
 185    */
 186  14 public String getMode() {
 187  14 return mode;
 188    }
 189   
 190    /**
 191    * Setter for property mode.
 192    *
 193    * @param mode
 194    * New value of property mode.
 195    */
 196  0 public void setMode(String mode) {
 197  0 this.mode = mode;
 198    }
 199   
 200    /**
 201    * Getter for property importPrecedence.
 202    *
 203    * @return Value of property importPrecedence.
 204    */
 205  0 public int getImportPrecedence() {
 206  0 return importPrecedence;
 207    }
 208   
 209    /**
 210    * Setter for property importPrecedence.
 211    *
 212    * @param importPrecedence
 213    * New value of property importPrecedence.
 214    */
 215  14 public void setImportPrecedence(int importPrecedence) {
 216  14 this.importPrecedence = importPrecedence;
 217    }
 218   
 219    /**
 220    * Getter for property priority.
 221    *
 222    * @return Value of property priority.
 223    */
 224  0 public double getPriority() {
 225  0 return priority;
 226    }
 227   
 228    /**
 229    * Setter for property priority.
 230    *
 231    * @param priority
 232    * New value of property priority.
 233    */
 234  0 public void setPriority(double priority) {
 235  0 this.priority = priority;
 236    }
 237   
 238    /**
 239    * Getter for property appearenceCount.
 240    *
 241    * @return Value of property appearenceCount.
 242    */
 243  0 public int getAppearenceCount() {
 244  0 return appearenceCount;
 245    }
 246   
 247    /**
 248    * Setter for property appearenceCount.
 249    *
 250    * @param appearenceCount
 251    * New value of property appearenceCount.
 252    */
 253  14 public void setAppearenceCount(int appearenceCount) {
 254  14 this.appearenceCount = appearenceCount;
 255    }
 256   
 257    /**
 258    * Getter for property pattern.
 259    *
 260    * @return Value of property pattern.
 261    */
 262  2 public Pattern getPattern() {
 263  2 return pattern;
 264    }
 265   
 266    /**
 267    * Setter for property pattern.
 268    *
 269    * @param pattern
 270    * New value of property pattern.
 271    */
 272  0 public void setPattern(Pattern pattern) {
 273  0 this.pattern = pattern;
 274    }
 275   
 276    /**
 277    * Getter for property action.
 278    *
 279    * @return Value of property action.
 280    */
 281  30 public Action getAction() {
 282  30 return action;
 283    }
 284   
 285    /**
 286    * Setter for property action.
 287    *
 288    * @param action
 289    * New value of property action.
 290    */
 291  0 public void setAction(Action action) {
 292  0 this.action = action;
 293    }
 294    }
 295   
 296    /*
 297    * Redistribution and use of this software and associated documentation
 298    * ("Software"), with or without modification, are permitted provided that the
 299    * following conditions are met:
 300    *
 301    * 1. Redistributions of source code must retain copyright statements and
 302    * notices. Redistributions must also contain a copy of this document.
 303    *
 304    * 2. Redistributions in binary form must reproduce the above copyright notice,
 305    * this list of conditions and the following disclaimer in the documentation
 306    * and/or other materials provided with the distribution.
 307    *
 308    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 309    * from this Software without prior written permission of MetaStuff, Ltd. For
 310    * written permission, please contact dom4j-info@metastuff.com.
 311    *
 312    * 4. Products derived from this Software may not be called "DOM4J" nor may
 313    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 314    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 315    *
 316    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 317    *
 318    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 319    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 320    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 321    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 322    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 323    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 324    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 325    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 326    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 327    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 328    * POSSIBILITY OF SUCH DAMAGE.
 329    *
 330    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 331    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/rule/NullAction.html0000644000175000017500000004545410242117652022033 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 63   Methods: 1
NCLOC: 7   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
NullAction.java - - 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.rule;
 9   
 10    import org.dom4j.Node;
 11   
 12    /**
 13    * <p>
 14    * <code>NullAction</code> represents an empty action that does nothing.
 15    * </p>
 16    *
 17    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 18    * @version $Revision: 1.7 $
 19    */
 20    public class NullAction implements Action {
 21    /** Singleton instance */
 22    public static final NullAction SINGLETON = new NullAction();
 23   
 24  0 public void run(Node node) throws Exception {
 25    }
 26    }
 27   
 28    /*
 29    * Redistribution and use of this software and associated documentation
 30    * ("Software"), with or without modification, are permitted provided that the
 31    * following conditions are met:
 32    *
 33    * 1. Redistributions of source code must retain copyright statements and
 34    * notices. Redistributions must also contain a copy of this document.
 35    *
 36    * 2. Redistributions in binary form must reproduce the above copyright notice,
 37    * this list of conditions and the following disclaimer in the documentation
 38    * and/or other materials provided with the distribution.
 39    *
 40    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 41    * from this Software without prior written permission of MetaStuff, Ltd. For
 42    * written permission, please contact dom4j-info@metastuff.com.
 43    *
 44    * 4. Products derived from this Software may not be called "DOM4J" nor may
 45    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 46    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 47    *
 48    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 49    *
 50    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 51    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 52    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 53    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 54    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 55    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 56    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 57    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 58    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 59    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 60    * POSSIBILITY OF SUCH DAMAGE.
 61    *
 62    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 63    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/InvalidXPathException.html0000644000175000017500000005263310242117606023222 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 71   Methods: 3
NCLOC: 14   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
InvalidXPathException.java - 33,3% 33,3% 33,3%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    /**
 11    * <p>
 12    * <code>InvalidXPathException</code> is thrown when an invalid XPath
 13    * expression is used to traverse an XML document
 14    * </p>
 15    *
 16    * @version $Revision: 1.6.2.1 $
 17    */
 18    public class InvalidXPathException extends IllegalArgumentException {
 19    /** The <code>serialVersionUID</code>. */
 20    private static final long serialVersionUID = 3257009869058881592L;
 21   
 22  0 public InvalidXPathException(String xpath) {
 23  0 super("Invalid XPath expression: " + xpath);
 24    }
 25   
 26  4 public InvalidXPathException(String xpath, String reason) {
 27  4 super("Invalid XPath expression: " + xpath + " " + reason);
 28    }
 29   
 30  0 public InvalidXPathException(String xpath, Throwable t) {
 31  0 super("Invalid XPath expression: '" + xpath
 32    + "'. Caused by: " + t.getMessage());
 33    }
 34    }
 35   
 36    /*
 37    * Redistribution and use of this software and associated documentation
 38    * ("Software"), with or without modification, are permitted provided that the
 39    * following conditions are met:
 40    *
 41    * 1. Redistributions of source code must retain copyright statements and
 42    * notices. Redistributions must also contain a copy of this document.
 43    *
 44    * 2. Redistributions in binary form must reproduce the above copyright notice,
 45    * this list of conditions and the following disclaimer in the documentation
 46    * and/or other materials provided with the distribution.
 47    *
 48    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 49    * from this Software without prior written permission of MetaStuff, Ltd. For
 50    * written permission, please contact dom4j-info@metastuff.com.
 51    *
 52    * 4. Products derived from this Software may not be called "DOM4J" nor may
 53    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 54    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 55    *
 56    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 57    *
 58    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 59    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 60    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 61    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 62    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 63    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 64    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 65    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 66    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 67    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 68    * POSSIBILITY OF SUCH DAMAGE.
 69    *
 70    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 71    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/DocumentType.html0000644000175000017500000007444710242117707021441 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 116   Methods: 0
NCLOC: 14   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DocumentType.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    import java.util.List;
 11   
 12    /**
 13    * <p>
 14    * <code>DocumentType</code> defines an XML DOCTYPE declaration.
 15    * </p>
 16    *
 17    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 18    * @version $Revision: 1.10 $
 19    */
 20    public interface DocumentType extends Node {
 21    /**
 22    * This method is the equivalent to the {@link #getName}method. It is added
 23    * for clarity.
 24    *
 25    * @return the root element name for the document type.
 26    */
 27    String getElementName();
 28   
 29    /**
 30    * This method is the equivalent to the {@link #setName}method. It is added
 31    * for clarity.
 32    *
 33    * @param elementName
 34    * DOCUMENT ME!
 35    */
 36    void setElementName(String elementName);
 37   
 38    String getPublicID();
 39   
 40    void setPublicID(String publicID);
 41   
 42    String getSystemID();
 43   
 44    void setSystemID(String systemID);
 45   
 46    /**
 47    * Returns a list of internal DTD declaration objects, defined in the
 48    * {@link org.dom4j.dtd}package
 49    *
 50    * @return DOCUMENT ME!
 51    */
 52    List getInternalDeclarations();
 53   
 54    /**
 55    * Sets the list of internal DTD declaration objects, defined in the
 56    * {@link org.dom4j.dtd}package
 57    *
 58    * @param declarations
 59    * DOCUMENT ME!
 60    */
 61    void setInternalDeclarations(List declarations);
 62   
 63    /**
 64    * Returns a list of internal DTD declaration objects, defined in the
 65    * {@link org.dom4j.dtd}package
 66    *
 67    * @return DOCUMENT ME!
 68    */
 69    List getExternalDeclarations();
 70   
 71    /**
 72    * Sets the list of internal DTD declaration objects, defined in the
 73    * {@link org.dom4j.dtd}package
 74    *
 75    * @param declarations
 76    * DOCUMENT ME!
 77    */
 78    void setExternalDeclarations(List declarations);
 79    }
 80   
 81    /*
 82    * Redistribution and use of this software and associated documentation
 83    * ("Software"), with or without modification, are permitted provided that the
 84    * following conditions are met:
 85    *
 86    * 1. Redistributions of source code must retain copyright statements and
 87    * notices. Redistributions must also contain a copy of this document.
 88    *
 89    * 2. Redistributions in binary form must reproduce the above copyright notice,
 90    * this list of conditions and the following disclaimer in the documentation
 91    * and/or other materials provided with the distribution.
 92    *
 93    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 94    * from this Software without prior written permission of MetaStuff, Ltd. For
 95    * written permission, please contact dom4j-info@metastuff.com.
 96    *
 97    * 4. Products derived from this Software may not be called "DOM4J" nor may
 98    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 99    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 100    *
 101    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 102    *
 103    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 104    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 105    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 106    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 107    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 108    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 109    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 110    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 111    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 112    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 113    * POSSIBILITY OF SUCH DAMAGE.
 114    *
 115    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 116    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/0000755000175000017500000000000012133227266016525 5ustar ebourgebourgdom4j-1.6.1/docs/clover/org/dom4j/io/pkg-classes.html0000644000175000017500000001310210242117702021614 0ustar ebourgebourg dom4j - 1.6.1 org.dom4j.io
Classes
DOMReader (78,2%)
DOMWriter (67,2%)
DispatchHandler (62,9%)
DocumentInputSource (22,7%)
DocumentResult (40%)
DocumentSource (16,7%)
ElementStack (35,2%)
HTMLWriter (37,3%)
HTMLWriter.FormatState (0%)
JAXPHelper (92,3%)
OutputFormat (51,7%)
PruningDispatchHandler (0%)
PruningElementStack (0%)
SAXContentHandler (73,8%)
SAXEventRecorder (0%)
SAXEventRecorder.SAXEvent (0%)
SAXHelper (40,4%)
SAXModifier (0%)
SAXModifyContentHandler (0%)
SAXModifyElementHandler (0%)
SAXModifyException (0%)
SAXModifyReader (0%)
SAXReader (58,4%)
SAXReader.SAXEntityResolver (90,9%)
SAXValidator (0%)
SAXWriter (63,6%)
STAXEventReader (43,1%)
STAXEventWriter (36,2%)
STAXEventWriter.AttributeIterator (36,4%)
STAXEventWriter.NamespaceIterator (36,4%)
XMLResult (41,7%)
XMLWriter (62,3%)
XPP3Reader (46,7%)
XPPReader (0%)
dom4j-1.6.1/docs/clover/org/dom4j/io/JAXPHelper.html0000644000175000017500000007216010242117741021316 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 102   Methods: 3
NCLOC: 26   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
JAXPHelper.java - 100% 66,7% 92,3%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import javax.xml.parsers.DocumentBuilder;
 11    import javax.xml.parsers.DocumentBuilderFactory;
 12    import javax.xml.parsers.SAXParser;
 13    import javax.xml.parsers.SAXParserFactory;
 14   
 15    import org.xml.sax.XMLReader;
 16   
 17    /**
 18    * <code>JAXPHelper</code> contains some helper methods for working with JAXP.
 19    * These methods are kept in a seperate class to avoid class loading issues,
 20    * such that dom4j can work without JAXP on the CLASSPATH
 21    *
 22    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 23    * @version $Revision: 1.7 $
 24    */
 25    class JAXPHelper {
 26  0 protected JAXPHelper() {
 27    }
 28   
 29    /**
 30    * This method attempts to use JAXP to locate the SAX2 XMLReader
 31    * implementation. This method uses reflection to avoid being dependent
 32    * directly on the JAXP classes.
 33    *
 34    * @param validating
 35    * DOCUMENT ME!
 36    * @param namespaceAware
 37    * DOCUMENT ME!
 38    *
 39    * @return DOCUMENT ME!
 40    *
 41    * @throws Exception
 42    * DOCUMENT ME!
 43    */
 44  5764 public static XMLReader createXMLReader(boolean validating,
 45    boolean namespaceAware) throws Exception {
 46  5764 SAXParserFactory factory = SAXParserFactory.newInstance();
 47  5764 factory.setValidating(validating);
 48  5764 factory.setNamespaceAware(namespaceAware);
 49   
 50  5764 SAXParser parser = factory.newSAXParser();
 51   
 52  5764 return parser.getXMLReader();
 53    }
 54   
 55  13 public static org.w3c.dom.Document createDocument(boolean validating,
 56    boolean namespaceAware) throws Exception {
 57  13 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 58  13 factory.setValidating(validating);
 59  13 factory.setNamespaceAware(namespaceAware);
 60   
 61  13 DocumentBuilder builder = factory.newDocumentBuilder();
 62   
 63  13 return builder.newDocument();
 64    }
 65    }
 66   
 67    /*
 68    * Redistribution and use of this software and associated documentation
 69    * ("Software"), with or without modification, are permitted provided that the
 70    * following conditions are met:
 71    *
 72    * 1. Redistributions of source code must retain copyright statements and
 73    * notices. Redistributions must also contain a copy of this document.
 74    *
 75    * 2. Redistributions in binary form must reproduce the above copyright notice,
 76    * this list of conditions and the following disclaimer in the documentation
 77    * and/or other materials provided with the distribution.
 78    *
 79    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 80    * from this Software without prior written permission of MetaStuff, Ltd. For
 81    * written permission, please contact dom4j-info@metastuff.com.
 82    *
 83    * 4. Products derived from this Software may not be called "DOM4J" nor may
 84    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 85    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 86    *
 87    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 88    *
 89    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 90    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 91    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 92    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 93    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 94    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 95    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 96    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 97    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 98    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 99    * POSSIBILITY OF SUCH DAMAGE.
 100    *
 101    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 102    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/XMLWriter.html0000644000175000017500000203040610242117743021252 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 1.934   Methods: 93
NCLOC: 1.101   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
XMLWriter.java 59,5% 64,3% 57% 62,3%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.io.BufferedWriter;
 11    import java.io.IOException;
 12    import java.io.OutputStream;
 13    import java.io.OutputStreamWriter;
 14    import java.io.UnsupportedEncodingException;
 15    import java.io.Writer;
 16    import java.util.HashMap;
 17    import java.util.Iterator;
 18    import java.util.List;
 19    import java.util.Map;
 20    import java.util.StringTokenizer;
 21   
 22    import org.dom4j.Attribute;
 23    import org.dom4j.CDATA;
 24    import org.dom4j.Comment;
 25    import org.dom4j.Document;
 26    import org.dom4j.DocumentType;
 27    import org.dom4j.Element;
 28    import org.dom4j.Entity;
 29    import org.dom4j.Namespace;
 30    import org.dom4j.Node;
 31    import org.dom4j.ProcessingInstruction;
 32    import org.dom4j.Text;
 33    import org.dom4j.tree.NamespaceStack;
 34   
 35    import org.xml.sax.Attributes;
 36    import org.xml.sax.InputSource;
 37    import org.xml.sax.Locator;
 38    import org.xml.sax.SAXException;
 39    import org.xml.sax.SAXNotRecognizedException;
 40    import org.xml.sax.SAXNotSupportedException;
 41    import org.xml.sax.XMLReader;
 42    import org.xml.sax.ext.LexicalHandler;
 43    import org.xml.sax.helpers.XMLFilterImpl;
 44   
 45    /**
 46    * <p>
 47    * <code>XMLWriter</code> takes a DOM4J tree and formats it to a stream as
 48    * XML. It can also take SAX events too so can be used by SAX clients as this
 49    * object implements the {@link org.xml.sax.ContentHandler}and {@link
 50    * LexicalHandler} interfaces. as well. This formatter performs typical document
 51    * formatting. The XML declaration and processing instructions are always on
 52    * their own lines. An {@link OutputFormat}object can be used to define how
 53    * whitespace is handled when printing and allows various configuration options,
 54    * such as to allow suppression of the XML declaration, the encoding declaration
 55    * or whether empty documents are collapsed.
 56    * </p>
 57    *
 58    * <p>
 59    * There are <code>write(...)</code> methods to print any of the standard
 60    * DOM4J classes, including <code>Document</code> and <code>Element</code>,
 61    * to either a <code>Writer</code> or an <code>OutputStream</code>.
 62    * Warning: using your own <code>Writer</code> may cause the writer's
 63    * preferred character encoding to be ignored. If you use encodings other than
 64    * UTF8, we recommend using the method that takes an OutputStream instead.
 65    * </p>
 66    *
 67    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 68    * @author Joseph Bowbeer
 69    * @version $Revision: 1.83.2.2 $
 70    */
 71    public class XMLWriter extends XMLFilterImpl implements LexicalHandler {
 72    private static final String PAD_TEXT = " ";
 73   
 74    protected static final String[] LEXICAL_HANDLER_NAMES = {
 75    "http://xml.org/sax/properties/lexical-handler",
 76    "http://xml.org/sax/handlers/LexicalHandler"};
 77   
 78    protected static final OutputFormat DEFAULT_FORMAT = new OutputFormat();
 79   
 80    /** Should entityRefs by resolved when writing ? */
 81    private boolean resolveEntityRefs = true;
 82   
 83    /**
 84    * Stores the last type of node written so algorithms can refer to the
 85    * previous node type
 86    */
 87    protected int lastOutputNodeType;
 88   
 89    /**
 90    * Stores if the last written element node was a closing tag or an opening
 91    * tag.
 92    */
 93    private boolean lastElementClosed = false;
 94   
 95    /** Stores the xml:space attribute value of preserve for whitespace flag */
 96    protected boolean preserve = false;
 97   
 98    /** The Writer used to output to */
 99    protected Writer writer;
 100   
 101    /** The Stack of namespaceStack written so far */
 102    private NamespaceStack namespaceStack = new NamespaceStack();
 103   
 104    /** The format used by this writer */
 105    private OutputFormat format;
 106   
 107    /** whether we should escape text */
 108    private boolean escapeText = true;
 109   
 110    /**
 111    * The initial number of indentations (so you can print a whole document
 112    * indented, if you like)
 113    */
 114    private int indentLevel = 0;
 115   
 116    /** buffer used when escaping strings */
 117    private StringBuffer buffer = new StringBuffer();
 118   
 119    /**
 120    * whether we have added characters before from the same chunk of characters
 121    */
 122    private boolean charsAdded = false;
 123   
 124    private char lastChar;
 125   
 126    /** Whether a flush should occur after writing a document */
 127    private boolean autoFlush;
 128   
 129    /** Lexical handler we should delegate to */
 130    private LexicalHandler lexicalHandler;
 131   
 132    /**
 133    * Whether comments should appear inside DTD declarations - defaults to
 134    * false
 135    */
 136    private boolean showCommentsInDTDs;
 137   
 138    /** Is the writer curerntly inside a DTD definition? */
 139    private boolean inDTD;
 140   
 141    /** The namespaces used for the current element when consuming SAX events */
 142    private Map namespacesMap;
 143   
 144    /**
 145    * what is the maximum allowed character code such as 127 in US-ASCII (7
 146    * bit) or 255 in ISO- (8 bit) or -1 to not escape any characters (other
 147    * than the special XML characters like &lt; &gt; &amp;)
 148    */
 149    private int maximumAllowedCharacter;
 150   
 151  18 public XMLWriter(Writer writer) {
 152  18 this(writer, DEFAULT_FORMAT);
 153    }
 154   
 155  2143 public XMLWriter(Writer writer, OutputFormat format) {
 156  2143 this.writer = writer;
 157  2143 this.format = format;
 158  2143 namespaceStack.push(Namespace.NO_NAMESPACE);
 159    }
 160   
 161  2 public XMLWriter() {
 162  2 this.format = DEFAULT_FORMAT;
 163  2 this.writer = new BufferedWriter(new OutputStreamWriter(System.out));
 164  2 this.autoFlush = true;
 165  2 namespaceStack.push(Namespace.NO_NAMESPACE);
 166    }
 167   
 168  2 public XMLWriter(OutputStream out) throws UnsupportedEncodingException {
 169  2 this.format = DEFAULT_FORMAT;
 170  2 this.writer = createWriter(out, format.getEncoding());
 171  2 this.autoFlush = true;
 172  2 namespaceStack.push(Namespace.NO_NAMESPACE);
 173    }
 174   
 175  7 public XMLWriter(OutputStream out, OutputFormat format)
 176    throws UnsupportedEncodingException {
 177  7 this.format = format;
 178  7 this.writer = createWriter(out, format.getEncoding());
 179  7 this.autoFlush = true;
 180  7 namespaceStack.push(Namespace.NO_NAMESPACE);
 181    }
 182   
 183  8 public XMLWriter(OutputFormat format) throws UnsupportedEncodingException {
 184  8 this.format = format;
 185  8 this.writer = createWriter(System.out, format.getEncoding());
 186  8 this.autoFlush = true;
 187  8 namespaceStack.push(Namespace.NO_NAMESPACE);
 188    }
 189   
 190  2 public void setWriter(Writer writer) {
 191  2 this.writer = writer;
 192  2 this.autoFlush = false;
 193    }
 194   
 195  8 public void setOutputStream(OutputStream out)
 196    throws UnsupportedEncodingException {
 197  8 this.writer = createWriter(out, format.getEncoding());
 198  8 this.autoFlush = true;
 199    }
 200   
 201    /**
 202    * DOCUMENT ME!
 203    *
 204    * @return true if text thats output should be escaped. This is enabled by
 205    * default. It could be disabled if the output format is textual,
 206    * like in XSLT where we can have xml, html or text output.
 207    */
 208  0 public boolean isEscapeText() {
 209  0 return escapeText;
 210    }
 211   
 212    /**
 213    * Sets whether text output should be escaped or not. This is enabled by
 214    * default. It could be disabled if the output format is textual, like in
 215    * XSLT where we can have xml, html or text output.
 216    *
 217    * @param escapeText
 218    * DOCUMENT ME!
 219    */
 220  1 public void setEscapeText(boolean escapeText) {
 221  1 this.escapeText = escapeText;
 222    }
 223   
 224    /**
 225    * Set the initial indentation level. This can be used to output a document
 226    * (or, more likely, an element) starting at a given indent level, so it's
 227    * not always flush against the left margin. Default: 0
 228    *
 229    * @param indentLevel
 230    * the number of indents to start with
 231    */
 232  0 public void setIndentLevel(int indentLevel) {
 233  0 this.indentLevel = indentLevel;
 234    }
 235   
 236    /**
 237    * Returns the maximum allowed character code that should be allowed
 238    * unescaped which defaults to 127 in US-ASCII (7 bit) or 255 in ISO- (8
 239    * bit).
 240    *
 241    * @return DOCUMENT ME!
 242    */
 243  484095 public int getMaximumAllowedCharacter() {
 244  484095 if (maximumAllowedCharacter == 0) {
 245  2147 maximumAllowedCharacter = defaultMaximumAllowedCharacter();
 246    }
 247   
 248  484095 return maximumAllowedCharacter;
 249    }
 250   
 251    /**
 252    * Sets the maximum allowed character code that should be allowed unescaped
 253    * such as 127 in US-ASCII (7 bit) or 255 in ISO- (8 bit) or -1 to not
 254    * escape any characters (other than the special XML characters like &lt;
 255    * &gt; &amp;) If this is not explicitly set then it is defaulted from the
 256    * encoding.
 257    *
 258    * @param maximumAllowedCharacter
 259    * The maximumAllowedCharacter to set
 260    */
 261  1 public void setMaximumAllowedCharacter(int maximumAllowedCharacter) {
 262  1 this.maximumAllowedCharacter = maximumAllowedCharacter;
 263    }
 264   
 265    /**
 266    * Flushes the underlying Writer
 267    *
 268    * @throws IOException
 269    * DOCUMENT ME!
 270    */
 271  2119 public void flush() throws IOException {
 272  2119 writer.flush();
 273    }
 274   
 275    /**
 276    * Closes the underlying Writer
 277    *
 278    * @throws IOException
 279    * DOCUMENT ME!
 280    */
 281  21 public void close() throws IOException {
 282  21 writer.close();
 283    }
 284   
 285    /**
 286    * Writes the new line text to the underlying Writer
 287    *
 288    * @throws IOException
 289    * DOCUMENT ME!
 290    */
 291  113 public void println() throws IOException {
 292  113 writer.write(format.getLineSeparator());
 293    }
 294   
 295    /**
 296    * Writes the given {@link Attribute}.
 297    *
 298    * @param attribute
 299    * <code>Attribute</code> to output.
 300    *
 301    * @throws IOException
 302    * DOCUMENT ME!
 303    */
 304  0 public void write(Attribute attribute) throws IOException {
 305  0 writeAttribute(attribute);
 306   
 307  0 if (autoFlush) {
 308  0 flush();
 309    }
 310    }
 311   
 312    /**
 313    * <p>
 314    * This will print the <code>Document</code> to the current Writer.
 315    * </p>
 316    *
 317    * <p>
 318    * Warning: using your own Writer may cause the writer's preferred character
 319    * encoding to be ignored. If you use encodings other than UTF8, we
 320    * recommend using the method that takes an OutputStream instead.
 321    * </p>
 322    *
 323    * <p>
 324    * Note: as with all Writers, you may need to flush() yours after this
 325    * method returns.
 326    * </p>
 327    *
 328    * @param doc
 329    * <code>Document</code> to format.
 330    *
 331    * @throws IOException
 332    * if there's any problem writing.
 333    */
 334  113 public void write(Document doc) throws IOException {
 335  113 writeDeclaration();
 336   
 337  113 if (doc.getDocType() != null) {
 338  1 indent();
 339  1 writeDocType(doc.getDocType());
 340    }
 341   
 342  113 for (int i = 0, size = doc.nodeCount(); i < size; i++) {
 343  116 Node node = doc.node(i);
 344  116 writeNode(node);
 345    }
 346   
 347  113 writePrintln();
 348   
 349  113 if (autoFlush) {
 350  16 flush();
 351    }
 352    }
 353   
 354    /**
 355    * <p>
 356    * Writes the <code>{@link Element}</code>, including its <code>{@link
 357    * Attribute}</code>
 358    * s, and its value, and all its content (child nodes) to the current
 359    * Writer.
 360    * </p>
 361    *
 362    * @param element
 363    * <code>Element</code> to output.
 364    *
 365    * @throws IOException
 366    * DOCUMENT ME!
 367    */
 368  2043 public void write(Element element) throws IOException {
 369  2043 writeElement(element);
 370   
 371  2043 if (autoFlush) {
 372  2 flush();
 373    }
 374    }
 375   
 376    /**
 377    * Writes the given {@link CDATA}.
 378    *
 379    * @param cdata
 380    * <code>CDATA</code> to output.
 381    *
 382    * @throws IOException
 383    * DOCUMENT ME!
 384    */
 385  0 public void write(CDATA cdata) throws IOException {
 386  0 writeCDATA(cdata.getText());
 387   
 388  0 if (autoFlush) {
 389  0 flush();
 390    }
 391    }
 392   
 393    /**
 394    * Writes the given {@link Comment}.
 395    *
 396    * @param comment
 397    * <code>Comment</code> to output.
 398    *
 399    * @throws IOException
 400    * DOCUMENT ME!
 401    */
 402  0 public void write(Comment comment) throws IOException {
 403  0 writeComment(comment.getText());
 404   
 405  0 if (autoFlush) {
 406  0 flush();
 407    }
 408    }
 409   
 410    /**
 411    * Writes the given {@link DocumentType}.
 412    *
 413    * @param docType
 414    * <code>DocumentType</code> to output.
 415    *
 416    * @throws IOException
 417    * DOCUMENT ME!
 418    */
 419  0 public void write(DocumentType docType) throws IOException {
 420  0 writeDocType(docType);
 421   
 422  0 if (autoFlush) {
 423  0 flush();
 424    }
 425    }
 426   
 427    /**
 428    * Writes the given {@link Entity}.
 429    *
 430    * @param entity
 431    * <code>Entity</code> to output.
 432    *
 433    * @throws IOException
 434    * DOCUMENT ME!
 435    */
 436  0 public void write(Entity entity) throws IOException {
 437  0 writeEntity(entity);
 438   
 439  0 if (autoFlush) {
 440  0 flush();
 441    }
 442    }
 443   
 444    /**
 445    * Writes the given {@link Namespace}.
 446    *
 447    * @param namespace
 448    * <code>Namespace</code> to output.
 449    *
 450    * @throws IOException
 451    * DOCUMENT ME!
 452    */
 453  0 public void write(Namespace namespace) throws IOException {
 454  0 writeNamespace(namespace);
 455   
 456  0 if (autoFlush) {
 457  0 flush();
 458    }
 459    }
 460   
 461    /**
 462    * Writes the given {@link ProcessingInstruction}.
 463    *
 464    * @param processingInstruction
 465    * <code>ProcessingInstruction</code> to output.
 466    *
 467    * @throws IOException
 468    * DOCUMENT ME!
 469    */
 470  0 public void write(ProcessingInstruction processingInstruction)
 471    throws IOException {
 472  0 writeProcessingInstruction(processingInstruction);
 473   
 474  0 if (autoFlush) {
 475  0 flush();
 476    }
 477    }
 478   
 479    /**
 480    * <p>
 481    * Print out a {@link String}, Perfoms the necessary entity escaping and
 482    * whitespace stripping.
 483    * </p>
 484    *
 485    * @param text
 486    * is the text to output
 487    *
 488    * @throws IOException
 489    * DOCUMENT ME!
 490    */
 491  0 public void write(String text) throws IOException {
 492  0 writeString(text);
 493   
 494  0 if (autoFlush) {
 495  0 flush();
 496    }
 497    }
 498   
 499    /**
 500    * Writes the given {@link Text}.
 501    *
 502    * @param text
 503    * <code>Text</code> to output.
 504    *
 505    * @throws IOException
 506    * DOCUMENT ME!
 507    */
 508  0 public void write(Text text) throws IOException {
 509  0 writeString(text.getText());
 510   
 511  0 if (autoFlush) {
 512  0 flush();
 513    }
 514    }
 515   
 516    /**
 517    * Writes the given {@link Node}.
 518    *
 519    * @param node
 520    * <code>Node</code> to output.
 521    *
 522    * @throws IOException
 523    * DOCUMENT ME!
 524    */
 525  1 public void write(Node node) throws IOException {
 526  1 writeNode(node);
 527   
 528  1 if (autoFlush) {
 529  0 flush();
 530    }
 531    }
 532   
 533    /**
 534    * Writes the given object which should be a String, a Node or a List of
 535    * Nodes.
 536    *
 537    * @param object
 538    * is the object to output.
 539    *
 540    * @throws IOException
 541    * DOCUMENT ME!
 542    */
 543  1 public void write(Object object) throws IOException {
 544  1 if (object instanceof Node) {
 545  1 write((Node) object);
 546  0 } else if (object instanceof String) {
 547  0 write((String) object);
 548  0 } else if (object instanceof List) {
 549  0 List list = (List) object;
 550   
 551  0 for (int i = 0, size = list.size(); i < size; i++) {
 552  0 write(list.get(i));
 553    }
 554  0 } else if (object != null) {
 555  0 throw new IOException("Invalid object: " + object);
 556    }
 557    }
 558   
 559    /**
 560    * <p>
 561    * Writes the opening tag of an {@link Element}, including its {@link
 562    * Attribute}s but without its content.
 563    * </p>
 564    *
 565    * @param element
 566    * <code>Element</code> to output.
 567    *
 568    * @throws IOException
 569    * DOCUMENT ME!
 570    */
 571  0 public void writeOpen(Element element) throws IOException {
 572  0 writer.write("<");
 573  0 writer.write(element.getQualifiedName());
 574  0 writeAttributes(element);
 575  0 writer.write(">");
 576    }
 577   
 578    /**
 579    * <p>
 580    * Writes the closing tag of an {@link Element}
 581    * </p>
 582    *
 583    * @param element
 584    * <code>Element</code> to output.
 585    *
 586    * @throws IOException
 587    * DOCUMENT ME!
 588    */
 589  0 public void writeClose(Element element) throws IOException {
 590  0 writeClose(element.getQualifiedName());
 591    }
 592   
 593    // XMLFilterImpl methods
 594    // -------------------------------------------------------------------------
 595  0 public void parse(InputSource source) throws IOException, SAXException {
 596  0 installLexicalHandler();
 597  0 super.parse(source);
 598    }
 599   
 600  0 public void setProperty(String name, Object value)
 601    throws SAXNotRecognizedException, SAXNotSupportedException {
 602  0 for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
 603  0 if (LEXICAL_HANDLER_NAMES[i].equals(name)) {
 604  0 setLexicalHandler((LexicalHandler) value);
 605   
 606  0 return;
 607    }
 608    }
 609   
 610  0 super.setProperty(name, value);
 611    }
 612   
 613  0 public Object getProperty(String name) throws SAXNotRecognizedException,
 614    SAXNotSupportedException {
 615  0 for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
 616  0 if (LEXICAL_HANDLER_NAMES[i].equals(name)) {
 617  0 return getLexicalHandler();
 618    }
 619    }
 620   
 621  0 return super.getProperty(name);
 622    }
 623   
 624  0 public void setLexicalHandler(LexicalHandler handler) {
 625  0 if (handler == null) {
 626  0 throw new NullPointerException("Null lexical handler");
 627    } else {
 628  0 this.lexicalHandler = handler;
 629    }
 630    }
 631   
 632  0 public LexicalHandler getLexicalHandler() {
 633  0 return lexicalHandler;
 634    }
 635   
 636    // ContentHandler interface
 637    // -------------------------------------------------------------------------
 638  1 public void setDocumentLocator(Locator locator) {
 639  1 super.setDocumentLocator(locator);
 640    }
 641   
 642  4 public void startDocument() throws SAXException {
 643  4 try {
 644  4 writeDeclaration();
 645  4 super.startDocument();
 646    } catch (IOException e) {
 647  0 handleException(e);
 648    }
 649    }
 650   
 651  4 public void endDocument() throws SAXException {
 652  4 super.endDocument();
 653   
 654  4 if (autoFlush) {
 655  0 try {
 656  0 flush();
 657    } catch (IOException e) {
 658    }
 659    }
 660    }
 661   
 662  0 public void startPrefixMapping(String prefix, String uri)
 663    throws SAXException {
 664  0 if (namespacesMap == null) {
 665  0 namespacesMap = new HashMap();
 666    }
 667   
 668  0 namespacesMap.put(prefix, uri);
 669  0 super.startPrefixMapping(prefix, uri);
 670    }
 671   
 672  0 public void endPrefixMapping(String prefix) throws SAXException {
 673  0 super.endPrefixMapping(prefix);
 674    }
 675   
 676  8 public void startElement(String namespaceURI, String localName,
 677    String qName, Attributes attributes) throws SAXException {
 678  8 try {
 679  8 charsAdded = false;
 680   
 681  8 writePrintln();
 682  8 indent();
 683  8 writer.write("<");
 684  8 writer.write(qName);
 685  8 writeNamespaces();
 686  8 writeAttributes(attributes);
 687  8 writer.write(">");
 688  8 ++indentLevel;
 689  8 lastOutputNodeType = Node.ELEMENT_NODE;
 690  8 lastElementClosed = false;
 691   
 692  8 super.startElement(namespaceURI, localName, qName, attributes);
 693    } catch (IOException e) {
 694  0 handleException(e);
 695    }
 696    }
 697   
 698  8 public void endElement(String namespaceURI, String localName, String qName)
 699    throws SAXException {
 700  8 try {
 701  8 charsAdded = false;
 702  8 --indentLevel;
 703   
 704  8 if (lastElementClosed) {
 705  4 writePrintln();
 706  4 indent();
 707    }
 708   
 709    // XXXX: need to determine this using a stack and checking for
 710    // content / children
 711  8 boolean hadContent = true;
 712   
 713  8 if (hadContent) {
 714  8 writeClose(qName);
 715    } else {
 716  0 writeEmptyElementClose(qName);
 717    }
 718   
 719  8 lastOutputNodeType = Node.ELEMENT_NODE;
 720  8 lastElementClosed = true;
 721   
 722  8 super.endElement(namespaceURI, localName, qName);
 723    } catch (IOException e) {
 724  0 handleException(e);
 725    }
 726    }
 727   
 728  16 public void characters(char[] ch, int start, int length)
 729    throws SAXException {
 730  16 if ((ch == null) || (ch.length == 0) || (length <= 0)) {
 731  1 return;
 732    }
 733   
 734  15 try {
 735    /*
 736    * we can't use the writeString method here because it's possible we
 737    * don't receive all characters at once and calling writeString
 738    * would cause unwanted spaces to be added in between these chunks
 739    * of character arrays.
 740    */
 741  15 String string = String.valueOf(ch, start, length);
 742   
 743  15 if (escapeText) {
 744  14 string = escapeElementEntities(string);
 745    }
 746   
 747  15 if (format.isTrimText()) {
 748  14 if ((lastOutputNodeType == Node.TEXT_NODE) && !charsAdded) {
 749  0 writer.write(' ');
 750  14 } else if (charsAdded && Character.isWhitespace(lastChar)) {
 751  1 writer.write(' ');
 752  13 } else if (lastOutputNodeType == Node.ELEMENT_NODE
 753    && format.isPadText() && lastElementClosed
 754    && Character.isWhitespace(ch[0])) {
 755  1 writer.write(PAD_TEXT);
 756    }
 757   
 758  14 String delim = "";
 759  14 StringTokenizer tokens = new StringTokenizer(string);
 760   
 761  14 while (tokens.hasMoreTokens()) {
 762  17 writer.write(delim);
 763  17 writer.write(tokens.nextToken());
 764  17 delim = " ";
 765    }
 766    } else {
 767  1 writer.write(string);
 768    }
 769   
 770  15 charsAdded = true;
 771  15 lastChar = ch[(start + length) - 1];
 772  15 lastOutputNodeType = Node.TEXT_NODE;
 773   
 774  15 super.characters(ch, start, length);
 775    } catch (IOException e) {
 776  0 handleException(e);
 777    }
 778    }
 779   
 780  0 public void ignorableWhitespace(char[] ch, int start, int length)
 781    throws SAXException {
 782  0 super.ignorableWhitespace(ch, start, length);
 783    }
 784   
 785  0 public void processingInstruction(String target, String data)
 786    throws SAXException {
 787  0 try {
 788  0 indent();
 789  0 writer.write("<?");
 790  0 writer.write(target);
 791  0 writer.write(" ");
 792  0 writer.write(data);
 793  0 writer.write("?>");
 794  0 writePrintln();
 795  0 lastOutputNodeType = Node.PROCESSING_INSTRUCTION_NODE;
 796   
 797  0 super.processingInstruction(target, data);
 798    } catch (IOException e) {
 799  0 handleException(e);
 800    }
 801    }
 802   
 803    // DTDHandler interface
 804    // -------------------------------------------------------------------------
 805  0 public void notationDecl(String name, String publicID, String systemID)
 806    throws SAXException {
 807  0 super.notationDecl(name, publicID, systemID);
 808    }
 809   
 810  0 public void unparsedEntityDecl(String name, String publicID,
 811    String systemID, String notationName) throws SAXException {
 812  0 super.unparsedEntityDecl(name, publicID, systemID, notationName);
 813    }
 814   
 815    // LexicalHandler interface
 816    // -------------------------------------------------------------------------
 817  0 public void startDTD(String name, String publicID, String systemID)
 818    throws SAXException {
 819  0 inDTD = true;
 820   
 821  0 try {
 822  0 writeDocType(name, publicID, systemID);
 823    } catch (IOException e) {
 824  0 handleException(e);
 825    }
 826   
 827  0 if (lexicalHandler != null) {
 828  0 lexicalHandler.startDTD(name, publicID, systemID);
 829    }
 830    }
 831   
 832  0 public void endDTD() throws SAXException {
 833  0 inDTD = false;
 834   
 835  0 if (lexicalHandler != null) {
 836  0 lexicalHandler.endDTD();
 837    }
 838    }
 839   
 840  0 public void startCDATA() throws SAXException {
 841  0 try {
 842  0 writer.write("<![CDATA[");
 843    } catch (IOException e) {
 844  0 handleException(e);
 845    }
 846   
 847  0 if (lexicalHandler != null) {
 848  0 lexicalHandler.startCDATA();
 849    }
 850    }
 851   
 852  0 public void endCDATA() throws SAXException {
 853  0 try {
 854  0 writer.write("]]>");
 855    } catch (IOException e) {
 856  0 handleException(e);
 857    }
 858   
 859  0 if (lexicalHandler != null) {
 860  0 lexicalHandler.endCDATA();
 861    }
 862    }
 863   
 864  0 public void startEntity(String name) throws SAXException {
 865  0 try {
 866  0 writeEntityRef(name);
 867    } catch (IOException e) {
 868  0 handleException(e);
 869    }
 870   
 871  0 if (lexicalHandler != null) {
 872  0 lexicalHandler.startEntity(name);
 873    }
 874    }
 875   
 876  0 public void endEntity(String name) throws SAXException {
 877  0 if (lexicalHandler != null) {
 878  0 lexicalHandler.endEntity(name);
 879    }
 880    }
 881   
 882  0 public void comment(char[] ch, int start, int length) throws SAXException {
 883  0 if (showCommentsInDTDs || !inDTD) {
 884  0 try {
 885  0 charsAdded = false;
 886  0 writeComment(new String(ch, start, length));
 887    } catch (IOException e) {
 888  0 handleException(e);
 889    }
 890    }
 891   
 892  0 if (lexicalHandler != null) {
 893  0 lexicalHandler.comment(ch, start, length);
 894    }
 895    }
 896   
 897    // Implementation methods
 898    // -------------------------------------------------------------------------
 899  20077 protected void writeElement(Element element) throws IOException {
 900  20077 int size = element.nodeCount();
 901  20077 String qualifiedName = element.getQualifiedName();
 902   
 903  20077 writePrintln();
 904  20077 indent();
 905   
 906  20077 writer.write("<");
 907  20077 writer.write(qualifiedName);
 908   
 909  20077 int previouslyDeclaredNamespaces = namespaceStack.size();
 910  20077 Namespace ns = element.getNamespace();
 911   
 912  20077 if (isNamespaceDeclaration(ns)) {
 913  602 namespaceStack.push(ns);
 914  602 writeNamespace(ns);
 915    }
 916   
 917    // Print out additional namespace declarations
 918  20077 boolean textOnly = true;
 919   
 920  20077 for (int i = 0; i < size; i++) {
 921  56305 Node node = element.node(i);
 922   
 923  56305 if (node instanceof Namespace) {
 924  198 Namespace additional = (Namespace) node;
 925   
 926  198 if (isNamespaceDeclaration(additional)) {
 927  16 namespaceStack.push(additional);
 928  16 writeNamespace(additional);
 929    }
 930  56107 } else if (node instanceof Element) {
 931  17921 textOnly = false;
 932  38186 } else if (node instanceof Comment) {
 933  445 textOnly = false;
 934    }
 935    }
 936   
 937  20077 writeAttributes(element);
 938   
 939  20077 lastOutputNodeType = Node.ELEMENT_NODE;
 940   
 941  20077 if (size <= 0) {
 942  300 writeEmptyElementClose(qualifiedName);
 943    } else {
 944  19777 writer.write(">");
 945   
 946  19777 if (textOnly) {
 947    // we have at least one text node so lets assume
 948    // that its non-empty
 949  14954 writeElementContent(element);
 950    } else {
 951    // we know it's not null or empty from above
 952  4823 ++indentLevel;
 953   
 954  4823 writeElementContent(element);
 955   
 956  4823 --indentLevel;
 957   
 958  4823 writePrintln();
 959  4823 indent();
 960    }
 961   
 962  19777 writer.write("</");
 963  19777 writer.write(qualifiedName);
 964  19777 writer.write(">");
 965    }
 966   
 967    // remove declared namespaceStack from stack
 968  20077 while (namespaceStack.size() > previouslyDeclaredNamespaces) {
 969  620 namespaceStack.pop();
 970    }
 971   
 972  20077 lastOutputNodeType = Node.ELEMENT_NODE;
 973    }
 974   
 975    /**
 976    * Determines if element is a special case of XML elements where it contains
 977    * an xml:space attribute of "preserve". If it does, then retain whitespace.
 978    *
 979    * @param element
 980    * DOCUMENT ME!
 981    *
 982    * @return DOCUMENT ME!
 983    */
 984  93 protected final boolean isElementSpacePreserved(Element element) {
 985  93 final Attribute attr = (Attribute) element.attribute("space");
 986  93 boolean preserveFound = preserve; // default to global state
 987   
 988  93 if (attr != null) {
 989  5 if ("xml".equals(attr.getNamespacePrefix())
 990    && "preserve".equals(attr.getText())) {
 991  4 preserveFound = true;
 992    } else {
 993  1 preserveFound = false;
 994    }
 995    }
 996   
 997  93 return preserveFound;
 998    }
 999   
 1000    /**
 1001    * Outputs the content of the given element. If whitespace trimming is
 1002    * enabled then all adjacent text nodes are appended together before the
 1003    * whitespace trimming occurs to avoid problems with multiple text nodes
 1004    * being created due to text content that spans parser buffers in a SAX
 1005    * parser.
 1006    *
 1007    * @param element
 1008    * DOCUMENT ME!
 1009    *
 1010    * @throws IOException
 1011    * DOCUMENT ME!
 1012    */
 1013  19777 protected void writeElementContent(Element element) throws IOException {
 1014  19777 boolean trim = format.isTrimText();
 1015  19777 boolean oldPreserve = preserve;
 1016   
 1017  19777 if (trim) { // verify we have to before more expensive test
 1018  93 preserve = isElementSpacePreserved(element);
 1019  93 trim = !preserve;
 1020    }
 1021   
 1022  19777 if (trim) {
 1023    // concatenate adjacent text nodes together
 1024    // so that whitespace trimming works properly
 1025  82 Text lastTextNode = null;
 1026  82 StringBuffer buff = null;
 1027  82 boolean textOnly = true;
 1028   
 1029  82 for (int i = 0, size = element.nodeCount(); i < size; i++) {
 1030  146 Node node = element.node(i);
 1031   
 1032  146 if (node instanceof Text) {
 1033  76 if (lastTextNode == null) {
 1034  53 lastTextNode = (Text) node;
 1035    } else {
 1036  23 if (buff == null) {
 1037  9 buff = new StringBuffer(lastTextNode.getText());
 1038    }
 1039   
 1040  23 buff.append(((Text) node).getText());
 1041    }
 1042    } else {
 1043  70 if (!textOnly && format.isPadText()) {
 1044    // only add the PAD_TEXT if the text itself starts with
 1045    // whitespace
 1046  7 char firstChar = 'a';
 1047  7 if (buff != null) {
 1048  0 firstChar = buff.charAt(0);
 1049  7 } else if (lastTextNode != null) {
 1050  0 firstChar = lastTextNode.getText().charAt(0);
 1051    }
 1052   
 1053  7 if (Character.isWhitespace(firstChar)) {
 1054  0 writer.write(PAD_TEXT);
 1055    }
 1056    }
 1057   
 1058  70 if (lastTextNode != null) {
 1059  17 if (buff != null) {
 1060  2 writeString(buff.toString());
 1061  2 buff = null;
 1062    } else {
 1063  15 writeString(lastTextNode.getText());
 1064    }
 1065   
 1066  17 if (format.isPadText()) {
 1067    // only add the PAD_TEXT if the text itself ends
 1068    // with whitespace
 1069  10 char lastTextChar = 'a';
 1070  10 if (buff != null) {
 1071  0 lastTextChar = buff.charAt(buff.length() - 1);
 1072  10 } else if (lastTextNode != null) {
 1073  10 String txt = lastTextNode.getText();
 1074  10 lastTextChar = txt.charAt(txt.length() - 1);
 1075    }
 1076   
 1077  10 if (Character.isWhitespace(lastTextChar)) {
 1078  1 writer.write(PAD_TEXT);
 1079    }
 1080    }
 1081   
 1082  17 lastTextNode = null;
 1083    }
 1084   
 1085  70 textOnly = false;
 1086  70 writeNode(node);
 1087    }
 1088    }
 1089   
 1090  82 if (lastTextNode != null) {
 1091  36 if (!textOnly && format.isPadText()) {
 1092    // only add the PAD_TEXT if the text itself starts with
 1093    // whitespace
 1094  3 char firstChar = 'a';
 1095  3 if (buff != null) {
 1096  0 firstChar = buff.charAt(0);
 1097    } else {
 1098  3 firstChar = lastTextNode.getText().charAt(0);
 1099    }
 1100   
 1101  3 if (Character.isWhitespace(firstChar)) {
 1102  2 writer.write(PAD_TEXT);
 1103    }
 1104    }
 1105   
 1106  36 if (buff != null) {
 1107  7 writeString(buff.toString());
 1108  7 buff = null;
 1109    } else {
 1110  29 writeString(lastTextNode.getText());
 1111    }
 1112   
 1113  36 lastTextNode = null;
 1114    }
 1115    } else {
 1116  19695 Node lastTextNode = null;
 1117   
 1118  19695 for (int i = 0, size = element.nodeCount(); i < size; i++) {
 1119  56159 Node node = element.node(i);
 1120   
 1121  56159 if (node instanceof Text) {
 1122  37643 writeNode(node);
 1123  37643 lastTextNode = node;
 1124    } else {
 1125  18516 if ((lastTextNode != null) && format.isPadText()) {
 1126    // only add the PAD_TEXT if the text itself ends with
 1127    // whitespace
 1128  0 String txt = lastTextNode.getText();
 1129  0 char lastTextChar = txt.charAt(txt.length() - 1);
 1130   
 1131  0 if (Character.isWhitespace(lastTextChar)) {
 1132  0 writer.write(PAD_TEXT);
 1133    }
 1134    }
 1135   
 1136  18516 writeNode(node);
 1137   
 1138    // if ((lastTextNode != null) && format.isPadText()) {
 1139    // writer.write(PAD_TEXT);
 1140    // }
 1141   
 1142  18516 lastTextNode = null;
 1143    }
 1144    }
 1145    }
 1146   
 1147  19777 preserve = oldPreserve;
 1148    }
 1149   
 1150  21 protected void writeCDATA(String text) throws IOException {
 1151  21 writer.write("<![CDATA[");
 1152   
 1153  21 if (text != null) {
 1154  17 writer.write(text);
 1155    }
 1156   
 1157  21 writer.write("]]>");
 1158   
 1159  21 lastOutputNodeType = Node.CDATA_SECTION_NODE;
 1160    }
 1161   
 1162  1 protected void writeDocType(DocumentType docType) throws IOException {
 1163  1 if (docType != null) {
 1164  1 docType.write(writer);
 1165  1 writePrintln();
 1166    }
 1167    }
 1168   
 1169  618 protected void writeNamespace(Namespace namespace) throws IOException {
 1170  618 if (namespace != null) {
 1171  618 writeNamespace(namespace.getPrefix(), namespace.getURI());
 1172    }
 1173    }
 1174   
 1175    /**
 1176    * Writes the SAX namepsaces
 1177    *
 1178    * @throws IOException
 1179    * DOCUMENT ME!
 1180    */
 1181  8 protected void writeNamespaces() throws IOException {
 1182  8 if (namespacesMap != null) {
 1183  0 for (Iterator iter = namespacesMap.entrySet().iterator(); iter
 1184    .hasNext();) {
 1185  0 Map.Entry entry = (Map.Entry) iter.next();
 1186  0 String prefix = (String) entry.getKey();
 1187  0 String uri = (String) entry.getValue();
 1188  0 writeNamespace(prefix, uri);
 1189    }
 1190   
 1191  0 namespacesMap = null;
 1192    }
 1193    }
 1194   
 1195    /**
 1196    * Writes the SAX namepsaces
 1197    *
 1198    * @param prefix
 1199    * the prefix
 1200    * @param uri
 1201    * the namespace uri
 1202    *
 1203    * @throws IOException
 1204    */
 1205  620 protected void writeNamespace(String prefix, String uri)
 1206    throws IOException {
 1207  620 if ((prefix != null) && (prefix.length() > 0)) {
 1208  566 writer.write(" xmlns:");
 1209  566 writer.write(prefix);
 1210  566 writer.write("=\"");
 1211    } else {
 1212  54 writer.write(" xmlns=\"");
 1213    }
 1214   
 1215  620 writer.write(uri);
 1216  620 writer.write("\"");
 1217    }
 1218   
 1219  1 protected void writeProcessingInstruction(ProcessingInstruction pi)
 1220    throws IOException {
 1221    // indent();
 1222  1 writer.write("<?");
 1223  1 writer.write(pi.getName());
 1224  1 writer.write(" ");
 1225  1 writer.write(pi.getText());
 1226  1 writer.write("?>");
 1227  1 writePrintln();
 1228   
 1229  1 lastOutputNodeType = Node.PROCESSING_INSTRUCTION_NODE;
 1230    }
 1231   
 1232  53 protected void writeString(String text) throws IOException {
 1233  53 if ((text != null) && (text.length() > 0)) {
 1234  51 if (escapeText) {
 1235  51 text = escapeElementEntities(text);
 1236    }
 1237   
 1238    // if (format.isPadText()) {
 1239    // if (lastOutputNodeType == Node.ELEMENT_NODE) {
 1240    // writer.write(PAD_TEXT);
 1241    // }
 1242    // }
 1243  51 if (format.isTrimText()) {
 1244  51 boolean first = true;
 1245  51 StringTokenizer tokenizer = new StringTokenizer(text);
 1246   
 1247  51 while (tokenizer.hasMoreTokens()) {
 1248  134 String token = tokenizer.nextToken();
 1249   
 1250  134 if (first) {
 1251  47 first = false;
 1252   
 1253  47 if (lastOutputNodeType == Node.TEXT_NODE) {
 1254  0 writer.write(" ");
 1255    }
 1256    } else {
 1257  87 writer.write(" ");
 1258    }
 1259   
 1260  134 writer.write(token);
 1261  134 lastOutputNodeType = Node.TEXT_NODE;
 1262  134 lastChar = token.charAt(token.length() - 1);
 1263    }
 1264    } else {
 1265  0 lastOutputNodeType = Node.TEXT_NODE;
 1266  0 writer.write(text);
 1267  0 lastChar = text.charAt(text.length() - 1);
 1268    }
 1269    }
 1270    }
 1271   
 1272    /**
 1273    * This method is used to write out Nodes that contain text and still allow
 1274    * for xml:space to be handled properly.
 1275    *
 1276    * @param node
 1277    * DOCUMENT ME!
 1278    *
 1279    * @throws IOException
 1280    * DOCUMENT ME!
 1281    */
 1282  37643 protected void writeNodeText(Node node) throws IOException {
 1283  37643 String text = node.getText();
 1284   
 1285  37643 if ((text != null) && (text.length() > 0)) {
 1286  37643 if (escapeText) {
 1287  37643 text = escapeElementEntities(text);
 1288    }
 1289   
 1290  37643 lastOutputNodeType = Node.TEXT_NODE;
 1291  37643 writer.write(text);
 1292  37643 lastChar = text.charAt(text.length() - 1);
 1293    }
 1294    }
 1295   
 1296  56346 protected void writeNode(Node node) throws IOException {
 1297  56346 int nodeType = node.getNodeType();
 1298   
 1299  56346 switch (nodeType) {
 1300  18034 case Node.ELEMENT_NODE:
 1301  18034 writeElement((Element) node);
 1302   
 1303  18034 break;
 1304   
 1305  0 case Node.ATTRIBUTE_NODE:
 1306  0 writeAttribute((Attribute) node);
 1307   
 1308  0 break;
 1309   
 1310  37643 case Node.TEXT_NODE:
 1311  37643 writeNodeText(node);
 1312   
 1313    // write((Text) node);
 1314  37643 break;
 1315   
 1316  22 case Node.CDATA_SECTION_NODE:
 1317  22 writeCDATA(node.getText());
 1318   
 1319  22 break;
 1320   
 1321  0 case Node.ENTITY_REFERENCE_NODE:
 1322  0 writeEntity((Entity) node);
 1323   
 1324  0 break;
 1325   
 1326  1 case Node.PROCESSING_INSTRUCTION_NODE:
 1327  1 writeProcessingInstruction((ProcessingInstruction) node);
 1328   
 1329  1 break;
 1330   
 1331  447 case Node.COMMENT_NODE:
 1332  447 writeComment(node.getText());
 1333   
 1334  447 break;
 1335   
 1336  1 case Node.DOCUMENT_NODE:
 1337  1 write((Document) node);
 1338   
 1339  1 break;
 1340   
 1341  0 case Node.DOCUMENT_TYPE_NODE:
 1342  0 writeDocType((DocumentType) node);
 1343   
 1344  0 break;
 1345   
 1346  198 case Node.NAMESPACE_NODE:
 1347   
 1348    // Will be output with attributes
 1349    // write((Namespace) node);
 1350  198 break;
 1351   
 1352  0 default:
 1353  0 throw new IOException("Invalid node type: " + node);
 1354    }
 1355    }
 1356   
 1357  0 protected void installLexicalHandler() {
 1358  0 XMLReader parent = getParent();
 1359   
 1360  0 if (parent == null) {
 1361  0 throw new NullPointerException("No parent for filter");
 1362    }
 1363   
 1364    // try to register for lexical events
 1365  0 for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
 1366  0 try {
 1367  0 parent.setProperty(LEXICAL_HANDLER_NAMES[i], this);
 1368   
 1369  0 break;
 1370    } catch (SAXNotRecognizedException ex) {
 1371    // ignore
 1372    } catch (SAXNotSupportedException ex) {
 1373    // ignore
 1374    }
 1375    }
 1376    }
 1377   
 1378  0 protected void writeDocType(String name, String publicID, String systemID)
 1379    throws IOException {
 1380  0 boolean hasPublic = false;
 1381   
 1382  0 writer.write("<!DOCTYPE ");
 1383  0 writer.write(name);
 1384   
 1385  0 if ((publicID != null) && (!publicID.equals(""))) {
 1386  0 writer.write(" PUBLIC \"");
 1387  0 writer.write(publicID);
 1388  0 writer.write("\"");
 1389  0 hasPublic = true;
 1390    }
 1391   
 1392  0 if ((systemID != null) && (!systemID.equals(""))) {
 1393  0 if (!hasPublic) {
 1394  0 writer.write(" SYSTEM");
 1395    }
 1396   
 1397  0 writer.write(" \"");
 1398  0 writer.write(systemID);
 1399  0 writer.write("\"");
 1400    }
 1401   
 1402  0 writer.write(">");
 1403  0 writePrintln();
 1404    }
 1405   
 1406  0 protected void writeEntity(Entity entity) throws IOException {
 1407  0 if (!resolveEntityRefs()) {
 1408  0 writeEntityRef(entity.getName());
 1409    } else {
 1410  0 writer.write(entity.getText());
 1411    }
 1412    }
 1413   
 1414  0 protected void writeEntityRef(String name) throws IOException {
 1415  0 writer.write("&");
 1416  0 writer.write(name);
 1417  0 writer.write(";");
 1418   
 1419  0 lastOutputNodeType = Node.ENTITY_REFERENCE_NODE;
 1420    }
 1421   
 1422  447 protected void writeComment(String text) throws IOException {
 1423  447 if (format.isNewlines()) {
 1424  3 println();
 1425  3 indent();
 1426    }
 1427   
 1428  447 writer.write("<!--");
 1429  447 writer.write(text);
 1430  447 writer.write("-->");
 1431   
 1432  447 lastOutputNodeType = Node.COMMENT_NODE;
 1433    }
 1434   
 1435    /**
 1436    * Writes the attributes of the given element
 1437    *
 1438    * @param element
 1439    * DOCUMENT ME!
 1440    *
 1441    * @throws IOException
 1442    * DOCUMENT ME!
 1443    */
 1444  20077 protected void writeAttributes(Element element) throws IOException {
 1445    // I do not yet handle the case where the same prefix maps to
 1446    // two different URIs. For attributes on the same element
 1447    // this is illegal; but as yet we don't throw an exception
 1448    // if someone tries to do this
 1449  20077 for (int i = 0, size = element.attributeCount(); i < size; i++) {
 1450  4276 Attribute attribute = element.attribute(i);
 1451  4276 Namespace ns = attribute.getNamespace();
 1452   
 1453  4276 if ((ns != null) && (ns != Namespace.NO_NAMESPACE)
 1454    && (ns != Namespace.XML_NAMESPACE)) {
 1455  14 String prefix = ns.getPrefix();
 1456  14 String uri = namespaceStack.getURI(prefix);
 1457   
 1458  14 if (!ns.getURI().equals(uri)) {
 1459  0 writeNamespace(ns);
 1460  0 namespaceStack.push(ns);
 1461    }
 1462    }
 1463   
 1464    // If the attribute is a namespace declaration, check if we have
 1465    // already written that declaration elsewhere (if that's the case,
 1466    // it must be in the namespace stack
 1467  4276 String attName = attribute.getName();
 1468   
 1469  4276 if (attName.startsWith("xmlns:")) {
 1470  3 String prefix = attName.substring(6);
 1471   
 1472  3 if (namespaceStack.getNamespaceForPrefix(prefix) == null) {
 1473  2 String uri = attribute.getValue();
 1474  2 namespaceStack.push(prefix, uri);
 1475  2 writeNamespace(prefix, uri);
 1476    }
 1477  4273 } else if (attName.equals("xmlns")) {
 1478  1 if (namespaceStack.getDefaultNamespace() == null) {
 1479  0 String uri = attribute.getValue();
 1480  0 namespaceStack.push(null, uri);
 1481  0 writeNamespace(null, uri);
 1482    }
 1483    } else {
 1484  4272 char quote = format.getAttributeQuoteCharacter();
 1485  4272 writer.write(" ");
 1486  4272 writer.write(attribute.getQualifiedName());
 1487  4272 writer.write("=");
 1488  4272 writer.write(quote);
 1489  4272 writeEscapeAttributeEntities(attribute.getValue());
 1490  4272 writer.write(quote);
 1491    }
 1492    }
 1493    }
 1494   
 1495  0 protected void writeAttribute(Attribute attribute) throws IOException {
 1496  0 writer.write(" ");
 1497  0 writer.write(attribute.getQualifiedName());
 1498  0 writer.write("=");
 1499   
 1500  0 char quote = format.getAttributeQuoteCharacter();
 1501  0 writer.write(quote);
 1502   
 1503  0 writeEscapeAttributeEntities(attribute.getValue());
 1504   
 1505  0 writer.write(quote);
 1506  0 lastOutputNodeType = Node.ATTRIBUTE_NODE;
 1507    }
 1508   
 1509  8 protected void writeAttributes(Attributes attributes) throws IOException {
 1510  8 for (int i = 0, size = attributes.getLength(); i < size; i++) {
 1511  5 writeAttribute(attributes, i);
 1512    }
 1513    }
 1514   
 1515  5 protected void writeAttribute(Attributes attributes, int index)
 1516    throws IOException {
 1517  5 char quote = format.getAttributeQuoteCharacter();
 1518  5 writer.write(" ");
 1519  5 writer.write(attributes.getQName(index));
 1520  5 writer.write("=");
 1521  5 writer.write(quote);
 1522  5 writeEscapeAttributeEntities(attributes.getValue(index));
 1523  5 writer.write(quote);
 1524    }
 1525   
 1526  24916 protected void indent() throws IOException {
 1527  24916 String indent = format.getIndent();
 1528   
 1529  24916 if ((indent != null) && (indent.length() > 0)) {
 1530  151 for (int i = 0; i < indentLevel; i++) {
 1531  172 writer.write(indent);
 1532    }
 1533    }
 1534    }
 1535   
 1536    /**
 1537    * <p>
 1538    * This will print a new line only if the newlines flag was set to true
 1539    * </p>
 1540    *
 1541    * @throws IOException
 1542    * DOCUMENT ME!
 1543    */
 1544  25027 protected void writePrintln() throws IOException {
 1545  25027 if (format.isNewlines()) {
 1546  179 String seperator = format.getLineSeparator();
 1547  179 if (lastChar != seperator.charAt(seperator.length() - 1)) {
 1548  176 writer.write(format.getLineSeparator());
 1549    }
 1550    }
 1551    }
 1552   
 1553    /**
 1554    * Get an OutputStreamWriter, use preferred encoding.
 1555    *
 1556    * @param outStream
 1557    * DOCUMENT ME!
 1558    * @param encoding
 1559    * DOCUMENT ME!
 1560    *
 1561    * @return DOCUMENT ME!
 1562    *
 1563    * @throws UnsupportedEncodingException
 1564    * DOCUMENT ME!
 1565    */
 1566  25 protected Writer createWriter(OutputStream outStream, String encoding)
 1567    throws UnsupportedEncodingException {
 1568  25 return new BufferedWriter(new OutputStreamWriter(outStream, encoding));
 1569    }
 1570   
 1571    /**
 1572    * <p>
 1573    * This will write the declaration to the given Writer. Assumes XML version
 1574    * 1.0 since we don't directly know.
 1575    * </p>
 1576    *
 1577    * @throws IOException
 1578    * DOCUMENT ME!
 1579    */
 1580  114 protected void writeDeclaration() throws IOException {
 1581  114 String encoding = format.getEncoding();
 1582   
 1583    // Only print of declaration is not suppressed
 1584  114 if (!format.isSuppressDeclaration()) {
 1585    // Assume 1.0 version
 1586  110 if (encoding.equals("UTF8")) {
 1587  0 writer.write("<?xml version=\"1.0\"");
 1588   
 1589  0 if (!format.isOmitEncoding()) {
 1590  0 writer.write(" encoding=\"UTF-8\"");
 1591    }
 1592   
 1593  0 writer.write("?>");
 1594    } else {
 1595  110 writer.write("<?xml version=\"1.0\"");
 1596   
 1597  110 if (!format.isOmitEncoding()) {
 1598  110 writer.write(" encoding=\"" + encoding + "\"");
 1599    }
 1600   
 1601  110 writer.write("?>");
 1602    }
 1603   
 1604  110 if (format.isNewLineAfterDeclaration()) {
 1605  110 println();
 1606    }
 1607    }
 1608    }
 1609   
 1610  8 protected void writeClose(String qualifiedName) throws IOException {
 1611  8 writer.write("</");
 1612  8 writer.write(qualifiedName);
 1613  8 writer.write(">");
 1614    }
 1615   
 1616  299 protected void writeEmptyElementClose(String qualifiedName)
 1617    throws IOException {
 1618    // Simply close up
 1619  299 if (!format.isExpandEmptyElements()) {
 1620  295 writer.write("/>");
 1621    } else {
 1622  4 writer.write("></");
 1623  4 writer.write(qualifiedName);
 1624  4 writer.write(">");
 1625    }
 1626    }
 1627   
 1628  0 protected boolean isExpandEmptyElements() {
 1629  0 return format.isExpandEmptyElements();
 1630    }
 1631   
 1632    /**
 1633    * This will take the pre-defined entities in XML 1.0 and convert their
 1634    * character representation to the appropriate entity reference, suitable
 1635    * for XML attributes.
 1636    *
 1637    * @param text
 1638    * DOCUMENT ME!
 1639    *
 1640    * @return DOCUMENT ME!
 1641    */
 1642  37708 protected String escapeElementEntities(String text) {
 1643  37708 char[] block = null;
 1644  37708 int i;
 1645  37708 int last = 0;
 1646  37708 int size = text.length();
 1647   
 1648  37708 for (i = 0; i < size; i++) {
 1649  467325 String entity = null;
 1650  467325 char c = text.charAt(i);
 1651   
 1652  467325 switch (c) {
 1653  93 case '<':
 1654  93 entity = "&lt;";
 1655   
 1656  93 break;
 1657   
 1658  84 case '>':
 1659  84 entity = "&gt;";
 1660   
 1661  84 break;
 1662   
 1663  63 case '&':
 1664  63 entity = "&amp;";
 1665   
 1666  63 break;
 1667   
 1668  3455 case '\t':
 1669  27550 case '\n':
 1670  0 case '\r':
 1671   
 1672    // don't encode standard whitespace characters
 1673  31005 if (preserve) {
 1674  2 entity = String.valueOf(c);
 1675    }
 1676   
 1677  31005 break;
 1678   
 1679  436080 default:
 1680   
 1681  436080 if ((c < 32) || shouldEncodeChar(c)) {
 1682  1 entity = "&#" + (int) c + ";";
 1683    }
 1684   
 1685  436080 break;
 1686    }
 1687   
 1688  467325 if (entity != null) {
 1689  243 if (block == null) {
 1690  145 block = text.toCharArray();
 1691    }
 1692   
 1693  243 buffer.append(block, last, i - last);
 1694  243 buffer.append(entity);
 1695  243 last = i + 1;
 1696    }
 1697    }
 1698   
 1699  37708 if (last == 0) {
 1700  37563 return text;
 1701    }
 1702   
 1703  145 if (last < size) {
 1704  93 if (block == null) {
 1705  0 block = text.toCharArray();
 1706    }
 1707   
 1708  93 buffer.append(block, last, i - last);
 1709    }
 1710   
 1711  145 String answer = buffer.toString();
 1712  145 buffer.setLength(0);
 1713   
 1714  145 return answer;
 1715    }
 1716   
 1717  4277 protected void writeEscapeAttributeEntities(String txt) throws IOException {
 1718  4277 if (txt != null) {
 1719  4277 String escapedText = escapeAttributeEntities(txt);
 1720  4277 writer.write(escapedText);
 1721    }
 1722    }
 1723   
 1724    /**
 1725    * This will take the pre-defined entities in XML 1.0 and convert their
 1726    * character representation to the appropriate entity reference, suitable
 1727    * for XML attributes.
 1728    *
 1729    * @param text
 1730    * DOCUMENT ME!
 1731    *
 1732    * @return DOCUMENT ME!
 1733    */
 1734  4277 protected String escapeAttributeEntities(String text) {
 1735  4277 char quote = format.getAttributeQuoteCharacter();
 1736   
 1737  4277 char[] block = null;
 1738  4277 int i;
 1739  4277 int last = 0;
 1740  4277 int size = text.length();
 1741   
 1742  4277 for (i = 0; i < size; i++) {
 1743  48016 String entity = null;
 1744  48016 char c = text.charAt(i);
 1745   
 1746  48016 switch (c) {
 1747  0 case '<':
 1748  0 entity = "&lt;";
 1749   
 1750  0 break;
 1751   
 1752  0 case '>':
 1753  0 entity = "&gt;";
 1754   
 1755  0 break;
 1756   
 1757  1 case '\'':
 1758   
 1759  1 if (quote == '\'') {
 1760  0 entity = "&apos;";
 1761    }
 1762   
 1763  1 break;
 1764   
 1765  0 case '\"':
 1766   
 1767  0 if (quote == '\"') {
 1768  0 entity = "&quot;";
 1769    }
 1770   
 1771  0 break;
 1772   
 1773  0 case '&':
 1774  0 entity = "&amp;";
 1775   
 1776  0 break;
 1777   
 1778  0 case '\t':
 1779  0 case '\n':
 1780  0 case '\r':
 1781   
 1782    // don't encode standard whitespace characters
 1783  0 break;
 1784   
 1785  48015 default:
 1786   
 1787  48015 if ((c < 32) || shouldEncodeChar(c)) {
 1788  0 entity = "&#" + (int) c + ";";
 1789    }
 1790   
 1791  48015 break;
 1792    }
 1793   
 1794  48016 if (entity != null) {
 1795  0 if (block == null) {
 1796  0 block = text.toCharArray();
 1797    }
 1798   
 1799  0 buffer.append(block, last, i - last);
 1800  0 buffer.append(entity);
 1801  0 last = i + 1;
 1802    }
 1803    }
 1804   
 1805  4277 if (last == 0) {
 1806  4277 return text;
 1807    }
 1808   
 1809  0 if (last < size) {
 1810  0 if (block == null) {
 1811  0 block = text.toCharArray();
 1812    }
 1813   
 1814  0 buffer.append(block, last, i - last);
 1815    }
 1816   
 1817  0 String answer = buffer.toString();
 1818  0 buffer.setLength(0);
 1819   
 1820  0 return answer;
 1821    }
 1822   
 1823    /**
 1824    * Should the given character be escaped. This depends on the encoding of
 1825    * the document.
 1826    *
 1827    * @param c
 1828    * DOCUMENT ME!
 1829    *
 1830    * @return boolean
 1831    */
 1832  484095 protected boolean shouldEncodeChar(char c) {
 1833  484095 int max = getMaximumAllowedCharacter();
 1834   
 1835  484095 return (max > 0) && (c > max);
 1836    }
 1837   
 1838    /**
 1839    * Returns the maximum allowed character code that should be allowed
 1840    * unescaped which defaults to 127 in US-ASCII (7 bit) or 255 in ISO- (8
 1841    * bit).
 1842    *
 1843    * @return DOCUMENT ME!
 1844    */
 1845  2147 protected int defaultMaximumAllowedCharacter() {
 1846  2147 String encoding = format.getEncoding();
 1847   
 1848  2147 if (encoding != null) {
 1849  2147 if (encoding.equals("US-ASCII")) {
 1850  0 return 127;
 1851    }
 1852    }
 1853   
 1854    // no encoding for things like ISO-*, UTF-8 or UTF-16
 1855  2147 return -1;
 1856    }
 1857   
 1858  20275 protected boolean isNamespaceDeclaration(Namespace ns) {
 1859  20275 if ((ns != null) && (ns != Namespace.XML_NAMESPACE)) {
 1860  20275 String uri = ns.getURI();
 1861   
 1862  20275 if (uri != null) {
 1863  20275 if (!namespaceStack.contains(ns)) {
 1864  618 return true;
 1865    }
 1866    }
 1867    }
 1868   
 1869  19657 return false;
 1870    }
 1871   
 1872  0 protected void handleException(IOException e) throws SAXException {
 1873  0 throw new SAXException(e);
 1874    }
 1875   
 1876    // Laramie Crocker 4/8/2002 10:38AM
 1877   
 1878    /**
 1879    * Lets subclasses get at the current format object, so they can call
 1880    * setTrimText, setNewLines, etc. Put in to support the HTMLWriter, in the
 1881    * way that it pushes the current newline/trim state onto a stack and
 1882    * overrides the state within preformatted tags.
 1883    *
 1884    * @return DOCUMENT ME!
 1885    */
 1886  7 protected OutputFormat getOutputFormat() {
 1887  7 return format;
 1888    }
 1889   
 1890  0 public boolean resolveEntityRefs() {
 1891  0 return resolveEntityRefs;
 1892    }
 1893   
 1894  0 public void setResolveEntityRefs(boolean resolve) {
 1895  0 this.resolveEntityRefs = resolve;
 1896    }
 1897    }
 1898   
 1899    /*
 1900    * Redistribution and use of this software and associated documentation
 1901    * ("Software"), with or without modification, are permitted provided that the
 1902    * following conditions are met:
 1903    *
 1904    * 1. Redistributions of source code must retain copyright statements and
 1905    * notices. Redistributions must also contain a copy of this document.
 1906    *
 1907    * 2. Redistributions in binary form must reproduce the above copyright notice,
 1908    * this list of conditions and the following disclaimer in the documentation
 1909    * and/or other materials provided with the distribution.
 1910    *
 1911    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 1912    * from this Software without prior written permission of MetaStuff, Ltd. For
 1913    * written permission, please contact dom4j-info@metastuff.com.
 1914    *
 1915    * 4. Products derived from this Software may not be called "DOM4J" nor may
 1916    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 1917    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 1918    *
 1919    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 1920    *
 1921    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 1922    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 1923    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 1924    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 1925    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 1926    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 1927    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 1928    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 1929    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 1930    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 1931    * POSSIBILITY OF SUCH DAMAGE.
 1932    *
 1933    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 1934    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/DocumentResult.html0000644000175000017500000007163710242117656022406 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 100   Methods: 5
NCLOC: 31   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DocumentResult.java 0% 45,5% 60% 40%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import javax.xml.transform.sax.SAXResult;
 11   
 12    import org.dom4j.Document;
 13   
 14    import org.xml.sax.ContentHandler;
 15    import org.xml.sax.ext.LexicalHandler;
 16   
 17    /**
 18    * <p>
 19    * <code>DocumentResult</code> implements a JAXP {@link SAXResult}for a
 20    * {@link Document}.
 21    * </p>
 22    *
 23    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 24    * @version $Revision: 1.8 $
 25    */
 26    public class DocumentResult extends SAXResult {
 27    private SAXContentHandler contentHandler;
 28   
 29  6 public DocumentResult() {
 30  6 this(new SAXContentHandler());
 31    }
 32   
 33  6 public DocumentResult(SAXContentHandler contentHandler) {
 34  6 this.contentHandler = contentHandler;
 35  6 super.setHandler(this.contentHandler);
 36  6 super.setLexicalHandler(this.contentHandler);
 37    }
 38   
 39    /**
 40    * DOCUMENT ME!
 41    *
 42    * @return the Document created by the transformation
 43    */
 44  6 public Document getDocument() {
 45  6 return contentHandler.getDocument();
 46    }
 47   
 48    // Overloaded methods
 49    // -------------------------------------------------------------------------
 50  0 public void setHandler(ContentHandler handler) {
 51  0 if (handler instanceof SAXContentHandler) {
 52  0 this.contentHandler = (SAXContentHandler) handler;
 53  0 super.setHandler(this.contentHandler);
 54    }
 55    }
 56   
 57  0 public void setLexicalHandler(LexicalHandler handler) {
 58  0 if (handler instanceof SAXContentHandler) {
 59  0 this.contentHandler = (SAXContentHandler) handler;
 60  0 super.setLexicalHandler(this.contentHandler);
 61    }
 62    }
 63    }
 64   
 65    /*
 66    * Redistribution and use of this software and associated documentation
 67    * ("Software"), with or without modification, are permitted provided that the
 68    * following conditions are met:
 69    *
 70    * 1. Redistributions of source code must retain copyright statements and
 71    * notices. Redistributions must also contain a copy of this document.
 72    *
 73    * 2. Redistributions in binary form must reproduce the above copyright notice,
 74    * this list of conditions and the following disclaimer in the documentation
 75    * and/or other materials provided with the distribution.
 76    *
 77    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 78    * from this Software without prior written permission of MetaStuff, Ltd. For
 79    * written permission, please contact dom4j-info@metastuff.com.
 80    *
 81    * 4. Products derived from this Software may not be called "DOM4J" nor may
 82    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 83    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 84    *
 85    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 86    *
 87    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 88    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 89    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 90    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 91    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 92    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 93    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 94    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 95    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 96    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 97    * POSSIBILITY OF SUCH DAMAGE.
 98    *
 99    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 100    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/OutputFormat.html0000644000175000017500000046677610242117611022105 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 591   Methods: 35
NCLOC: 178   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
OutputFormat.java 17,6% 55% 77,1% 51,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    /**
 11    * <p>
 12    * <code>OutputFormat</code> represents the format configuration used by
 13    * {@linkXMLWriter}and its base classes to format the XML output
 14    * </p>
 15    *
 16    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 17    * @version $Revision: 1.17 $
 18    */
 19    public class OutputFormat implements Cloneable {
 20    /** standard value to indent by, if we are indenting */
 21    protected static final String STANDARD_INDENT = " ";
 22   
 23    /**
 24    * Whether or not to suppress the XML declaration - default is
 25    * <code>false</code>
 26    */
 27    private boolean suppressDeclaration = false;
 28   
 29    /**
 30    * Whether or not to print new line after the XML declaration - default is
 31    * <code>true</code>
 32    */
 33    private boolean newLineAfterDeclaration = true;
 34   
 35    /** The encoding format */
 36    private String encoding = "UTF-8";
 37   
 38    /**
 39    * Whether or not to output the encoding in the XML declaration - default is
 40    * <code>false</code>
 41    */
 42    private boolean omitEncoding = false;
 43   
 44    /** The default indent is no spaces (as original document) */
 45    private String indent = null;
 46   
 47    /**
 48    * Whether or not to expand empty elements to
 49    * &lt;tagName&gt;&lt;/tagName&gt; - default is <code>false</code>
 50    */
 51    private boolean expandEmptyElements = false;
 52   
 53    /**
 54    * The default new line flag, set to do new lines only as in original
 55    * document
 56    */
 57    private boolean newlines = false;
 58   
 59    /** New line separator */
 60    private String lineSeparator = "\n";
 61   
 62    /** should we preserve whitespace or not in text nodes? */
 63    private boolean trimText = false;
 64   
 65    /** pad string-element boundaries with whitespace */
 66    private boolean padText = false;
 67   
 68    /** Whether or not to use XHTML standard. */
 69    private boolean doXHTML = false;
 70   
 71    /**
 72    * Controls when to output a line.separtor every so many tags in case of no
 73    * lines and total text trimming.
 74    */
 75    private int newLineAfterNTags = 0; // zero means don't bother.
 76   
 77    /** Quote character to use when writing attributes. */
 78    private char attributeQuoteChar = '\"';
 79   
 80    /**
 81    * Creates an <code>OutputFormat</code> with no additional whitespace
 82    * (indent or new lines) added. The whitespace from the element text content
 83    * is fully preserved.
 84    */
 85  2159 public OutputFormat() {
 86    }
 87   
 88    /**
 89    * Creates an <code>OutputFormat</code> with the given indent added but no
 90    * new lines added. All whitespace from element text will be included.
 91    *
 92    * @param indent
 93    * is the indent string to be used for indentation (usually a
 94    * number of spaces).
 95    */
 96  0 public OutputFormat(String indent) {
 97  0 this.indent = indent;
 98    }
 99   
 100    /**
 101    * Creates an <code>OutputFormat</code> with the given indent added with
 102    * optional newlines between the Elements. All whitespace from element text
 103    * will be included.
 104    *
 105    * @param indent
 106    * is the indent string to be used for indentation (usually a
 107    * number of spaces).
 108    * @param newlines
 109    * whether new lines are added to layout the
 110    */
 111  4 public OutputFormat(String indent, boolean newlines) {
 112  4 this.indent = indent;
 113  4 this.newlines = newlines;
 114    }
 115   
 116    /**
 117    * Creates an <code>OutputFormat</code> with the given indent added with
 118    * optional newlines between the Elements and the given encoding format.
 119    *
 120    * @param indent
 121    * is the indent string to be used for indentation (usually a
 122    * number of spaces).
 123    * @param newlines
 124    * whether new lines are added to layout the
 125    * @param encoding
 126    * is the text encoding to use for writing the XML
 127    */
 128  4 public OutputFormat(String indent, boolean newlines, String encoding) {
 129  4 this.indent = indent;
 130  4 this.newlines = newlines;
 131  4 this.encoding = encoding;
 132    }
 133   
 134  468 public String getLineSeparator() {
 135  468 return lineSeparator;
 136    }
 137   
 138    /**
 139    * <p>
 140    * This will set the new-line separator. The default is <code>\n</code>.
 141    * Note that if the "newlines" property is false, this value is irrelevant.
 142    * To make it output the system default line ending string, call
 143    * <code>setLineSeparator(System.getProperty("line.separator"))</code>
 144    * </p>
 145    *
 146    * @param separator
 147    * <code>String</code> line separator to use.
 148    *
 149    * @see #setNewlines(boolean)
 150    */
 151  0 public void setLineSeparator(String separator) {
 152  0 lineSeparator = separator;
 153    }
 154   
 155  25477 public boolean isNewlines() {
 156  25477 return newlines;
 157    }
 158   
 159    /**
 160    * DOCUMENT ME!
 161    *
 162    * @param newlines
 163    * <code>true</code> indicates new lines should be printed,
 164    * else new lines are ignored (compacted).
 165    *
 166    * @see #setLineSeparator(String)
 167    */
 168  38 public void setNewlines(boolean newlines) {
 169  38 this.newlines = newlines;
 170    }
 171   
 172  2286 public String getEncoding() {
 173  2286 return encoding;
 174    }
 175   
 176    /**
 177    * DOCUMENT ME!
 178    *
 179    * @param encoding
 180    * encoding format
 181    */
 182  74 public void setEncoding(String encoding) {
 183  74 if (encoding != null) {
 184  54 this.encoding = encoding;
 185    }
 186    }
 187   
 188  110 public boolean isOmitEncoding() {
 189  110 return omitEncoding;
 190    }
 191   
 192    /**
 193    * <p>
 194    * This will set whether the XML declaration (<code>&lt;?xml version="1.0"
 195    * encoding="UTF-8"?&gt;</code>)
 196    * includes the encoding of the document. It is common to suppress this in
 197    * protocols such as WML and SOAP.
 198    * </p>
 199    *
 200    * @param omitEncoding
 201    * <code>boolean</code> indicating whether or not the XML
 202    * declaration should indicate the document encoding.
 203    */
 204  7 public void setOmitEncoding(boolean omitEncoding) {
 205  7 this.omitEncoding = omitEncoding;
 206    }
 207   
 208    /**
 209    * <p>
 210    * This will set whether the XML declaration (<code>&lt;?xml version="1.0"
 211    * encoding="UTF-8"?&gt;</code>)
 212    * is included or not. It is common to suppress this in protocols such as
 213    * WML and SOAP.
 214    * </p>
 215    *
 216    * @param suppressDeclaration
 217    * <code>boolean</code> indicating whether or not the XML
 218    * declaration should be suppressed.
 219    */
 220  10 public void setSuppressDeclaration(boolean suppressDeclaration) {
 221  10 this.suppressDeclaration = suppressDeclaration;
 222    }
 223   
 224    /**
 225    * DOCUMENT ME!
 226    *
 227    * @return true if the output of the XML declaration (<code>&lt;?xml
 228    * version="1.0"?&gt;</code>)
 229    * should be suppressed else false.
 230    */
 231  114 public boolean isSuppressDeclaration() {
 232  114 return suppressDeclaration;
 233    }
 234   
 235    /**
 236    * <p>
 237    * This will set whether a new line is printed after the XML declaration
 238    * (assuming it is not supressed.)
 239    * </p>
 240    *
 241    * @param newLineAfterDeclaration
 242    * <code>boolean</code> indicating whether or not to print new
 243    * line following the XML declaration. The default is true.
 244    */
 245  0 public void setNewLineAfterDeclaration(boolean newLineAfterDeclaration) {
 246  0 this.newLineAfterDeclaration = newLineAfterDeclaration;
 247    }
 248   
 249    /**
 250    * DOCUMENT ME!
 251    *
 252    * @return true if a new line should be printed following XML declaration
 253    */
 254  110 public boolean isNewLineAfterDeclaration() {
 255  110 return newLineAfterDeclaration;
 256    }
 257   
 258  299 public boolean isExpandEmptyElements() {
 259  299 return expandEmptyElements;
 260    }
 261   
 262    /**
 263    * <p>
 264    * This will set whether empty elements are expanded from
 265    * <code>&lt;tagName&gt;</code> to
 266    * <code>&lt;tagName&gt;&lt;/tagName&gt;</code>.
 267    * </p>
 268    *
 269    * @param expandEmptyElements
 270    * <code>boolean</code> indicating whether or not empty
 271    * elements should be expanded.
 272    */
 273  11 public void setExpandEmptyElements(boolean expandEmptyElements) {
 274  11 this.expandEmptyElements = expandEmptyElements;
 275    }
 276   
 277  19843 public boolean isTrimText() {
 278  19843 return trimText;
 279    }
 280   
 281    /**
 282    * <p>
 283    * This will set whether the text is output verbatim (false) or with
 284    * whitespace stripped as per <code>{@link
 285    * org.dom4j.Element#getTextTrim()}</code>.
 286    * </p>
 287    *
 288    * <p>
 289    * </p>
 290    *
 291    * <p>
 292    * Default: false
 293    * </p>
 294    *
 295    * @param trimText
 296    * <code>boolean</code> true=>trim the whitespace, false=>use
 297    * text verbatim
 298    */
 299  40 public void setTrimText(boolean trimText) {
 300  40 this.trimText = trimText;
 301    }
 302   
 303  16696 public boolean isPadText() {
 304  16696 return padText;
 305    }
 306   
 307    /**
 308    * <p>
 309    * Ensure that text immediately preceded by or followed by an element will
 310    * be "padded" with a single space. This is used to allow make
 311    * browser-friendly HTML, avoiding trimText's transformation of, e.g.,
 312    * <code>The quick &lt;b&gt;brown&lt;/b&gt; fox</code> into <code>The
 313    * quick&lt;b&gt;brown&lt;/b&gt;fox</code>
 314    * (the latter will run the three separate words together into a single
 315    * word). This setting is not too useful if you haven't also called
 316    * {@link #setTrimText}.
 317    * </p>
 318    *
 319    * <p>
 320    * The padding string will only be added if the text itself starts or ends
 321    * with some whitespace characters.
 322    * </p>
 323    *
 324    * <p>
 325    * Default: false
 326    * </p>
 327    *
 328    * @param padText
 329    * <code>boolean</code> if true, pad string-element boundaries
 330    */
 331  20 public void setPadText(boolean padText) {
 332  20 this.padText = padText;
 333    }
 334   
 335  24916 public String getIndent() {
 336  24916 return indent;
 337    }
 338   
 339    /**
 340    * <p>
 341    * This will set the indent <code>String</code> to use; this is usually a
 342    * <code>String</code> of empty spaces. If you pass null, or the empty
 343    * string (""), then no indentation will happen.
 344    * </p>
 345    * Default: none (null)
 346    *
 347    * @param indent
 348    * <code>String</code> to use for indentation.
 349    */
 350  0 public void setIndent(String indent) {
 351    // nullify empty string to void unnecessary indentation code
 352  0 if ((indent != null) && (indent.length() <= 0)) {
 353  0 indent = null;
 354    }
 355   
 356  0 this.indent = indent;
 357    }
 358   
 359    /**
 360    * Set the indent on or off. If setting on, will use the value of
 361    * STANDARD_INDENT, which is usually two spaces.
 362    *
 363    * @param doIndent
 364    * if true, set indenting on; if false, set indenting off
 365    */
 366  15 public void setIndent(boolean doIndent) {
 367  15 if (doIndent) {
 368  5 this.indent = STANDARD_INDENT;
 369    } else {
 370  10 this.indent = null;
 371    }
 372    }
 373   
 374    /**
 375    * <p>
 376    * This will set the indent <code>String</code>'s size; an indentSize of
 377    * 4 would result in the indention being equivalent to the
 378    * <code>String</code> "&nbsp;&nbsp;&nbsp;&nbsp;" (four space characters).
 379    * </p>
 380    *
 381    * @param indentSize
 382    * <code>int</code> number of spaces in indentation.
 383    */
 384  22 public void setIndentSize(int indentSize) {
 385  22 StringBuffer indentBuffer = new StringBuffer();
 386   
 387  22 for (int i = 0; i < indentSize; i++) {
 388  52 indentBuffer.append(" ");
 389    }
 390   
 391  22 this.indent = indentBuffer.toString();
 392    }
 393   
 394    /**
 395    * <p>
 396    * Whether or not to use the XHTML standard: like HTML but passes an XML
 397    * parser with real, closed tags. Also, XHTML CDATA sections will be output
 398    * with the CDATA delimiters: ( &quot; <b>&lt;![CDATA[ </b>&quot; and &quot;
 399    * <b>]]&gt; </b>&quot; ) otherwise, the class HTMLWriter will output the
 400    * CDATA text, but not the delimiters.
 401    * </p>
 402    *
 403    * <p>
 404    * Default is <code>false</code>
 405    * </p>
 406    *
 407    * @return DOCUMENT ME!
 408    */
 409  3 public boolean isXHTML() {
 410  3 return doXHTML;
 411    }
 412   
 413    /**
 414    * <p>
 415    * This will set whether or not to use the XHTML standard: like HTML but
 416    * passes an XML parser with real, closed tags. Also, XHTML CDATA sections
 417    * will be output with the CDATA delimiters: ( &quot; <b>&lt;[CDATA[
 418    * </b>&quot; and &quot; <b>]]&lt; </b>) otherwise, the class HTMLWriter
 419    * will output the CDATA text, but not the delimiters.
 420    * </p>
 421    *
 422    * <p>
 423    * Default: false
 424    * </p>
 425    *
 426    * @param xhtml
 427    * <code>boolean</code> true=>conform to XHTML, false=>conform
 428    * to HTML, can have unclosed tags, etc.
 429    */
 430  0 public void setXHTML(boolean xhtml) {
 431  0 doXHTML = xhtml;
 432    }
 433   
 434  1 public int getNewLineAfterNTags() {
 435  1 return newLineAfterNTags;
 436    }
 437   
 438    /**
 439    * Controls output of a line.separator every tagCount tags when isNewlines
 440    * is false. If tagCount equals zero, it means don't do anything special. If
 441    * greater than zero, then a line.separator will be output after tagCount
 442    * tags have been output. Used when you would like to squeeze the html as
 443    * much as possible, but some browsers don't like really long lines. A tag
 444    * count of 10 would produce a line.separator in the output after 10 close
 445    * tags (including single tags).
 446    *
 447    * @param tagCount
 448    * DOCUMENT ME!
 449    */
 450  0 public void setNewLineAfterNTags(int tagCount) {
 451  0 newLineAfterNTags = tagCount;
 452    }
 453   
 454  8554 public char getAttributeQuoteCharacter() {
 455  8554 return attributeQuoteChar;
 456    }
 457   
 458    /**
 459    * Sets the character used to quote attribute values. The specified
 460    * character must be a valid XML attribute quote character, otherwise an
 461    * <code>IllegalArgumentException</code> will be thrown.
 462    *
 463    * @param quoteChar
 464    * The character to use when quoting attribute values.
 465    *
 466    * @throws IllegalArgumentException
 467    * If the specified character is not a valid XML attribute quote
 468    * character.
 469    */
 470  0 public void setAttributeQuoteCharacter(char quoteChar) {
 471  0 if ((quoteChar == '\'') || (quoteChar == '"')) {
 472  0 attributeQuoteChar = quoteChar;
 473    } else {
 474  0 throw new IllegalArgumentException("Invalid attribute quote "
 475    + "character (" + quoteChar + ")");
 476    }
 477    }
 478   
 479    /**
 480    * Parses command line arguments of the form <code>-omitEncoding
 481    * -indentSize 3 -newlines -trimText</code>
 482    *
 483    * @param args
 484    * is the array of command line arguments
 485    * @param i
 486    * is the index in args to start parsing options
 487    *
 488    * @return the index of first parameter that we didn't understand
 489    */
 490  0 public int parseOptions(String[] args, int i) {
 491  0 for (int size = args.length; i < size; i++) {
 492  0 if (args[i].equals("-suppressDeclaration")) {
 493  0 setSuppressDeclaration(true);
 494  0 } else if (args[i].equals("-omitEncoding")) {
 495  0 setOmitEncoding(true);
 496  0 } else if (args[i].equals("-indent")) {
 497  0 setIndent(args[++i]);
 498  0 } else if (args[i].equals("-indentSize")) {
 499  0 setIndentSize(Integer.parseInt(args[++i]));
 500  0 } else if (args[i].startsWith("-expandEmpty")) {
 501  0 setExpandEmptyElements(true);
 502  0 } else if (args[i].equals("-encoding")) {
 503  0 setEncoding(args[++i]);
 504  0 } else if (args[i].equals("-newlines")) {
 505  0 setNewlines(true);
 506  0 } else if (args[i].equals("-lineSeparator")) {
 507  0 setLineSeparator(args[++i]);
 508  0 } else if (args[i].equals("-trimText")) {
 509  0 setTrimText(true);
 510  0 } else if (args[i].equals("-padText")) {
 511  0 setPadText(true);
 512  0 } else if (args[i].startsWith("-xhtml")) {
 513  0 setXHTML(true);
 514    } else {
 515  0 return i;
 516    }
 517    }
 518   
 519  0 return i;
 520    }
 521   
 522    /**
 523    * A static helper method to create the default pretty printing format. This
 524    * format consists of an indent of 2 spaces, newlines after each element and
 525    * all other whitespace trimmed, and XMTML is false.
 526    *
 527    * @return DOCUMENT ME!
 528    */
 529  18 public static OutputFormat createPrettyPrint() {
 530  18 OutputFormat format = new OutputFormat();
 531  18 format.setIndentSize(2);
 532  18 format.setNewlines(true);
 533  18 format.setTrimText(true);
 534  18 format.setPadText(true);
 535   
 536  18 return format;
 537    }
 538   
 539    /**
 540    * A static helper method to create the default compact format. This format
 541    * does not have any indentation or newlines after an alement and all other
 542    * whitespace trimmed
 543    *
 544    * @return DOCUMENT ME!
 545    */
 546  10 public static OutputFormat createCompactFormat() {
 547  10 OutputFormat format = new OutputFormat();
 548  10 format.setIndent(false);
 549  10 format.setNewlines(false);
 550  10 format.setTrimText(true);
 551   
 552  10 return format;
 553    }
 554    }
 555   
 556    /*
 557    * Redistribution and use of this software and associated documentation
 558    * ("Software"), with or without modification, are permitted provided that the
 559    * following conditions are met:
 560    *
 561    * 1. Redistributions of source code must retain copyright statements and
 562    * notices. Redistributions must also contain a copy of this document.
 563    *
 564    * 2. Redistributions in binary form must reproduce the above copyright notice,
 565    * this list of conditions and the following disclaimer in the documentation
 566    * and/or other materials provided with the distribution.
 567    *
 568    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 569    * from this Software without prior written permission of MetaStuff, Ltd. For
 570    * written permission, please contact dom4j-info@metastuff.com.
 571    *
 572    * 4. Products derived from this Software may not be called "DOM4J" nor may
 573    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 574    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 575    *
 576    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 577    *
 578    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 579    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 580    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 581    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 582    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 583    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 584    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 585    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 586    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 587    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 588    * POSSIBILITY OF SUCH DAMAGE.
 589    *
 590    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 591    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/ElementModifier.html0000644000175000017500000005430310242117730022461 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 77   Methods: 0
NCLOC: 5   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
ElementModifier.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import org.dom4j.Element;
 11   
 12    /**
 13    * ElementModifier defines a modifier of {@link org.dom4j.Element}objects. <br>
 14    * It can be used in the event based {@link org.dom4j.io.SAXModifier}, in order
 15    * to modify elements on the fly, rather than waiting until the complete
 16    * document is parsed.
 17    *
 18    * @author Wonne Keysers (Realsoftware.be)
 19    */
 20    public interface ElementModifier {
 21    /**
 22    * Called by an event based processor when an elements closing tag is
 23    * encountered. This method must return the modified version of the provided
 24    * {@link org.dom4j.Element}or null if it has to be removed from the
 25    * document. <br>
 26    * The incoming {@link org.dom4j.Element}is disconnected from the DOM4J
 27    * tree. This means that navigation to the elements parent {@link
 28    * org.dom4j.Element} and {@link org.dom4j.Document}are not available. Only
 29    * the element itself can be modified!
 30    *
 31    * @param element
 32    * {@link org.dom4j.Element}to be parsed
 33    *
 34    * @return the modified {@link org.dom4j.Element}
 35    *
 36    * @throws Exception
 37    * of any kind
 38    */
 39    Element modifyElement(Element element) throws Exception;
 40    }
 41   
 42    /*
 43    * Redistribution and use of this software and associated documentation
 44    * ("Software"), with or without modification, are permitted provided that the
 45    * following conditions are met:
 46    *
 47    * 1. Redistributions of source code must retain copyright statements and
 48    * notices. Redistributions must also contain a copy of this document.
 49    *
 50    * 2. Redistributions in binary form must reproduce the above copyright notice,
 51    * this list of conditions and the following disclaimer in the documentation
 52    * and/or other materials provided with the distribution.
 53    *
 54    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 55    * from this Software without prior written permission of MetaStuff, Ltd. For
 56    * written permission, please contact dom4j-info@metastuff.com.
 57    *
 58    * 4. Products derived from this Software may not be called "DOM4J" nor may
 59    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 60    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 61    *
 62    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 63    *
 64    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 65    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 66    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 67    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 68    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 69    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 70    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 71    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 72    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 73    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 74    * POSSIBILITY OF SUCH DAMAGE.
 75    *
 76    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 77    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/SAXValidator.html0000644000175000017500000015374110242117747021730 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 203   Methods: 9
NCLOC: 61   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
SAXValidator.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.io.IOException;
 11   
 12    import org.dom4j.Document;
 13   
 14    import org.xml.sax.ContentHandler;
 15    import org.xml.sax.ErrorHandler;
 16    import org.xml.sax.SAXException;
 17    import org.xml.sax.XMLReader;
 18    import org.xml.sax.helpers.DefaultHandler;
 19   
 20    /**
 21    * <p>
 22    * <code>SAXValidator</code> validates an XML document by writing the document
 23    * to a text buffer and parsing it with a validating SAX parser. This could be
 24    * implemented much more efficiently by validating against the dom4j object
 25    * model directly but at least allows the reuse of existing SAX based validating
 26    * parsers.
 27    * </p>
 28    *
 29    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 30    * @version $Revision: 1.10 $
 31    */
 32    public class SAXValidator {
 33    /** <code>XMLReader</code> used to parse the SAX events */
 34    private XMLReader xmlReader;
 35   
 36    /** ErrorHandler class to use */
 37    private ErrorHandler errorHandler;
 38   
 39  0 public SAXValidator() {
 40    }
 41   
 42  0 public SAXValidator(XMLReader xmlReader) {
 43  0 this.xmlReader = xmlReader;
 44    }
 45   
 46    /**
 47    * Validates the given <code>Document</code> by writing it to a validating
 48    * SAX Parser.
 49    *
 50    * @param document
 51    * is the Document to validate
 52    *
 53    * @throws SAXException
 54    * if a validation error occurs
 55    * @throws RuntimeException
 56    * DOCUMENT ME!
 57    */
 58  0 public void validate(Document document) throws SAXException {
 59  0 if (document != null) {
 60  0 XMLReader reader = getXMLReader();
 61   
 62  0 if (errorHandler != null) {
 63  0 reader.setErrorHandler(errorHandler);
 64    }
 65   
 66  0 try {
 67  0 reader.parse(new DocumentInputSource(document));
 68    } catch (IOException e) {
 69  0 throw new RuntimeException("Caught and exception that should "
 70    + "never happen: " + e);
 71    }
 72    }
 73    }
 74   
 75    // Properties
 76    // -------------------------------------------------------------------------
 77   
 78    /**
 79    * DOCUMENT ME!
 80    *
 81    * @return the <code>XMLReader</code> used to parse SAX events
 82    *
 83    * @throws SAXException
 84    * DOCUMENT ME!
 85    */
 86  0 public XMLReader getXMLReader() throws SAXException {
 87  0 if (xmlReader == null) {
 88  0 xmlReader = createXMLReader();
 89  0 configureReader();
 90    }
 91   
 92  0 return xmlReader;
 93    }
 94   
 95    /**
 96    * Sets the <code>XMLReader</code> used to parse SAX events
 97    *
 98    * @param reader
 99    * is the <code>XMLReader</code> to parse SAX events
 100    *
 101    * @throws SAXException
 102    * DOCUMENT ME!
 103    */
 104  0 public void setXMLReader(XMLReader reader) throws SAXException {
 105  0 this.xmlReader = reader;
 106  0 configureReader();
 107    }
 108   
 109    /**
 110    * DOCUMENT ME!
 111    *
 112    * @return the <code>ErrorHandler</code> used by SAX
 113    */
 114  0 public ErrorHandler getErrorHandler() {
 115  0 return errorHandler;
 116    }
 117   
 118    /**
 119    * Sets the <code>ErrorHandler</code> used by the SAX
 120    * <code>XMLReader</code>.
 121    *
 122    * @param errorHandler
 123    * is the <code>ErrorHandler</code> used by SAX
 124    */
 125  0 public void setErrorHandler(ErrorHandler errorHandler) {
 126  0 this.errorHandler = errorHandler;
 127    }
 128   
 129    // Implementation methods
 130    // -------------------------------------------------------------------------
 131   
 132    /**
 133    * Factory Method to allow alternate methods of creating and configuring
 134    * XMLReader objects
 135    *
 136    * @return DOCUMENT ME!
 137    *
 138    * @throws SAXException
 139    * DOCUMENT ME!
 140    */
 141  0 protected XMLReader createXMLReader() throws SAXException {
 142  0 return SAXHelper.createXMLReader(true);
 143    }
 144   
 145    /**
 146    * Configures the XMLReader before use
 147    *
 148    * @throws SAXException
 149    * DOCUMENT ME!
 150    */
 151  0 protected void configureReader() throws SAXException {
 152  0 ContentHandler handler = xmlReader.getContentHandler();
 153   
 154  0 if (handler == null) {
 155  0 xmlReader.setContentHandler(new DefaultHandler());
 156    }
 157   
 158    // configure validation support
 159  0 xmlReader.setFeature("http://xml.org/sax/features/validation", true);
 160   
 161    // configure namespace support
 162  0 xmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
 163  0 xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes",
 164    false);
 165    }
 166    }
 167   
 168    /*
 169    * Redistribution and use of this software and associated documentation
 170    * ("Software"), with or without modification, are permitted provided that the
 171    * following conditions are met:
 172    *
 173    * 1. Redistributions of source code must retain copyright statements and
 174    * notices. Redistributions must also contain a copy of this document.
 175    *
 176    * 2. Redistributions in binary form must reproduce the above copyright notice,
 177    * this list of conditions and the following disclaimer in the documentation
 178    * and/or other materials provided with the distribution.
 179    *
 180    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 181    * from this Software without prior written permission of MetaStuff, Ltd. For
 182    * written permission, please contact dom4j-info@metastuff.com.
 183    *
 184    * 4. Products derived from this Software may not be called "DOM4J" nor may
 185    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 186    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 187    *
 188    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 189    *
 190    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 191    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 192    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 193    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 194    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 195    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 196    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 197    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 198    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 199    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 200    * POSSIBILITY OF SUCH DAMAGE.
 201    *
 202    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 203    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/SAXModifier.html0000644000175000017500000036002610242117720021524 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 459   Methods: 23
NCLOC: 157   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
SAXModifier.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.io.File;
 11    import java.io.InputStream;
 12    import java.io.Reader;
 13    import java.net.URL;
 14    import java.util.HashMap;
 15    import java.util.Iterator;
 16    import java.util.Map;
 17   
 18    import org.dom4j.Document;
 19    import org.dom4j.DocumentException;
 20    import org.dom4j.DocumentFactory;
 21   
 22    import org.xml.sax.InputSource;
 23    import org.xml.sax.SAXException;
 24    import org.xml.sax.XMLReader;
 25   
 26    /**
 27    * The SAXModifier reads, modifies and writes XML documents using SAX.
 28    *
 29    * <p>
 30    * Registered {@link ElementModifier}objects can provide modifications to (part
 31    * of) the xml tree, while the document is still being processed. This makes it
 32    * possible to change large xml documents without having them in memory.
 33    * </p>
 34    *
 35    * <p>
 36    * The modified document is written when the {@link XMLWriter}is specified.
 37    * </p>
 38    *
 39    * @author Wonne Keysers (Realsoftware.be)
 40    *
 41    * @see org.dom4j.io.SAXReader
 42    * @see org.dom4j.io.XMLWriter
 43    */
 44    public class SAXModifier {
 45    private XMLWriter xmlWriter;
 46   
 47    private XMLReader xmlReader;
 48   
 49    private boolean pruneElements;
 50   
 51    private SAXModifyReader modifyReader;
 52   
 53    private HashMap modifiers = new HashMap();
 54   
 55    /**
 56    * Creates a new modifier. <br>
 57    * The XMLReader to parse the source will be created via the
 58    * org.xml.sax.driver system property or JAXP if the system property is not
 59    * set.
 60    */
 61  0 public SAXModifier() {
 62    }
 63   
 64    /**
 65    * Creates a new modifier. <br>
 66    * The XMLReader to parse the source will be created via the
 67    * org.xml.sax.driver system property or JAXP if the system property is not
 68    * set.
 69    *
 70    * @param pruneElements
 71    * Set to true when the modified document must NOT be kept in
 72    * memory.
 73    */
 74  0 public SAXModifier(boolean pruneElements) {
 75  0 this.pruneElements = pruneElements;
 76    }
 77   
 78    /**
 79    * Creates a new modifier that will the specified {@link
 80    * org.xml.sax.XMLReader} to parse the source.
 81    *
 82    * @param xmlReader
 83    * The XMLReader to use
 84    */
 85  0 public SAXModifier(XMLReader xmlReader) {
 86  0 this.xmlReader = xmlReader;
 87    }
 88   
 89    /**
 90    * Creates a new modifier that will the specified {@link
 91    * org.xml.sax.XMLReader} to parse the source.
 92    *
 93    * @param xmlReader
 94    * The XMLReader to use
 95    * @param pruneElements
 96    * Set to true when the modified document must NOT be kept in
 97    * memory.
 98    */
 99  0 public SAXModifier(XMLReader xmlReader, boolean pruneElements) {
 100  0 this.xmlReader = xmlReader;
 101    }
 102   
 103    /**
 104    * Reads a Document from the given {@link java.io.File}and writes it to the
 105    * specified {@link XMLWriter}using SAX. Registered {@linkElementModifier}
 106    * objects are invoked on the fly.
 107    *
 108    * @param source
 109    * is the <code>File</code> to read from.
 110    *
 111    * @return the newly created Document instance
 112    *
 113    * @throws DocumentException
 114    * DocumentException org.dom4j.DocumentException} if an error
 115    * occurs during parsing.
 116    */
 117  0 public Document modify(File source) throws DocumentException {
 118  0 try {
 119  0 return installModifyReader().read(source);
 120    } catch (SAXModifyException ex) {
 121  0 Throwable cause = ex.getCause();
 122  0 throw new DocumentException(cause.getMessage(), cause);
 123    }
 124    }
 125   
 126    /**
 127    * Reads a Document from the given {@link org.xml.sax.InputSource}and
 128    * writes it to the specified {@link XMLWriter}using SAX. Registered
 129    * {@link ElementModifier}objects are invoked on the fly.
 130    *
 131    * @param source
 132    * is the <code>org.xml.sax.InputSource</code> to read from.
 133    *
 134    * @return the newly created Document instance
 135    *
 136    * @throws DocumentException
 137    * DocumentException org.dom4j.DocumentException} if an error
 138    * occurs during parsing.
 139    */
 140  0 public Document modify(InputSource source) throws DocumentException {
 141  0 try {
 142  0 return installModifyReader().read(source);
 143    } catch (SAXModifyException ex) {
 144  0 Throwable cause = ex.getCause();
 145  0 throw new DocumentException(cause.getMessage(), cause);
 146    }
 147    }
 148   
 149    /**
 150    * Reads a Document from the given {@link java.io.InputStream}and writes it
 151    * to the specified {@link XMLWriter}using SAX. Registered {@link
 152    * ElementModifier} objects are invoked on the fly.
 153    *
 154    * @param source
 155    * is the <code>java.io.InputStream</code> to read from.
 156    *
 157    * @return the newly created Document instance
 158    *
 159    * @throws DocumentException
 160    * DocumentException org.dom4j.DocumentException} if an error
 161    * occurs during parsing.
 162    */
 163  0 public Document modify(InputStream source) throws DocumentException {
 164  0 try {
 165  0 return installModifyReader().read(source);
 166    } catch (SAXModifyException ex) {
 167  0 Throwable cause = ex.getCause();
 168  0 throw new DocumentException(cause.getMessage(), cause);
 169    }
 170    }
 171   
 172    /**
 173    * Reads a Document from the given {@link java.io.InputStream}and writes it
 174    * to the specified {@link XMLWriter}using SAX. Registered {@link
 175    * ElementModifier} objects are invoked on the fly.
 176    *
 177    * @param source
 178    * is the <code>java.io.InputStream</code> to read from.
 179    * @param systemId
 180    * DOCUMENT ME!
 181    *
 182    * @return the newly created Document instance
 183    *
 184    * @throws DocumentException
 185    * DocumentException org.dom4j.DocumentException} if an error
 186    * occurs during parsing.
 187    */
 188  0 public Document modify(InputStream source, String systemId)
 189    throws DocumentException {
 190  0 try {
 191  0 return installModifyReader().read(source);
 192    } catch (SAXModifyException ex) {
 193  0 Throwable cause = ex.getCause();
 194  0 throw new DocumentException(cause.getMessage(), cause);
 195    }
 196    }
 197   
 198    /**
 199    * Reads a Document from the given {@link java.io.Reader}and writes it to
 200    * the specified {@link XMLWriter}using SAX. Registered {@link
 201    * ElementModifier} objects are invoked on the fly.
 202    *
 203    * @param source
 204    * is the <code>java.io.Reader</code> to read from.
 205    *
 206    * @return the newly created Document instance
 207    *
 208    * @throws DocumentException
 209    * DocumentException org.dom4j.DocumentException} if an error
 210    * occurs during parsing.
 211    */
 212  0 public Document modify(Reader source) throws DocumentException {
 213  0 try {
 214  0 return installModifyReader().read(source);
 215    } catch (SAXModifyException ex) {
 216  0 Throwable cause = ex.getCause();
 217  0 throw new DocumentException(cause.getMessage(), cause);
 218    }
 219    }
 220   
 221    /**
 222    * Reads a Document from the given {@link java.io.Reader}and writes it to
 223    * the specified {@link XMLWriter}using SAX. Registered {@link
 224    * ElementModifier} objects are invoked on the fly.
 225    *
 226    * @param source
 227    * is the <code>java.io.Reader</code> to read from.
 228    * @param systemId
 229    * DOCUMENT ME!
 230    *
 231    * @return the newly created Document instance
 232    *
 233    * @throws DocumentException
 234    * DocumentException org.dom4j.DocumentException} if an error
 235    * occurs during parsing.
 236    */
 237  0 public Document modify(Reader source, String systemId)
 238    throws DocumentException {
 239  0 try {
 240  0 return installModifyReader().read(source);
 241    } catch (SAXModifyException ex) {
 242  0 Throwable cause = ex.getCause();
 243  0 throw new DocumentException(cause.getMessage(), cause);
 244    }
 245    }
 246   
 247    /**
 248    * Reads a Document from the given {@link java.net.URL}and writes it to the
 249    * specified {@link XMLWriter}using SAX. Registered {@linkElementModifier}
 250    * objects are invoked on the fly.
 251    *
 252    * @param source
 253    * is the <code>java.net.URL</code> to read from.
 254    *
 255    * @return the newly created Document instance
 256    *
 257    * @throws DocumentException
 258    * DocumentException org.dom4j.DocumentException} if an error
 259    * occurs during parsing.
 260    */
 261  0 public Document modify(URL source) throws DocumentException {
 262  0 try {
 263  0 return installModifyReader().read(source);
 264    } catch (SAXModifyException ex) {
 265  0 Throwable cause = ex.getCause();
 266  0 throw new DocumentException(cause.getMessage(), cause);
 267    }
 268    }
 269   
 270    /**
 271    * Reads a Document from the given URL or filename and writes it to the
 272    * specified {@link XMLWriter}using SAX. Registered {@linkElementModifier}
 273    * objects are invoked on the fly.
 274    *
 275    * @param source
 276    * is the URL or filename to read from.
 277    *
 278    * @return the newly created Document instance
 279    *
 280    * @throws DocumentException
 281    * DocumentException org.dom4j.DocumentException} if an error
 282    * occurs during parsing.
 283    */
 284  0 public Document modify(String source) throws DocumentException {
 285  0 try {
 286  0 return installModifyReader().read(source);
 287    } catch (SAXModifyException ex) {
 288  0 Throwable cause = ex.getCause();
 289  0 throw new DocumentException(cause.getMessage(), cause);
 290    }
 291    }
 292   
 293    /**
 294    * Adds the {@link ElementModifier}to be called when the specified element
 295    * path is encounted while parsing the source.
 296    *
 297    * @param path
 298    * The element path to be handled
 299    * @param modifier
 300    * The {@link ElementModifier}to be called by the event based
 301    * processor.
 302    */
 303  0 public void addModifier(String path, ElementModifier modifier) {
 304  0 this.modifiers.put(path, modifier);
 305    }
 306   
 307    /**
 308    * Removes all registered {@link ElementModifier}instances from the event
 309    * based processor.
 310    */
 311  0 public void resetModifiers() {
 312  0 this.modifiers.clear();
 313  0 getSAXModifyReader().resetHandlers();
 314    }
 315   
 316    /**
 317    * Removes the {@link ElementModifier}from the event based processor, for
 318    * the specified element path.
 319    *
 320    * @param path
 321    * The path to remove the {@link ElementModifier}for.
 322    */
 323  0 public void removeModifier(String path) {
 324  0 this.modifiers.remove(path);
 325  0 getSAXModifyReader().removeHandler(path);
 326    }
 327   
 328    /**
 329    * Get the {@link org.dom4j.DocumentFactory}used to create the DOM4J
 330    * document structure
 331    *
 332    * @return <code>DocumentFactory</code> that will be used
 333    */
 334  0 public DocumentFactory getDocumentFactory() {
 335  0 return getSAXModifyReader().getDocumentFactory();
 336    }
 337   
 338    /**
 339    * Sets the {@link org.dom4j.DocumentFactory}used to create the DOM4J
 340    * document tree.
 341    *
 342    * @param factory
 343    * <code>DocumentFactory</code> to be used
 344    */
 345  0 public void setDocumentFactory(DocumentFactory factory) {
 346  0 getSAXModifyReader().setDocumentFactory(factory);
 347    }
 348   
 349    /**
 350    * Returns the current {@link XMLWriter}.
 351    *
 352    * @return XMLWriter
 353    */
 354  0 public XMLWriter getXMLWriter() {
 355  0 return this.xmlWriter;
 356    }
 357   
 358    /**
 359    * Sets the {@link XMLWriter}used to write the modified document.
 360    *
 361    * @param writer
 362    * The writer to use.
 363    */
 364  0 public void setXMLWriter(XMLWriter writer) {
 365  0 this.xmlWriter = writer;
 366    }
 367   
 368    /**
 369    * Returns true when xml elements are not kept in memory while parsing. The
 370    * {@link org.dom4j.Document}returned by the modify methods will be null.
 371    *
 372    * @return Returns the pruneElements.
 373    */
 374  0 public boolean isPruneElements() {
 375  0 return pruneElements;
 376    }
 377   
 378  0 private SAXReader installModifyReader() throws DocumentException {
 379  0 try {
 380  0 SAXModifyReader reader = getSAXModifyReader();
 381   
 382  0 if (isPruneElements()) {
 383  0 modifyReader.setDispatchHandler(new PruningDispatchHandler());
 384    }
 385   
 386  0 reader.resetHandlers();
 387   
 388  0 Iterator modifierIt = this.modifiers.entrySet().iterator();
 389   
 390  0 while (modifierIt.hasNext()) {
 391  0 Map.Entry entry = (Map.Entry) modifierIt.next();
 392   
 393  0 SAXModifyElementHandler handler = new SAXModifyElementHandler(
 394    (ElementModifier) entry.getValue());
 395  0 reader.addHandler((String) entry.getKey(), handler);
 396    }
 397   
 398  0 reader.setXMLWriter(getXMLWriter());
 399  0 reader.setXMLReader(getXMLReader());
 400   
 401  0 return reader;
 402    } catch (SAXException ex) {
 403  0 throw new DocumentException(ex.getMessage(), ex);
 404    }
 405    }
 406   
 407  0 private XMLReader getXMLReader() throws SAXException {
 408  0 if (this.xmlReader == null) {
 409  0 xmlReader = SAXHelper.createXMLReader(false);
 410    }
 411   
 412  0 return this.xmlReader;
 413    }
 414   
 415  0 private SAXModifyReader getSAXModifyReader() {
 416  0 if (modifyReader == null) {
 417  0 modifyReader = new SAXModifyReader();
 418    }
 419   
 420  0 return modifyReader;
 421    }
 422    }
 423   
 424    /*
 425    * Redistribution and use of this software and associated documentation
 426    * ("Software"), with or without modification, are permitted provided that the
 427    * following conditions are met:
 428    *
 429    * 1. Redistributions of source code must retain copyright statements and
 430    * notices. Redistributions must also contain a copy of this document.
 431    *
 432    * 2. Redistributions in binary form must reproduce the above copyright notice,
 433    * this list of conditions and the following disclaimer in the documentation
 434    * and/or other materials provided with the distribution.
 435    *
 436    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 437    * from this Software without prior written permission of MetaStuff, Ltd. For
 438    * written permission, please contact dom4j-info@metastuff.com.
 439    *
 440    * 4. Products derived from this Software may not be called "DOM4J" nor may
 441    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 442    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 443    *
 444    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 445    *
 446    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 447    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 448    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 449    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 450    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 451    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 452    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 453    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 454    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 455    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 456    * POSSIBILITY OF SUCH DAMAGE.
 457    *
 458    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 459    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/DispatchHandler.html0000644000175000017500000021042110242117702022440 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 255   Methods: 11
NCLOC: 84   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DispatchHandler.java 83,3% 64,1% 36,4% 62,9%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.util.ArrayList;
 11    import java.util.HashMap;
 12   
 13    import org.dom4j.Element;
 14    import org.dom4j.ElementHandler;
 15    import org.dom4j.ElementPath;
 16   
 17    /**
 18    * <p>
 19    * <code>DispatchHandler</code> implements the <code>ElementHandler</code>
 20    * interface and provides a means to register multiple
 21    * <code>ElementHandler</code> instances to be used by an event based
 22    * processor. This is a special <code>ElementHandler</code> in that it's
 23    * <b>onStart </b> and <b>onEnd </b> implementation methods are called for every
 24    * element encountered during the parse. It then delegates to other
 25    * <code>ElementHandler</code> instances registered with it to process the
 26    * elements encountered.
 27    * </p>
 28    *
 29    * @author <a href="mailto:dwhite@equipecom.com">Dave White </a>
 30    * @version $Revision: 1.11 $
 31    */
 32    class DispatchHandler implements ElementHandler {
 33    /** Whether the parser is at the root element or not */
 34    private boolean atRoot;
 35   
 36    /** The current path in the XML tree (i.e. /a/b/c) */
 37    private String path;
 38   
 39    /** maintains a stack of previously encountered paths */
 40    private ArrayList pathStack;
 41   
 42    /** maintains a stack of previously encountered handlers */
 43    private ArrayList handlerStack;
 44   
 45    /**
 46    * <code>HashMap</code> maintains the mapping between element paths and
 47    * handlers
 48    */
 49    private HashMap handlers;
 50   
 51    /**
 52    * <code>ElementHandler</code> to use by default for element paths with no
 53    * handlers registered
 54    */
 55    private ElementHandler defaultHandler;
 56   
 57  21 public DispatchHandler() {
 58  21 atRoot = true;
 59  21 path = "/";
 60  21 pathStack = new ArrayList();
 61  21 handlerStack = new ArrayList();
 62  21 handlers = new HashMap();
 63    }
 64   
 65    /**
 66    * Adds the <code>ElementHandler</code> to be called when the specified
 67    * path is encounted.
 68    *
 69    * @param handlerPath
 70    * is the path to be handled
 71    * @param handler
 72    * is the <code>ElementHandler</code> to be called by the event
 73    * based processor.
 74    */
 75  21 public void addHandler(String handlerPath, ElementHandler handler) {
 76  21 handlers.put(handlerPath, handler);
 77    }
 78   
 79    /**
 80    * Removes the <code>ElementHandler</code> from the event based processor,
 81    * for the specified path.
 82    *
 83    * @param handlerPath
 84    * is the path to remove the <code>ElementHandler</code> for.
 85    *
 86    * @return DOCUMENT ME!
 87    */
 88  0 public ElementHandler removeHandler(String handlerPath) {
 89  0 return (ElementHandler) handlers.remove(handlerPath);
 90    }
 91   
 92    /**
 93    * DOCUMENT ME!
 94    *
 95    * @param handlerPath
 96    * DOCUMENT ME!
 97    *
 98    * @return true when an <code>ElementHandler</code> is registered for the
 99    * specified path.
 100    */
 101  0 public boolean containsHandler(String handlerPath) {
 102  0 return handlers.containsKey(handlerPath);
 103    }
 104   
 105    /**
 106    * Get the registered {@link ElementHandler}for the specified path.
 107    *
 108    * @param handlerPath
 109    * XML path to get the handler for
 110    *
 111    * @return the registered handler
 112    */
 113  0 public ElementHandler getHandler(String handlerPath) {
 114  0 return (ElementHandler) handlers.get(handlerPath);
 115    }
 116   
 117    /**
 118    * Returns the number of {@link ElementHandler}objects that are waiting for
 119    * their elements closing tag.
 120    *
 121    * @return number of active handlers
 122    */
 123  0 public int getActiveHandlerCount() {
 124  0 return handlerStack.size();
 125    }
 126   
 127    /**
 128    * When multiple <code>ElementHandler</code> instances have been
 129    * registered, this will set a default <code>ElementHandler</code> to be
 130    * called for any path which does <b>NOT </b> have a handler registered.
 131    *
 132    * @param handler
 133    * is the <code>ElementHandler</code> to be called by the event
 134    * based processor.
 135    */
 136  0 public void setDefaultHandler(ElementHandler handler) {
 137  0 defaultHandler = handler;
 138    }
 139   
 140    /**
 141    * Used to remove all the Element Handlers and return things back to the way
 142    * they were when object was created.
 143    */
 144  0 public void resetHandlers() {
 145  0 atRoot = true;
 146  0 path = "/";
 147  0 pathStack.clear();
 148  0 handlerStack.clear();
 149  0 handlers.clear();
 150  0 defaultHandler = null;
 151    }
 152   
 153    /**
 154    * DOCUMENT ME!
 155    *
 156    * @return the current path for the parse
 157    */
 158  0 public String getPath() {
 159  0 return path;
 160    }
 161   
 162    // The following methods implement the ElementHandler interface
 163  78 public void onStart(ElementPath elementPath) {
 164  78 Element element = elementPath.getCurrent();
 165   
 166    // Save the location of the last (i.e. parent) path
 167  78 pathStack.add(path);
 168   
 169    // Calculate the new path
 170  78 if (atRoot) {
 171  18 path = path + element.getName();
 172  18 atRoot = false;
 173    } else {
 174  60 path = path + "/" + element.getName();
 175    }
 176   
 177  78 if ((handlers != null) && (handlers.containsKey(path))) {
 178    // The current node has a handler associated with it.
 179    // Find the handler and save it on the handler stack.
 180  54 ElementHandler handler = (ElementHandler) handlers.get(path);
 181  54 handlerStack.add(handler);
 182   
 183    // Call the handlers onStart method.
 184  54 handler.onStart(elementPath);
 185    } else {
 186    // No handler is associated with this node, so use the
 187    // defaultHandler it it exists.
 188  24 if (handlerStack.isEmpty() && (defaultHandler != null)) {
 189  0 defaultHandler.onStart(elementPath);
 190    }
 191    }
 192    }
 193   
 194  78 public void onEnd(ElementPath elementPath) {
 195  78 if ((handlers != null) && (handlers.containsKey(path))) {
 196    // This node has a handler associated with it.
 197    // Find the handler and pop it from the handler stack.
 198  54 ElementHandler handler = (ElementHandler) handlers.get(path);
 199  54 handlerStack.remove(handlerStack.size() - 1);
 200   
 201    // Call the handlers onEnd method
 202  54 handler.onEnd(elementPath);
 203    } else {
 204    // No handler is associated with this node, so use the
 205    // defaultHandler it it exists.
 206  24 if (handlerStack.isEmpty() && (defaultHandler != null)) {
 207  0 defaultHandler.onEnd(elementPath);
 208    }
 209    }
 210   
 211    // Set path back to its parent
 212  78 path = (String) pathStack.remove(pathStack.size() - 1);
 213   
 214  78 if (pathStack.size() == 0) {
 215  18 atRoot = true;
 216    }
 217    }
 218    }
 219   
 220    /*
 221    * Redistribution and use of this software and associated documentation
 222    * ("Software"), with or without modification, are permitted provided that the
 223    * following conditions are met:
 224    *
 225    * 1. Redistributions of source code must retain copyright statements and
 226    * notices. Redistributions must also contain a copy of this document.
 227    *
 228    * 2. Redistributions in binary form must reproduce the above copyright notice,
 229    * this list of conditions and the following disclaimer in the documentation
 230    * and/or other materials provided with the distribution.
 231    *
 232    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 233    * from this Software without prior written permission of MetaStuff, Ltd. For
 234    * written permission, please contact dom4j-info@metastuff.com.
 235    *
 236    * 4. Products derived from this Software may not be called "DOM4J" nor may
 237    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 238    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 239    *
 240    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 241    *
 242    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 243    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 244    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 245    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 246    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 247    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 248    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 249    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 250    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 251    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 252    * POSSIBILITY OF SUCH DAMAGE.
 253    *
 254    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 255    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/SAXContentHandler.html0000644000175000017500000101570410242117735022705 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 1.006   Methods: 55
NCLOC: 449   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
SAXContentHandler.java 64,4% 79,2% 72,7% 73,8%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.lang.reflect.Method;
 11    import java.util.ArrayList;
 12    import java.util.HashMap;
 13    import java.util.List;
 14    import java.util.Map;
 15   
 16    import org.dom4j.Branch;
 17    import org.dom4j.Document;
 18    import org.dom4j.DocumentFactory;
 19    import org.dom4j.DocumentType;
 20    import org.dom4j.Element;
 21    import org.dom4j.ElementHandler;
 22    import org.dom4j.Namespace;
 23    import org.dom4j.QName;
 24    import org.dom4j.dtd.AttributeDecl;
 25    import org.dom4j.dtd.ElementDecl;
 26    import org.dom4j.dtd.ExternalEntityDecl;
 27    import org.dom4j.dtd.InternalEntityDecl;
 28    import org.dom4j.tree.AbstractElement;
 29    import org.dom4j.tree.NamespaceStack;
 30   
 31    import org.xml.sax.Attributes;
 32    import org.xml.sax.DTDHandler;
 33    import org.xml.sax.EntityResolver;
 34    import org.xml.sax.InputSource;
 35    import org.xml.sax.Locator;
 36    import org.xml.sax.SAXException;
 37    import org.xml.sax.SAXParseException;
 38    import org.xml.sax.ext.DeclHandler;
 39    import org.xml.sax.ext.LexicalHandler;
 40    import org.xml.sax.helpers.DefaultHandler;
 41   
 42    /**
 43    * <p>
 44    * <code>SAXContentHandler</code> builds a dom4j tree via SAX events.
 45    * </p>
 46    *
 47    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 48    * @version $Revision: 1.61 $
 49    */
 50    public class SAXContentHandler extends DefaultHandler implements
 51    LexicalHandler, DeclHandler, DTDHandler {
 52    /** The factory used to create new <code>Document</code> instances */
 53    private DocumentFactory documentFactory;
 54   
 55    /** The document that is being built */
 56    private Document document;
 57   
 58    /** stack of <code>Element</code> objects */
 59    private ElementStack elementStack;
 60   
 61    /** stack of <code>Namespace</code> and <code>QName</code> objects */
 62    private NamespaceStack namespaceStack;
 63   
 64    /** the <code>ElementHandler</code> called as the elements are complete */
 65    private ElementHandler elementHandler;
 66   
 67    /** the Locator */
 68    private Locator locator;
 69   
 70    /** The name of the current entity */
 71    private String entity;
 72   
 73    /** Flag used to indicate that we are inside a DTD section */
 74    private boolean insideDTDSection;
 75   
 76    /** Flag used to indicate that we are inside a CDATA section */
 77    private boolean insideCDATASection;
 78   
 79    /**
 80    * buffer to hold contents of cdata section across multiple characters
 81    * events
 82    */
 83    private StringBuffer cdataText;
 84   
 85    /** namespaces that are available for use */
 86    private Map availableNamespaceMap = new HashMap();
 87   
 88    /** declared namespaces that are not yet available for use */
 89    private List declaredNamespaceList = new ArrayList();
 90   
 91    /** internal DTD declarations */
 92    private List internalDTDDeclarations;
 93   
 94    /** external DTD declarations */
 95    private List externalDTDDeclarations;
 96   
 97    /** The number of namespaces that are declared in the current scope */
 98    private int declaredNamespaceIndex;
 99   
 100    /** The entity resolver */
 101    private EntityResolver entityResolver;
 102   
 103    private InputSource inputSource;
 104   
 105    /** The current element we are on */
 106    private Element currentElement;
 107   
 108    /** Should internal DTD declarations be expanded into a List in the DTD */
 109    private boolean includeInternalDTDDeclarations = false;
 110   
 111    /** Should external DTD declarations be expanded into a List in the DTD */
 112    private boolean includeExternalDTDDeclarations = false;
 113   
 114    /** The number of levels deep we are inside a startEntity/endEntity call */
 115    private int entityLevel;
 116   
 117    /** Are we in an internal DTD subset? */
 118    private boolean internalDTDsubset = false;
 119   
 120    /** Whether adjacent text nodes should be merged */
 121    private boolean mergeAdjacentText = false;
 122   
 123    /** Have we added text to the buffer */
 124    private boolean textInTextBuffer = false;
 125   
 126    /** Should we ignore comments */
 127    private boolean ignoreComments = false;
 128   
 129    /** Buffer used to concatenate text together */
 130    private StringBuffer textBuffer;
 131   
 132    /** Holds value of property stripWhitespaceText. */
 133    private boolean stripWhitespaceText = false;
 134   
 135  19 public SAXContentHandler() {
 136  19 this(DocumentFactory.getInstance());
 137    }
 138   
 139  19 public SAXContentHandler(DocumentFactory documentFactory) {
 140  19 this(documentFactory, null);
 141    }
 142   
 143  5811 public SAXContentHandler(DocumentFactory documentFactory,
 144    ElementHandler elementHandler) {
 145  5811 this(documentFactory, elementHandler, null);
 146  5811 this.elementStack = createElementStack();
 147    }
 148   
 149  5811 public SAXContentHandler(DocumentFactory documentFactory,
 150    ElementHandler elementHandler, ElementStack elementStack) {
 151  5811 this.documentFactory = documentFactory;
 152  5811 this.elementHandler = elementHandler;
 153  5811 this.elementStack = elementStack;
 154  5811 this.namespaceStack = new NamespaceStack(documentFactory);
 155    }
 156   
 157    /**
 158    * DOCUMENT ME!
 159    *
 160    * @return the document that has been or is being built
 161    */
 162  11692 public Document getDocument() {
 163  11692 if (document == null) {
 164  5814 document = createDocument();
 165    }
 166   
 167  11692 return document;
 168    }
 169   
 170    // ContentHandler interface
 171    // -------------------------------------------------------------------------
 172  5813 public void setDocumentLocator(Locator documentLocator) {
 173  5813 this.locator = documentLocator;
 174    }
 175   
 176  23 public void processingInstruction(String target, String data)
 177    throws SAXException {
 178  23 if (mergeAdjacentText && textInTextBuffer) {
 179  0 completeCurrentTextNode();
 180    }
 181   
 182  23 if (currentElement != null) {
 183  1 currentElement.addProcessingInstruction(target, data);
 184    } else {
 185  22 getDocument().addProcessingInstruction(target, data);
 186    }
 187    }
 188   
 189  5884 public void startPrefixMapping(String prefix, String uri)
 190    throws SAXException {
 191  5884 namespaceStack.push(prefix, uri);
 192    }
 193   
 194  5884 public void endPrefixMapping(String prefix) throws SAXException {
 195  5884 namespaceStack.pop(prefix);
 196  5884 declaredNamespaceIndex = namespaceStack.size();
 197    }
 198   
 199  5814 public void startDocument() throws SAXException {
 200    // document = createDocument();
 201  5814 document = null;
 202  5814 currentElement = null;
 203   
 204  5814 elementStack.clear();
 205   
 206  5814 if ((elementHandler != null)
 207    && (elementHandler instanceof DispatchHandler)) {
 208  18 elementStack.setDispatchHandler((DispatchHandler) elementHandler);
 209    }
 210   
 211  5814 namespaceStack.clear();
 212  5814 declaredNamespaceIndex = 0;
 213   
 214  5814 if (mergeAdjacentText && (textBuffer == null)) {
 215  4 textBuffer = new StringBuffer();
 216    }
 217   
 218  5814 textInTextBuffer = false;
 219    }
 220   
 221  5814 public void endDocument() throws SAXException {
 222  5814 namespaceStack.clear();
 223  5814 elementStack.clear();
 224  5814 currentElement = null;
 225  5814 textBuffer = null;
 226    }
 227   
 228  86721 public void startElement(String namespaceURI, String localName,
 229    String qualifiedName, Attributes attributes) throws SAXException {
 230  86721 if (mergeAdjacentText && textInTextBuffer) {
 231  1 completeCurrentTextNode();
 232    }
 233   
 234  86721 QName qName = namespaceStack.getQName(namespaceURI, localName,
 235    qualifiedName);
 236   
 237  86721 Branch branch = currentElement;
 238   
 239  86721 if (branch == null) {
 240  5814 branch = getDocument();
 241    }
 242   
 243  86721 Element element = branch.addElement(qName);
 244   
 245    // add all declared namespaces
 246  86721 addDeclaredNamespaces(element);
 247   
 248    // now lets add all attribute values
 249  86721 addAttributes(element, attributes);
 250   
 251  86721 elementStack.pushElement(element);
 252  86721 currentElement = element;
 253   
 254  86721 entity = null; // fixes bug527062
 255   
 256  86721 if (elementHandler != null) {
 257  78 elementHandler.onStart(elementStack);
 258    }
 259    }
 260   
 261  86721 public void endElement(String namespaceURI, String localName, String qName)
 262    throws SAXException {
 263  86721 if (mergeAdjacentText && textInTextBuffer) {
 264  5 completeCurrentTextNode();
 265    }
 266   
 267  86721 if ((elementHandler != null) && (currentElement != null)) {
 268  78 elementHandler.onEnd(elementStack);
 269    }
 270   
 271  86721 elementStack.popElement();
 272  86721 currentElement = elementStack.peekElement();
 273    }
 274   
 275  109454 public void characters(char[] ch, int start, int end) throws SAXException {
 276  109454 if (end == 0) {
 277  0 return;
 278    }
 279   
 280  109454 if (currentElement != null) {
 281  109454 if (entity != null) {
 282  4 if (mergeAdjacentText && textInTextBuffer) {
 283  0 completeCurrentTextNode();
 284    }
 285   
 286  4 currentElement.addEntity(entity, new String(ch, start, end));
 287  4 entity = null;
 288  109450 } else if (insideCDATASection) {
 289  200 if (mergeAdjacentText && textInTextBuffer) {
 290  1 completeCurrentTextNode();
 291    }
 292   
 293  200 cdataText.append(new String(ch, start, end));
 294    } else {
 295  109250 if (mergeAdjacentText) {
 296  32 textBuffer.append(ch, start, end);
 297  32 textInTextBuffer = true;
 298    } else {
 299  109218 currentElement.addText(new String(ch, start, end));
 300    }
 301    }
 302    }
 303    }
 304   
 305    // ErrorHandler interface
 306    // -------------------------------------------------------------------------
 307   
 308    /**
 309    * This method is called when a warning occurs during the parsing of the
 310    * document. This method does nothing.
 311    *
 312    * @param exception
 313    * DOCUMENT ME!
 314    *
 315    * @throws SAXException
 316    * DOCUMENT ME!
 317    */
 318  0 public void warning(SAXParseException exception) throws SAXException {
 319    // ignore warnings by default
 320    }
 321   
 322    /**
 323    * This method is called when an error is detected during parsing such as a
 324    * validation error. This method rethrows the exception
 325    *
 326    * @param exception
 327    * DOCUMENT ME!
 328    *
 329    * @throws SAXException
 330    * DOCUMENT ME!
 331    */
 332  0 public void error(SAXParseException exception) throws SAXException {
 333  0 throw exception;
 334    }
 335   
 336    /**
 337    * This method is called when a fatal error occurs during parsing. This
 338    * method rethrows the exception
 339    *
 340    * @param exception
 341    * DOCUMENT ME!
 342    *
 343    * @throws SAXException
 344    * DOCUMENT ME!
 345    */
 346  0 public void fatalError(SAXParseException exception) throws SAXException {
 347  0 throw exception;
 348    }
 349   
 350    // LexicalHandler interface
 351    // -------------------------------------------------------------------------
 352  11 public void startDTD(String name, String publicId, String systemId)
 353    throws SAXException {
 354  11 getDocument().addDocType(name, publicId, systemId);
 355  11 insideDTDSection = true;
 356  11 internalDTDsubset = true;
 357    }
 358   
 359  11 public void endDTD() throws SAXException {
 360  11 insideDTDSection = false;
 361   
 362  11 DocumentType docType = getDocument().getDocType();
 363   
 364  11 if (docType != null) {
 365  11 if (internalDTDDeclarations != null) {
 366  4 docType.setInternalDeclarations(internalDTDDeclarations);
 367    }
 368   
 369  11 if (externalDTDDeclarations != null) {
 370  3 docType.setExternalDeclarations(externalDTDDeclarations);
 371    }
 372    }
 373   
 374  11 internalDTDDeclarations = null;
 375  11 externalDTDDeclarations = null;
 376    }
 377   
 378  433 public void startEntity(String name) throws SAXException {
 379  433 ++entityLevel;
 380   
 381    // Ignore DTD references
 382  433 entity = null;
 383   
 384  433 if (!insideDTDSection) {
 385  429 if (!isIgnorableEntity(name)) {
 386  5 entity = name;
 387    }
 388    }
 389   
 390    // internal DTD subsets can only appear outside of a
 391    // startEntity/endEntity block
 392    // see the startDTD method in
 393    // http://dom4j.org/javadoc/org/xml/sax/ext/LexicalHandler.html
 394  433 internalDTDsubset = false;
 395    }
 396   
 397  433 public void endEntity(String name) throws SAXException {
 398  433 --entityLevel;
 399  433 entity = null;
 400   
 401  433 if (entityLevel == 0) {
 402  433 internalDTDsubset = true;
 403    }
 404    }
 405   
 406  70 public void startCDATA() throws SAXException {
 407  70 insideCDATASection = true;
 408  70 cdataText = new StringBuffer();
 409    }
 410   
 411  70 public void endCDATA() throws SAXException {
 412  70 insideCDATASection = false;
 413  70 currentElement.addCDATA(cdataText.toString());
 414    }
 415   
 416  445 public void comment(char[] ch, int start, int end) throws SAXException {
 417  445 if (!ignoreComments) {
 418  445 if (mergeAdjacentText && textInTextBuffer) {
 419  1 completeCurrentTextNode();
 420    }
 421   
 422  445 String text = new String(ch, start, end);
 423   
 424  445 if (!insideDTDSection && (text.length() > 0)) {
 425  442 if (currentElement != null) {
 426  422 currentElement.addComment(text);
 427    } else {
 428  20 getDocument().addComment(text);
 429    }
 430    }
 431    }
 432    }
 433   
 434    // DeclHandler interface
 435    // -------------------------------------------------------------------------
 436   
 437    /**
 438    * Report an element type declaration.
 439    *
 440    * <p>
 441    * The content model will consist of the string "EMPTY", the string "ANY",
 442    * or a parenthesised group, optionally followed by an occurrence indicator.
 443    * The model will be normalized so that all parameter entities are fully
 444    * resolved and all whitespace is removed,and will include the enclosing
 445    * parentheses. Other normalization (such as removing redundant parentheses
 446    * or simplifying occurrence indicators) is at the discretion of the parser.
 447    * </p>
 448    *
 449    * @param name
 450    * The element type name.
 451    * @param model
 452    * The content model as a normalized string.
 453    *
 454    * @exception SAXException
 455    * The application may raise an exception.
 456    */
 457  6 public void elementDecl(String name, String model) throws SAXException {
 458  6 if (internalDTDsubset) {
 459  3 if (includeInternalDTDDeclarations) {
 460  3 addDTDDeclaration(new ElementDecl(name, model));
 461    }
 462    } else {
 463  3 if (includeExternalDTDDeclarations) {
 464  3 addExternalDTDDeclaration(new ElementDecl(name, model));
 465    }
 466    }
 467    }
 468   
 469    /**
 470    * Report an attribute type declaration.
 471    *
 472    * <p>
 473    * Only the effective (first) declaration for an attribute will be reported.
 474    * The type will be one of the strings "CDATA", "ID", "IDREF", "IDREFS",
 475    * "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", a parenthesized token group
 476    * with the separator "|" and all whitespace removed, or the word "NOTATION"
 477    * followed by a space followed by a parenthesized token group with all
 478    * whitespace removed.
 479    * </p>
 480    *
 481    * <p>
 482    * Any parameter entities in the attribute value will be expanded, but
 483    * general entities will not.
 484    * </p>
 485    *
 486    * @param eName
 487    * The name of the associated element.
 488    * @param aName
 489    * The name of the attribute.
 490    * @param type
 491    * A string representing the attribute type.
 492    * @param valueDefault
 493    * A string representing the attribute default ("#IMPLIED",
 494    * "#REQUIRED", or "#FIXED") or null if none of these applies.
 495    * @param val
 496    * A string representing the attribute's default value, or null
 497    * if there is none.
 498    *
 499    * @exception SAXException
 500    * The application may raise an exception.
 501    */
 502  3 public void attributeDecl(String eName, String aName, String type,
 503    String valueDefault, String val) throws SAXException {
 504  3 if (internalDTDsubset) {
 505  3 if (includeInternalDTDDeclarations) {
 506  3 addDTDDeclaration(new AttributeDecl(eName, aName, type,
 507    valueDefault, val));
 508    }
 509    } else {
 510  0 if (includeExternalDTDDeclarations) {
 511  0 addExternalDTDDeclaration(new AttributeDecl(eName, aName, type,
 512    valueDefault, val));
 513    }
 514    }
 515    }
 516   
 517    /**
 518    * Report an internal entity declaration.
 519    *
 520    * <p>
 521    * Only the effective (first) declaration for each entity will be reported.
 522    * All parameter entities in the value will be expanded, but general
 523    * entities will not.
 524    * </p>
 525    *
 526    * @param name
 527    * The name of the entity. If it is a parameter entity, the name
 528    * will begin with '%'.
 529    * @param value
 530    * The replacement text of the entity.
 531    *
 532    * @exception SAXException
 533    * The application may raise an exception.
 534    *
 535    * @see #externalEntityDecl
 536    * @see org.xml.sax.DTDHandler#unparsedEntityDecl
 537    */
 538  13 public void internalEntityDecl(String name, String value)
 539    throws SAXException {
 540  13 if (internalDTDsubset) {
 541  13 if (includeInternalDTDDeclarations) {
 542  13 addDTDDeclaration(new InternalEntityDecl(name, value));
 543    }
 544    } else {
 545  0 if (includeExternalDTDDeclarations) {
 546  0 addExternalDTDDeclaration(new InternalEntityDecl(name, value));
 547    }
 548    }
 549    }
 550   
 551    /**
 552    * Report a parsed external entity declaration.
 553    *
 554    * <p>
 555    * Only the effective (first) declaration for each entity will be reported.
 556    * </p>
 557    *
 558    * @param name
 559    * The name of the entity. If it is a parameter entity, the name
 560    * will begin with '%'.
 561    * @param publicId
 562    * The declared public identifier of the entity, or null if none
 563    * was declared.
 564    * @param sysId
 565    * The declared system identifier of the entity.
 566    *
 567    * @exception SAXException
 568    * The application may raise an exception.
 569    *
 570    * @see #internalEntityDecl
 571    * @see org.xml.sax.DTDHandler#unparsedEntityDecl
 572    */
 573  0 public void externalEntityDecl(String name, String publicId, String sysId)
 574    throws SAXException {
 575  0 ExternalEntityDecl declaration = new ExternalEntityDecl(name, publicId,
 576    sysId);
 577   
 578  0 if (internalDTDsubset) {
 579  0 if (includeInternalDTDDeclarations) {
 580  0 addDTDDeclaration(declaration);
 581    }
 582    } else {
 583  0 if (includeExternalDTDDeclarations) {
 584  0 addExternalDTDDeclaration(declaration);
 585    }
 586    }
 587    }
 588   
 589    // DTDHandler interface
 590    // -------------------------------------------------------------------------
 591   
 592    /**
 593    * Receive notification of a notation declaration event.
 594    *
 595    * <p>
 596    * It is up to the application to record the notation for later reference,
 597    * if necessary.
 598    * </p>
 599    *
 600    * <p>
 601    * At least one of publicId and systemId must be non-null. If a system
 602    * identifier is present, and it is a URL, the SAX parser must resolve it
 603    * fully before passing it to the application through this event.
 604    * </p>
 605    *
 606    * <p>
 607    * There is no guarantee that the notation declaration will be reported
 608    * before any unparsed entities that use it.
 609    * </p>
 610    *
 611    * @param name
 612    * The notation name.
 613    * @param publicId
 614    * The notation's public identifier, or null if none was given.
 615    * @param systemId
 616    * The notation's system identifier, or null if none was given.
 617    *
 618    * @exception SAXException
 619    * Any SAX exception, possibly wrapping another exception.
 620    *
 621    * @see #unparsedEntityDecl
 622    * @see org.xml.sax.AttributeList
 623    */
 624  0 public void notationDecl(String name, String publicId, String systemId)
 625    throws SAXException {
 626    // #### not supported yet!
 627    }
 628   
 629    /**
 630    * Receive notification of an unparsed entity declaration event.
 631    *
 632    * <p>
 633    * Note that the notation name corresponds to a notation reported by the
 634    * {@link #notationDecl notationDecl}event. It is up to the application to
 635    * record the entity for later reference, if necessary.
 636    * </p>
 637    *
 638    * <p>
 639    * If the system identifier is a URL, the parser must resolve it fully
 640    * before passing it to the application.
 641    * </p>
 642    *
 643    * @param name
 644    * The unparsed entity's name.
 645    * @param publicId
 646    * The entity's public identifier, or null if none was given.
 647    * @param systemId
 648    * The entity's system identifier.
 649    * @param notationName
 650    * The name of the associated notation.
 651    *
 652    * @exception SAXException
 653    * Any SAX exception, possibly wrapping another exception.
 654    *
 655    * @see #notationDecl
 656    * @see org.xml.sax.AttributeList
 657    */
 658  0 public void unparsedEntityDecl(String name, String publicId,
 659    String systemId, String notationName) throws SAXException {
 660    // #### not supported yet!
 661    }
 662   
 663    // Properties
 664    // -------------------------------------------------------------------------
 665  0 public ElementStack getElementStack() {
 666  0 return elementStack;
 667    }
 668   
 669  0 public void setElementStack(ElementStack elementStack) {
 670  0 this.elementStack = elementStack;
 671    }
 672   
 673  0 public EntityResolver getEntityResolver() {
 674  0 return entityResolver;
 675    }
 676   
 677  5792 public void setEntityResolver(EntityResolver entityResolver) {
 678  5792 this.entityResolver = entityResolver;
 679    }
 680   
 681  0 public InputSource getInputSource() {
 682  0 return inputSource;
 683    }
 684   
 685  5792 public void setInputSource(InputSource inputSource) {
 686  5792 this.inputSource = inputSource;
 687    }
 688   
 689    /**
 690    * DOCUMENT ME!
 691    *
 692    * @return whether internal DTD declarations should be expanded into the
 693    * DocumentType object or not.
 694    */
 695  0 public boolean isIncludeInternalDTDDeclarations() {
 696  0 return includeInternalDTDDeclarations;
 697    }
 698   
 699    /**
 700    * Sets whether internal DTD declarations should be expanded into the
 701    * DocumentType object or not.
 702    *
 703    * @param include
 704    * whether or not DTD declarations should be expanded and
 705    * included into the DocumentType object.
 706    */
 707  5792 public void setIncludeInternalDTDDeclarations(boolean include) {
 708  5792 this.includeInternalDTDDeclarations = include;
 709    }
 710   
 711    /**
 712    * DOCUMENT ME!
 713    *
 714    * @return whether external DTD declarations should be expanded into the
 715    * DocumentType object or not.
 716    */
 717  0 public boolean isIncludeExternalDTDDeclarations() {
 718  0 return includeExternalDTDDeclarations;
 719    }
 720   
 721    /**
 722    * Sets whether DTD external declarations should be expanded into the
 723    * DocumentType object or not.
 724    *
 725    * @param include
 726    * whether or not DTD declarations should be expanded and
 727    * included into the DocumentType object.
 728    */
 729  5792 public void setIncludeExternalDTDDeclarations(boolean include) {
 730  5792 this.includeExternalDTDDeclarations = include;
 731    }
 732   
 733    /**
 734    * Returns whether adjacent text nodes should be merged together.
 735    *
 736    * @return Value of property mergeAdjacentText.
 737    */
 738  0 public boolean isMergeAdjacentText() {
 739  0 return mergeAdjacentText;
 740    }
 741   
 742    /**
 743    * Sets whether or not adjacent text nodes should be merged together when
 744    * parsing.
 745    *
 746    * @param mergeAdjacentText
 747    * New value of property mergeAdjacentText.
 748    */
 749  5792 public void setMergeAdjacentText(boolean mergeAdjacentText) {
 750  5792 this.mergeAdjacentText = mergeAdjacentText;
 751    }
 752   
 753    /**
 754    * Sets whether whitespace between element start and end tags should be
 755    * ignored
 756    *
 757    * @return Value of property stripWhitespaceText.
 758    */
 759  0 public boolean isStripWhitespaceText() {
 760  0 return stripWhitespaceText;
 761    }
 762   
 763    /**
 764    * Sets whether whitespace between element start and end tags should be
 765    * ignored.
 766    *
 767    * @param stripWhitespaceText
 768    * New value of property stripWhitespaceText.
 769    */
 770  5792 public void setStripWhitespaceText(boolean stripWhitespaceText) {
 771  5792 this.stripWhitespaceText = stripWhitespaceText;
 772    }
 773   
 774    /**
 775    * Returns whether we should ignore comments or not.
 776    *
 777    * @return boolean
 778    */
 779  0 public boolean isIgnoreComments() {
 780  0 return ignoreComments;
 781    }
 782   
 783    /**
 784    * Sets whether we should ignore comments or not.
 785    *
 786    * @param ignoreComments
 787    * whether we should ignore comments or not.
 788    */
 789  5792 public void setIgnoreComments(boolean ignoreComments) {
 790  5792 this.ignoreComments = ignoreComments;
 791    }
 792   
 793    // Implementation methods
 794    // -------------------------------------------------------------------------
 795   
 796    /**
 797    * If the current text buffer contains any text then create a new text node
 798    * with it and add it to the current element
 799    */
 800  8 protected void completeCurrentTextNode() {
 801  8 if (stripWhitespaceText) {
 802  0 boolean whitespace = true;
 803   
 804  0 for (int i = 0, size = textBuffer.length(); i < size; i++) {
 805  0 if (!Character.isWhitespace(textBuffer.charAt(i))) {
 806  0 whitespace = false;
 807   
 808  0 break;
 809    }
 810    }
 811   
 812  0 if (!whitespace) {
 813  0 currentElement.addText(textBuffer.toString());
 814    }
 815    } else {
 816  8 currentElement.addText(textBuffer.toString());
 817    }
 818   
 819  8 textBuffer.setLength(0);
 820  8 textInTextBuffer = false;
 821    }
 822   
 823    /**
 824    * DOCUMENT ME!
 825    *
 826    * @return the current document
 827    */
 828  5814 protected Document createDocument() {
 829  5814 String encoding = getEncoding();
 830  5814 Document doc = documentFactory.createDocument(encoding);
 831   
 832    // set the EntityResolver
 833  5814 doc.setEntityResolver(entityResolver);
 834   
 835  5814 if (inputSource != null) {
 836  5791 doc.setName(inputSource.getSystemId());
 837    }
 838   
 839  5814 return doc;
 840    }
 841   
 842  5814 private String getEncoding() {
 843  5814 if (locator == null) {
 844  1 return null;
 845    }
 846   
 847    // use reflection to avoid dependency on Locator2
 848    // or other locator implemenations.
 849  5813 try {
 850  5813 Method m = locator.getClass().getMethod("getEncoding",
 851    new Class[] {});
 852   
 853  5801 if (m != null) {
 854  5801 return (String) m.invoke(locator, null);
 855    }
 856    } catch (Exception e) {
 857    // do nothing
 858    }
 859   
 860    // couldn't determine encoding, returning null...
 861  12 return null;
 862    }
 863   
 864    /**
 865    * a Strategy Method to determine if a given entity name is ignorable
 866    *
 867    * @param name
 868    * DOCUMENT ME!
 869    *
 870    * @return DOCUMENT ME!
 871    */
 872  429 protected boolean isIgnorableEntity(String name) {
 873  429 return "amp".equals(name) || "apos".equals(name) || "gt".equals(name)
 874    || "lt".equals(name) || "quot".equals(name);
 875    }
 876   
 877    /**
 878    * Add all namespaces declared before the startElement() SAX event to the
 879    * current element so that they are available to child elements and
 880    * attributes
 881    *
 882    * @param element
 883    * DOCUMENT ME!
 884    */
 885  86721 protected void addDeclaredNamespaces(Element element) {
 886  86701 Namespace elementNamespace = element.getNamespace();
 887   
 888  86721 for (int size = namespaceStack.size(); declaredNamespaceIndex < size;
 889    declaredNamespaceIndex++) {
 890  5884 Namespace namespace = namespaceStack
 891    .getNamespace(declaredNamespaceIndex);
 892   
 893    // if ( namespace != elementNamespace ) {
 894  5884 element.add(namespace);
 895   
 896    // }
 897    }
 898    }
 899   
 900    /**
 901    * Add all the attributes to the given elements
 902    *
 903    * @param element
 904    * DOCUMENT ME!
 905    * @param attributes
 906    * DOCUMENT ME!
 907    */
 908  86721 protected void addAttributes(Element element, Attributes attributes) {
 909    // XXXX: as an optimisation, we could deduce this value from the current
 910    // SAX parser settings, the SAX namespaces-prefixes feature
 911  86721 boolean noNamespaceAttributes = false;
 912   
 913  86721 if (element instanceof AbstractElement) {
 914    // optimised method
 915  86700 AbstractElement baseElement = (AbstractElement) element;
 916  86721 baseElement.setAttributes(attributes, namespaceStack,
 917    noNamespaceAttributes);
 918    } else {
 919  0 int size = attributes.getLength();
 920   
 921  0 for (int i = 0; i < size; i++) {
 922  0 String attributeQName = attributes.getQName(i);
 923   
 924  0 if (noNamespaceAttributes
 925    || !attributeQName.startsWith("xmlns")) {
 926  0 String attributeURI = attributes.getURI(i);
 927  0 String attributeLocalName = attributes.getLocalName(i);
 928  0 String attributeValue = attributes.getValue(i);
 929   
 930  0 QName qName = namespaceStack.getAttributeQName(
 931    attributeURI, attributeLocalName, attributeQName);
 932  0 element.addAttribute(qName, attributeValue);
 933    }
 934    }
 935    }
 936    }
 937   
 938    /**
 939    * Adds an internal DTD declaration to the list of declarations
 940    *
 941    * @param declaration
 942    * DOCUMENT ME!
 943    */
 944  19 protected void addDTDDeclaration(Object declaration) {
 945  19 if (internalDTDDeclarations == null) {
 946  4 internalDTDDeclarations = new ArrayList();
 947    }
 948   
 949  19 internalDTDDeclarations.add(declaration);
 950    }
 951   
 952    /**
 953    * Adds an external DTD declaration to the list of declarations
 954    *
 955    * @param declaration
 956    * DOCUMENT ME!
 957    */
 958  3 protected void addExternalDTDDeclaration(Object declaration) {
 959  3 if (externalDTDDeclarations == null) {
 960  3 externalDTDDeclarations = new ArrayList();
 961    }
 962   
 963  3 externalDTDDeclarations.add(declaration);
 964    }
 965   
 966  5811 protected ElementStack createElementStack() {
 967  5811 return new ElementStack();
 968    }
 969    }
 970   
 971    /*
 972    * Redistribution and use of this software and associated documentation
 973    * ("Software"), with or without modification, are permitted provided that the
 974    * following conditions are met:
 975    *
 976    * 1. Redistributions of source code must retain copyright statements and
 977    * notices. Redistributions must also contain a copy of this document.
 978    *
 979    * 2. Redistributions in binary form must reproduce the above copyright notice,
 980    * this list of conditions and the following disclaimer in the documentation
 981    * and/or other materials provided with the distribution.
 982    *
 983    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 984    * from this Software without prior written permission of MetaStuff, Ltd. For
 985    * written permission, please contact dom4j-info@metastuff.com.
 986    *
 987    * 4. Products derived from this Software may not be called "DOM4J" nor may
 988    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 989    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 990    *
 991    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 992    *
 993    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 994    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 995    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 996    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 997    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 998    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 999    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 1000    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 1001    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 1002    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 1003    * POSSIBILITY OF SUCH DAMAGE.
 1004    *
 1005    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 1006    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/STAXEventReader.html0000644000175000017500000054626610242117677022345 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 679   Methods: 24
NCLOC: 270   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
STAXEventReader.java 32,7% 47,6% 41,7% 43,1%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.io.InputStream;
 11    import java.io.Reader;
 12    import java.util.Iterator;
 13   
 14    import javax.xml.namespace.QName;
 15    import javax.xml.stream.XMLEventReader;
 16    import javax.xml.stream.XMLInputFactory;
 17    import javax.xml.stream.XMLStreamConstants;
 18    import javax.xml.stream.XMLStreamException;
 19    import javax.xml.stream.events.Attribute;
 20    import javax.xml.stream.events.Characters;
 21    import javax.xml.stream.events.Comment;
 22    import javax.xml.stream.events.EndElement;
 23    import javax.xml.stream.events.EntityReference;
 24    import javax.xml.stream.events.Namespace;
 25    import javax.xml.stream.events.ProcessingInstruction;
 26    import javax.xml.stream.events.StartDocument;
 27    import javax.xml.stream.events.StartElement;
 28    import javax.xml.stream.events.XMLEvent;
 29   
 30    import org.dom4j.CharacterData;
 31    import org.dom4j.Document;
 32    import org.dom4j.DocumentFactory;
 33    import org.dom4j.Element;
 34    import org.dom4j.Entity;
 35    import org.dom4j.Node;
 36   
 37    /**
 38    * Reads a DOM4J {@link Document}, as well as other {@link Node}s, from a StAX
 39    * {@link XMLEventReader}.
 40    *
 41    * @author Christian Niles
 42    */
 43    public class STAXEventReader {
 44    /** Reference to the DocumentFactory used to build DOM4J nodes. */
 45    private DocumentFactory factory;
 46   
 47    /** A StAX input factory, used to construct streams from IO streams. */
 48    private XMLInputFactory inputFactory = XMLInputFactory.newInstance();
 49   
 50    /**
 51    * Constructs a default <code>STAXEventReader</code> instance with a
 52    * default {@link DocumentFactory}.
 53    */
 54  1 public STAXEventReader() {
 55  1 this.factory = DocumentFactory.getInstance();
 56    }
 57   
 58    /**
 59    * Constructs a <code>STAXEventReader</code> instance that uses the
 60    * specified {@link DocumentFactory}to construct DOM4J {@link Node}s.
 61    *
 62    * @param factory
 63    * The DocumentFactory to use when constructing DOM4J nodes, or
 64    * <code>null</code> if a default should be used.
 65    */
 66  0 public STAXEventReader(DocumentFactory factory) {
 67  0 if (factory != null) {
 68  0 this.factory = factory;
 69    } else {
 70  0 this.factory = DocumentFactory.getInstance();
 71    }
 72    }
 73   
 74    /**
 75    * Sets the DocumentFactory to be used when constructing DOM4J nodes.
 76    *
 77    * @param documentFactory
 78    * The DocumentFactory to use when constructing DOM4J nodes, or
 79    * <code>null</code> if a default should be used.
 80    */
 81  0 public void setDocumentFactory(DocumentFactory documentFactory) {
 82  0 if (documentFactory != null) {
 83  0 this.factory = documentFactory;
 84    } else {
 85  0 this.factory = DocumentFactory.getInstance();
 86    }
 87    }
 88   
 89    /**
 90    * Constructs a StAX event stream from the provided I/O stream and reads a
 91    * DOM4J document from it.
 92    *
 93    * @param is
 94    * The I/O stream from which the Document will be read.
 95    *
 96    * @return The Document that was read from the stream.
 97    *
 98    * @throws XMLStreamException
 99    * If an error occurs reading content from the stream.
 100    */
 101  0 public Document readDocument(InputStream is) throws XMLStreamException {
 102  0 return readDocument(is, null);
 103    }
 104   
 105    /**
 106    * Constructs a StAX event stream from the provided I/O character stream and
 107    * reads a DOM4J document from it.
 108    *
 109    * @param reader
 110    * The character stream from which the Document will be read.
 111    *
 112    * @return The Document that was read from the stream.
 113    *
 114    * @throws XMLStreamException
 115    * If an error occurs reading content from the stream.
 116    */
 117  1 public Document readDocument(Reader reader) throws XMLStreamException {
 118  1 return readDocument(reader, null);
 119    }
 120   
 121    /**
 122    * Constructs a StAX event stream from the provided I/O stream and reads a
 123    * DOM4J document from it.
 124    *
 125    * @param is
 126    * The I/O stream from which the Document will be read.
 127    * @param systemId
 128    * A system id used to resolve entities.
 129    *
 130    * @return The Document that was read from the stream.
 131    *
 132    * @throws XMLStreamException
 133    * If an error occurs reading content from the stream.
 134    */
 135  0 public Document readDocument(InputStream is, String systemId)
 136    throws XMLStreamException {
 137  0 XMLEventReader eventReader = inputFactory.createXMLEventReader(
 138    systemId, is);
 139   
 140  0 try {
 141  0 return readDocument(eventReader);
 142    } finally {
 143  0 eventReader.close();
 144    }
 145    }
 146   
 147    /**
 148    * Constructs a StAX event stream from the provided I/O character stream and
 149    * reads a DOM4J document from it.
 150    *
 151    * @param reader
 152    * The character stream from which the Document will be read.
 153    * @param systemId
 154    * A system id used to resolve entities.
 155    *
 156    * @return The Document that was read from the stream.
 157    *
 158    * @throws XMLStreamException
 159    * If an error occurs reading content from the stream.
 160    */
 161  1 public Document readDocument(Reader reader, String systemId)
 162    throws XMLStreamException {
 163  1 XMLEventReader eventReader = inputFactory.createXMLEventReader(
 164    systemId, reader);
 165   
 166  1 try {
 167  1 return readDocument(eventReader);
 168    } finally {
 169  1 eventReader.close();
 170    }
 171    }
 172   
 173    /**
 174    * Reads a {@link Node}from the event stream. If the next event is a
 175    * {@link StartElement}, all events until the closing {@link EndElement}
 176    * will be read, and the resulting nodes will be added to the returned
 177    * {@link Element}.
 178    *
 179    * <p>
 180    * <strong>Pre-Conditions </strong>: The stream must be positioned before an
 181    * event other than an <code>EndElement</code>,<code>EndDocument</code>,
 182    * or any DTD-related events, which are not currently supported.
 183    * </p>
 184    *
 185    * @param reader
 186    * The reader from which events will be read.
 187    *
 188    * @return A DOM4J {@link Node}constructed from the read events.
 189    *
 190    * @throws XMLStreamException
 191    * If an error occurs reading from the stream, or the stream was
 192    * positioned before an unsupported event.
 193    */
 194  24 public Node readNode(XMLEventReader reader) throws XMLStreamException {
 195  24 XMLEvent event = reader.peek();
 196   
 197  24 if (event.isStartElement()) {
 198  8 return readElement(reader);
 199  16 } else if (event.isCharacters()) {
 200  16 return readCharacters(reader);
 201  0 } else if (event.isStartDocument()) {
 202  0 return readDocument(reader);
 203  0 } else if (event.isProcessingInstruction()) {
 204  0 return readProcessingInstruction(reader);
 205  0 } else if (event.isEntityReference()) {
 206  0 return readEntityReference(reader);
 207  0 } else if (event.isAttribute()) {
 208  0 return readAttribute(reader);
 209  0 } else if (event.isNamespace()) {
 210  0 return readNamespace(reader);
 211    } else {
 212  0 throw new XMLStreamException("Unsupported event: " + event);
 213    }
 214    }
 215   
 216    /**
 217    * Reads a DOM4J {@link Document}from the provided stream. The stream
 218    * should be positioned at the start of a document, or before a {@link
 219    * StartElement} event.
 220    *
 221    * @param reader
 222    * The event stream from which to read the {@link Document}.
 223    *
 224    * @return The {@link Document}that was read from the stream.
 225    *
 226    * @throws XMLStreamException
 227    * If an error occurs reading events from the stream.
 228    */
 229  1 public Document readDocument(XMLEventReader reader)
 230    throws XMLStreamException {
 231  1 Document doc = null;
 232   
 233  1 while (reader.hasNext()) {
 234  5 XMLEvent nextEvent = reader.peek();
 235  5 int type = nextEvent.getEventType();
 236   
 237  5 switch (type) {
 238  1 case XMLStreamConstants.START_DOCUMENT:
 239   
 240  1 StartDocument event = (StartDocument) reader.nextEvent();
 241   
 242  1 if (doc == null) {
 243    // create document
 244  1 if (event.encodingSet()) {
 245  1 String encodingScheme = event
 246    .getCharacterEncodingScheme();
 247  1 doc = factory.createDocument(encodingScheme);
 248    } else {
 249  0 doc = factory.createDocument();
 250    }
 251    } else {
 252    // duplicate or misplaced xml declaration
 253  0 String msg = "Unexpected StartDocument event";
 254  0 throw new XMLStreamException(msg, event.getLocation());
 255    }
 256   
 257  1 break;
 258   
 259  1 case XMLStreamConstants.END_DOCUMENT:
 260  0 case XMLStreamConstants.SPACE:
 261  2 case XMLStreamConstants.CHARACTERS:
 262   
 263    // skip end document and space outside the root element
 264  3 reader.nextEvent();
 265   
 266  3 break;
 267   
 268  1 default:
 269   
 270  1 if (doc == null) {
 271    // create document
 272  0 doc = factory.createDocument();
 273    }
 274   
 275  1 Node n = readNode(reader);
 276  1 doc.add(n);
 277    }
 278    }
 279   
 280  1 return doc;
 281    }
 282   
 283    /**
 284    * Reads a DOM4J Element from the provided event stream. The stream must be
 285    * positioned before an {@link StartElement}event. In addition to the
 286    * initial start event, all events up to and including the closing {@link
 287    * EndElement} will be read, and included with the returned element.
 288    *
 289    * @param eventReader
 290    * The event stream from which to read the Element.
 291    *
 292    * @return The Element that was read from the stream.
 293    *
 294    * @throws XMLStreamException
 295    * If an error occured reading events from the stream, or the
 296    * stream was not positioned before a {@linkStartElement}event.
 297    */
 298  8 public Element readElement(XMLEventReader eventReader)
 299    throws XMLStreamException {
 300  8 XMLEvent event = eventReader.peek();
 301   
 302  8 if (event.isStartElement()) {
 303    // advance the reader and get the StartElement event
 304  8 StartElement startTag = eventReader.nextEvent().asStartElement();
 305  8 Element elem = createElement(startTag);
 306   
 307    // read element content
 308  8 while (true) {
 309  31 if (!eventReader.hasNext()) {
 310  0 String msg = "Unexpected end of stream while reading"
 311    + " element content";
 312  0 throw new XMLStreamException(msg);
 313    }
 314   
 315  31 XMLEvent nextEvent = eventReader.peek();
 316   
 317  31 if (nextEvent.isEndElement()) {
 318  8 EndElement endElem = eventReader.nextEvent().asEndElement();
 319   
 320  8 if (!endElem.getName().equals(startTag.getName())) {
 321  0 throw new XMLStreamException("Expected "
 322    + startTag.getName() + " end-tag, but found"
 323    + endElem.getName());
 324    }
 325   
 326  8 break;
 327    }
 328   
 329  23 Node child = readNode(eventReader);
 330  23 elem.add(child);
 331    }
 332   
 333  8 return elem;
 334    } else {
 335  0 throw new XMLStreamException("Expected Element event, found: "
 336    + event);
 337    }
 338    }
 339   
 340    /**
 341    * Constructs a DOM4J Attribute from the provided event stream. The stream
 342    * must be positioned before an {@link Attribute}event.
 343    *
 344    * @param reader
 345    * The event stream from which to read the Attribute.
 346    *
 347    * @return The Attribute that was read from the stream.
 348    *
 349    * @throws XMLStreamException
 350    * If an error occured reading events from the stream, or the
 351    * stream was not positioned before an {@linkAttribute}event.
 352    */
 353  0 public org.dom4j.Attribute readAttribute(XMLEventReader reader)
 354    throws XMLStreamException {
 355  0 XMLEvent event = reader.peek();
 356   
 357  0 if (event.isAttribute()) {
 358  0 Attribute attr = (Attribute) reader.nextEvent();
 359   
 360  0 return createAttribute(null, attr);
 361    } else {
 362  0 throw new XMLStreamException("Expected Attribute event, found: "
 363    + event);
 364    }
 365    }
 366   
 367    /**
 368    * Constructs a DOM4J Namespace from the provided event stream. The stream
 369    * must be positioned before a {@link Namespace}event.
 370    *
 371    * @param reader
 372    * The event stream from which to read the Namespace.
 373    *
 374    * @return The Namespace that was read from the stream.
 375    *
 376    * @throws XMLStreamException
 377    * If an error occured reading events from the stream, or the
 378    * stream was not positioned before a {@linkNamespace}event.
 379    */
 380  0 public org.dom4j.Namespace readNamespace(XMLEventReader reader)
 381    throws XMLStreamException {
 382  0 XMLEvent event = reader.peek();
 383   
 384  0 if (event.isNamespace()) {
 385  0 Namespace ns = (Namespace) reader.nextEvent();
 386   
 387  0 return createNamespace(ns);
 388    } else {
 389  0 throw new XMLStreamException("Expected Namespace event, found: "
 390    + event);
 391    }
 392    }
 393   
 394    /**
 395    * Constructs a DOM4J Text or CDATA section from the provided event stream.
 396    * The stream must be positioned before a {@link Characters}event.
 397    *
 398    * @param reader
 399    * The event stream from which to read the Text or CDATA.
 400    *
 401    * @return The Text or CDATA that was read from the stream.
 402    *
 403    * @throws XMLStreamException
 404    * If an error occured reading events from the stream, or the
 405    * stream was not positioned before a {@linkCharacters}event.
 406    */
 407  16 public CharacterData readCharacters(XMLEventReader reader)
 408    throws XMLStreamException {
 409  16 XMLEvent event = reader.peek();
 410   
 411  16 if (event.isCharacters()) {
 412  16 Characters characters = reader.nextEvent().asCharacters();
 413   
 414  16 return createCharacterData(characters);
 415    } else {
 416  0 throw new XMLStreamException("Expected Characters event, found: "
 417    + event);
 418    }
 419    }
 420   
 421    /**
 422    * Constructs a DOM4J Comment from the provided event stream. The stream
 423    * must be positioned before a {@link Comment}event.
 424    *
 425    * @param reader
 426    * The event stream from which to read the Comment.
 427    *
 428    * @return The Comment that was read from the stream.
 429    *
 430    * @throws XMLStreamException
 431    * If an error occured reading events from the stream, or the
 432    * stream was not positioned before a {@linkComment}event.
 433    */
 434  0 public org.dom4j.Comment readComment(XMLEventReader reader)
 435    throws XMLStreamException {
 436  0 XMLEvent event = reader.peek();
 437   
 438  0 if (event instanceof Comment) {
 439  0 return createComment((Comment) reader.nextEvent());
 440    } else {
 441  0 throw new XMLStreamException("Expected Comment event, found: "
 442    + event);
 443    }
 444    }
 445   
 446    /**
 447    * Constructs a DOM4J Entity from the provided event stream. The stream must
 448    * be positioned before an {@link EntityReference}event.
 449    *
 450    * @param reader
 451    * The event stream from which to read the {@link
 452    * EntityReference}.
 453    *
 454    * @return The {@link org.dom4j.Entity}that was read from the stream.
 455    *
 456    * @throws XMLStreamException
 457    * If an error occured reading events from the stream, or the
 458    * stream was not positioned before an {@linkEntityReference}
 459    * event.
 460    */
 461  0 public Entity readEntityReference(XMLEventReader reader)
 462    throws XMLStreamException {
 463  0 XMLEvent event = reader.peek();
 464   
 465  0 if (event.isEntityReference()) {
 466  0 EntityReference entityRef = (EntityReference) reader.nextEvent();
 467   
 468  0 return createEntity(entityRef);
 469    } else {
 470  0 throw new XMLStreamException("Expected EntityRef event, found: "
 471    + event);
 472    }
 473    }
 474   
 475    /**
 476    * Constructs a DOM4J ProcessingInstruction from the provided event stream.
 477    * The stream must be positioned before a {@link ProcessingInstruction}
 478    * event.
 479    *
 480    * @param reader
 481    * The event stream from which to read the ProcessingInstruction.
 482    *
 483    * @return The ProcessingInstruction that was read from the stream.
 484    *
 485    * @throws XMLStreamException
 486    * If an error occured reading events from the stream, or the
 487    * stream was not positioned before a {@link
 488    * ProcessingInstruction} event.
 489    */
 490  0 public org.dom4j.ProcessingInstruction readProcessingInstruction(
 491    XMLEventReader reader) throws XMLStreamException {
 492  0 XMLEvent event = reader.peek();
 493   
 494  0 if (event.isProcessingInstruction()) {
 495  0 ProcessingInstruction pi = (ProcessingInstruction) reader
 496    .nextEvent();
 497   
 498  0 return createProcessingInstruction(pi);
 499    } else {
 500  0 throw new XMLStreamException("Expected PI event, found: " + event);
 501    }
 502    }
 503   
 504    /**
 505    * Constructs a new DOM4J Element from the provided StartElement event. All
 506    * attributes and namespaces will be added to the returned element.
 507    *
 508    * @param startEvent
 509    * The StartElement event from which to construct the new DOM4J
 510    * Element.
 511    *
 512    * @return The Element constructed from the provided StartElement event.
 513    */
 514  8 public Element createElement(StartElement startEvent) {
 515  8 QName qname = startEvent.getName();
 516  8 org.dom4j.QName elemName = createQName(qname);
 517   
 518  8 Element elem = factory.createElement(elemName);
 519   
 520    // create attributes
 521  8 for (Iterator i = startEvent.getAttributes(); i.hasNext();) {
 522  0 Attribute attr = (Attribute) i.next();
 523  0 elem.addAttribute(createQName(attr.getName()), attr.getValue());
 524    }
 525   
 526    // create namespaces
 527  8 for (Iterator i = startEvent.getNamespaces(); i.hasNext();) {
 528  0 Namespace ns = (Namespace) i.next();
 529  0 elem.addNamespace(ns.getPrefix(), ns.getNamespaceURI());
 530    }
 531   
 532  8 return elem;
 533    }
 534   
 535    /**
 536    * Constructs a new DOM4J Attribute from the provided StAX Attribute event.
 537    *
 538    * @param elem
 539    * DOCUMENT ME!
 540    * @param attr
 541    * The Attribute event from which to construct the new DOM4J
 542    * Attribute.
 543    *
 544    * @return The Attribute constructed from the provided Attribute event.
 545    */
 546  0 public org.dom4j.Attribute createAttribute(Element elem, Attribute attr) {
 547  0 return factory.createAttribute(elem, createQName(attr.getName()), attr
 548    .getValue());
 549    }
 550   
 551    /**
 552    * Constructs a new DOM4J Namespace from the provided StAX Namespace event.
 553    *
 554    * @param ns
 555    * The Namespace event from which to construct the new DOM4J
 556    * Namespace.
 557    *
 558    * @return The Namespace constructed from the provided Namespace event.
 559    */
 560  0 public org.dom4j.Namespace createNamespace(Namespace ns) {
 561  0 return factory.createNamespace(ns.getPrefix(), ns.getNamespaceURI());
 562    }
 563   
 564    /**
 565    * Constructs a new DOM4J Text or CDATA object from the provided Characters
 566    * event.
 567    *
 568    * @param characters
 569    * The Characters event from which to construct the new DOM4J
 570    * Text or CDATA object.
 571    *
 572    * @return The Text or CDATA object constructed from the provided Characters
 573    * event.
 574    */
 575  16 public CharacterData createCharacterData(Characters characters) {
 576  16 String data = characters.getData();
 577   
 578  16 if (characters.isCData()) {
 579  0 return factory.createCDATA(data);
 580    } else {
 581  16 return factory.createText(data);
 582    }
 583    }
 584   
 585    /**
 586    * Constructs a new DOM4J Comment from the provided StAX Comment event.
 587    *
 588    * @param comment
 589    * The Comment event from which to construct the new DOM4J
 590    * Comment.
 591    *
 592    * @return The Comment constructed from the provided Comment event.
 593    */
 594  0 public org.dom4j.Comment createComment(Comment comment) {
 595  0 return factory.createComment(comment.getText());
 596    }
 597   
 598    /**
 599    * Constructs a new DOM4J Entity from the provided StAX EntityReference
 600    * event.
 601    *
 602    * @param entityRef
 603    * The EntityReference event from which to construct the new
 604    * DOM4J Entity.
 605    *
 606    * @return The Entity constructed from the provided EntityReference event.
 607    */
 608  0 public org.dom4j.Entity createEntity(EntityReference entityRef) {
 609  0 return factory.createEntity(entityRef.getName(), entityRef
 610    .getDeclaration().getReplacementText());
 611    }
 612   
 613    /**
 614    * Constructs a new DOM4J ProcessingInstruction from the provided StAX
 615    * ProcessingInstruction event.
 616    *
 617    * @param pi
 618    * The ProcessingInstruction event from which to construct the
 619    * new DOM4J ProcessingInstruction.
 620    *
 621    * @return The ProcessingInstruction constructed from the provided
 622    * ProcessingInstruction event.
 623    */
 624  0 public org.dom4j.ProcessingInstruction createProcessingInstruction(
 625    ProcessingInstruction pi) {
 626  0 return factory
 627    .createProcessingInstruction(pi.getTarget(), pi.getData());
 628    }
 629   
 630    /**
 631    * Constructs a new DOM4J QName from the provided JAXP QName.
 632    *
 633    * @param qname
 634    * The JAXP QName from which to create a DOM4J QName.
 635    *
 636    * @return The newly constructed DOM4J QName.
 637    */
 638  8 public org.dom4j.QName createQName(QName qname) {
 639  8 return factory.createQName(qname.getLocalPart(), qname.getPrefix(),
 640    qname.getNamespaceURI());
 641    }
 642    }
 643   
 644    /*
 645    * Redistribution and use of this software and associated documentation
 646    * ("Software"), with or without modification, are permitted provided that the
 647    * following conditions are met:
 648    *
 649    * 1. Redistributions of source code must retain copyright statements and
 650    * notices. Redistributions must also contain a copy of this document.
 651    *
 652    * 2. Redistributions in binary form must reproduce the above copyright notice,
 653    * this list of conditions and the following disclaimer in the documentation
 654    * and/or other materials provided with the distribution.
 655    *
 656    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 657    * from this Software without prior written permission of MetaStuff, Ltd. For
 658    * written permission, please contact dom4j-info@metastuff.com.
 659    *
 660    * 4. Products derived from this Software may not be called "DOM4J" nor may
 661    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 662    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 663    *
 664    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 665    *
 666    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 667    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 668    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 669    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 670    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 671    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 672    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 673    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 674    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 675    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 676    * POSSIBILITY OF SUCH DAMAGE.
 677    *
 678    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 679    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/XPPReader.html0000644000175000017500000037243110242117710021206 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 484   Methods: 22
NCLOC: 164   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
XPPReader.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.io.BufferedReader;
 11    import java.io.File;
 12    import java.io.FileReader;
 13    import java.io.IOException;
 14    import java.io.InputStream;
 15    import java.io.InputStreamReader;
 16    import java.io.Reader;
 17    import java.net.URL;
 18   
 19    import org.dom4j.Document;
 20    import org.dom4j.DocumentException;
 21    import org.dom4j.DocumentFactory;
 22    import org.dom4j.Element;
 23    import org.dom4j.ElementHandler;
 24    import org.dom4j.xpp.ProxyXmlStartTag;
 25   
 26    import org.gjt.xpp.XmlEndTag;
 27    import org.gjt.xpp.XmlPullParser;
 28    import org.gjt.xpp.XmlPullParserException;
 29    import org.gjt.xpp.XmlPullParserFactory;
 30   
 31    /**
 32    * <p>
 33    * <code>XPPReader</code> is a Reader of DOM4J documents that uses the fast <a
 34    * href="http://www.extreme.indiana.edu/soap/xpp/">XML Pull Parser 2.x </a>. It
 35    * does not currently support comments, CDATA or ProcessingInstructions or
 36    * validation but it is very fast for use in SOAP style environments.
 37    * </p>
 38    *
 39    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 40    * @version $Revision: 1.7 $
 41    */
 42    public class XPPReader {
 43    /** <code>DocumentFactory</code> used to create new document objects */
 44    private DocumentFactory factory;
 45   
 46    /** <code>XmlPullParser</code> used to parse XML */
 47    private XmlPullParser xppParser;
 48   
 49    /** <code>XmlPullParser</code> used to parse XML */
 50    private XmlPullParserFactory xppFactory;
 51   
 52    /** DispatchHandler to call when each <code>Element</code> is encountered */
 53    private DispatchHandler dispatchHandler;
 54   
 55  0 public XPPReader() {
 56    }
 57   
 58  0 public XPPReader(DocumentFactory factory) {
 59  0 this.factory = factory;
 60    }
 61   
 62    /**
 63    * <p>
 64    * Reads a Document from the given <code>File</code>
 65    * </p>
 66    *
 67    * @param file
 68    * is the <code>File</code> to read from.
 69    *
 70    * @return the newly created Document instance
 71    *
 72    * @throws DocumentException
 73    * if an error occurs during parsing.
 74    * @throws IOException
 75    * if a URL could not be made for the given File
 76    * @throws XmlPullParserException
 77    * DOCUMENT ME!
 78    */
 79  0 public Document read(File file) throws DocumentException, IOException,
 80    XmlPullParserException {
 81  0 String systemID = file.getAbsolutePath();
 82   
 83  0 return read(new BufferedReader(new FileReader(file)), systemID);
 84    }
 85   
 86    /**
 87    * <p>
 88    * Reads a Document from the given <code>URL</code>
 89    * </p>
 90    *
 91    * @param url
 92    * <code>URL</code> to read from.
 93    *
 94    * @return the newly created Document instance
 95    *
 96    * @throws DocumentException
 97    * if an error occurs during parsing.
 98    * @throws IOException
 99    * DOCUMENT ME!
 100    * @throws XmlPullParserException
 101    * DOCUMENT ME!
 102    */
 103  0 public Document read(URL url) throws DocumentException, IOException,
 104    XmlPullParserException {
 105  0 String systemID = url.toExternalForm();
 106   
 107  0 return read(createReader(url.openStream()), systemID);
 108    }
 109   
 110    /**
 111    * <p>
 112    * Reads a Document from the given URL or filename.
 113    * </p>
 114    *
 115    * <p>
 116    * If the systemID contains a <code>':'</code> character then it is
 117    * assumed to be a URL otherwise its assumed to be a file name. If you want
 118    * finer grained control over this mechansim then please explicitly pass in
 119    * either a {@link URL}or a {@link File}instance instead of a {@link
 120    * String} to denote the source of the document.
 121    * </p>
 122    *
 123    * @param systemID
 124    * is a URL for a document or a file name.
 125    *
 126    * @return the newly created Document instance
 127    *
 128    * @throws DocumentException
 129    * if an error occurs during parsing.
 130    * @throws IOException
 131    * if a URL could not be made for the given File
 132    * @throws XmlPullParserException
 133    * DOCUMENT ME!
 134    */
 135  0 public Document read(String systemID) throws DocumentException,
 136    IOException, XmlPullParserException {
 137  0 if (systemID.indexOf(':') >= 0) {
 138    // lets assume its a URL
 139  0 return read(new URL(systemID));
 140    } else {
 141    // lets assume that we are given a file name
 142  0 return read(new File(systemID));
 143    }
 144    }
 145   
 146    /**
 147    * <p>
 148    * Reads a Document from the given stream
 149    * </p>
 150    *
 151    * @param in
 152    * <code>InputStream</code> to read from.
 153    *
 154    * @return the newly created Document instance
 155    *
 156    * @throws DocumentException
 157    * if an error occurs during parsing.
 158    * @throws IOException
 159    * DOCUMENT ME!
 160    * @throws XmlPullParserException
 161    * DOCUMENT ME!
 162    */
 163  0 public Document read(InputStream in) throws DocumentException, IOException,
 164    XmlPullParserException {
 165  0 return read(createReader(in));
 166    }
 167   
 168    /**
 169    * <p>
 170    * Reads a Document from the given <code>Reader</code>
 171    * </p>
 172    *
 173    * @param reader
 174    * is the reader for the input
 175    *
 176    * @return the newly created Document instance
 177    *
 178    * @throws DocumentException
 179    * if an error occurs during parsing.
 180    * @throws IOException
 181    * DOCUMENT ME!
 182    * @throws XmlPullParserException
 183    * DOCUMENT ME!
 184    */
 185  0 public Document read(Reader reader) throws DocumentException, IOException,
 186    XmlPullParserException {
 187  0 getXPPParser().setInput(reader);
 188   
 189  0 return parseDocument();
 190    }
 191   
 192    /**
 193    * <p>
 194    * Reads a Document from the given array of characters
 195    * </p>
 196    *
 197    * @param text
 198    * is the text to parse
 199    *
 200    * @return the newly created Document instance
 201    *
 202    * @throws DocumentException
 203    * if an error occurs during parsing.
 204    * @throws IOException
 205    * DOCUMENT ME!
 206    * @throws XmlPullParserException
 207    * DOCUMENT ME!
 208    */
 209  0 public Document read(char[] text) throws DocumentException, IOException,
 210    XmlPullParserException {
 211  0 getXPPParser().setInput(text);
 212   
 213  0 return parseDocument();
 214    }
 215   
 216    /**
 217    * <p>
 218    * Reads a Document from the given stream
 219    * </p>
 220    *
 221    * @param in
 222    * <code>InputStream</code> to read from.
 223    * @param systemID
 224    * is the URI for the input
 225    *
 226    * @return the newly created Document instance
 227    *
 228    * @throws DocumentException
 229    * if an error occurs during parsing.
 230    * @throws IOException
 231    * DOCUMENT ME!
 232    * @throws XmlPullParserException
 233    * DOCUMENT ME!
 234    */
 235  0 public Document read(InputStream in, String systemID)
 236    throws DocumentException, IOException, XmlPullParserException {
 237  0 return read(createReader(in), systemID);
 238    }
 239   
 240    /**
 241    * <p>
 242    * Reads a Document from the given <code>Reader</code>
 243    * </p>
 244    *
 245    * @param reader
 246    * is the reader for the input
 247    * @param systemID
 248    * is the URI for the input
 249    *
 250    * @return the newly created Document instance
 251    *
 252    * @throws DocumentException
 253    * if an error occurs during parsing.
 254    * @throws IOException
 255    * DOCUMENT ME!
 256    * @throws XmlPullParserException
 257    * DOCUMENT ME!
 258    */
 259  0 public Document read(Reader reader, String systemID)
 260    throws DocumentException, IOException, XmlPullParserException {
 261  0 Document document = read(reader);
 262  0 document.setName(systemID);
 263   
 264  0 return document;
 265    }
 266   
 267    // Properties
 268    // -------------------------------------------------------------------------
 269  0 public XmlPullParser getXPPParser() throws XmlPullParserException {
 270  0 if (xppParser == null) {
 271  0 xppParser = getXPPFactory().newPullParser();
 272    }
 273   
 274  0 return xppParser;
 275    }
 276   
 277  0 public XmlPullParserFactory getXPPFactory() throws XmlPullParserException {
 278  0 if (xppFactory == null) {
 279  0 xppFactory = XmlPullParserFactory.newInstance();
 280    }
 281   
 282  0 return xppFactory;
 283    }
 284   
 285  0 public void setXPPFactory(XmlPullParserFactory xPPFactory) {
 286  0 this.xppFactory = xPPFactory;
 287    }
 288   
 289    /**
 290    * DOCUMENT ME!
 291    *
 292    * @return the <code>DocumentFactory</code> used to create document
 293    * objects
 294    */
 295  0 public DocumentFactory getDocumentFactory() {
 296  0 if (factory == null) {
 297  0 factory = DocumentFactory.getInstance();
 298    }
 299   
 300  0 return factory;
 301    }
 302   
 303    /**
 304    * <p>
 305    * This sets the <code>DocumentFactory</code> used to create new
 306    * documents. This method allows the building of custom DOM4J tree objects
 307    * to be implemented easily using a custom derivation of
 308    * {@link DocumentFactory}
 309    * </p>
 310    *
 311    * @param documentFactory
 312    * <code>DocumentFactory</code> used to create DOM4J objects
 313    */
 314  0 public void setDocumentFactory(DocumentFactory documentFactory) {
 315  0 this.factory = documentFactory;
 316    }
 317   
 318    /**
 319    * Adds the <code>ElementHandler</code> to be called when the specified
 320    * path is encounted.
 321    *
 322    * @param path
 323    * is the path to be handled
 324    * @param handler
 325    * is the <code>ElementHandler</code> to be called by the event
 326    * based processor.
 327    */
 328  0 public void addHandler(String path, ElementHandler handler) {
 329  0 getDispatchHandler().addHandler(path, handler);
 330    }
 331   
 332    /**
 333    * Removes the <code>ElementHandler</code> from the event based processor,
 334    * for the specified path.
 335    *
 336    * @param path
 337    * is the path to remove the <code>ElementHandler</code> for.
 338    */
 339  0 public void removeHandler(String path) {
 340  0 getDispatchHandler().removeHandler(path);
 341    }
 342   
 343    /**
 344    * When multiple <code>ElementHandler</code> instances have been
 345    * registered, this will set a default <code>ElementHandler</code> to be
 346    * called for any path which does <b>NOT </b> have a handler registered.
 347    *
 348    * @param handler
 349    * is the <code>ElementHandler</code> to be called by the event
 350    * based processor.
 351    */
 352  0 public void setDefaultHandler(ElementHandler handler) {
 353  0 getDispatchHandler().setDefaultHandler(handler);
 354    }
 355   
 356    // Implementation methods
 357    // -------------------------------------------------------------------------
 358  0 protected Document parseDocument() throws DocumentException, IOException,
 359    XmlPullParserException {
 360  0 Document document = getDocumentFactory().createDocument();
 361  0 Element parent = null;
 362  0 XmlPullParser parser = getXPPParser();
 363  0 parser.setNamespaceAware(true);
 364   
 365  0 ProxyXmlStartTag startTag = new ProxyXmlStartTag();
 366  0 XmlEndTag endTag = xppFactory.newEndTag();
 367   
 368  0 while (true) {
 369  0 int type = parser.next();
 370   
 371  0 switch (type) {
 372  0 case XmlPullParser.END_DOCUMENT:
 373  0 return document;
 374   
 375  0 case XmlPullParser.START_TAG: {
 376  0 parser.readStartTag(startTag);
 377   
 378  0 Element newElement = startTag.getElement();
 379   
 380  0 if (parent != null) {
 381  0 parent.add(newElement);
 382    } else {
 383  0 document.add(newElement);
 384    }
 385   
 386  0 parent = newElement;
 387   
 388  0 break;
 389    }
 390   
 391  0 case XmlPullParser.END_TAG: {
 392  0 parser.readEndTag(endTag);
 393   
 394  0 if (parent != null) {
 395  0 parent = parent.getParent();
 396    }
 397   
 398  0 break;
 399    }
 400   
 401  0 case XmlPullParser.CONTENT: {
 402  0 String text = parser.readContent();
 403   
 404  0 if (parent != null) {
 405  0 parent.addText(text);
 406    } else {
 407  0 String msg = "Cannot have text content outside of the "
 408    + "root document";
 409  0 throw new DocumentException(msg);
 410    }
 411   
 412  0 break;
 413    }
 414   
 415  0 default:
 416  0 throw new DocumentException("Error: unknown type: " + type);
 417    }
 418    }
 419    }
 420   
 421  0 protected DispatchHandler getDispatchHandler() {
 422  0 if (dispatchHandler == null) {
 423  0 dispatchHandler = new DispatchHandler();
 424    }
 425   
 426  0 return dispatchHandler;
 427    }
 428   
 429  0 protected void setDispatchHandler(DispatchHandler dispatchHandler) {
 430  0 this.dispatchHandler = dispatchHandler;
 431    }
 432   
 433    /**
 434    * Factory method to create a Reader from the given InputStream.
 435    *
 436    * @param in
 437    * DOCUMENT ME!
 438    *
 439    * @return DOCUMENT ME!
 440    *
 441    * @throws IOException
 442    * DOCUMENT ME!
 443    */
 444  0 protected Reader createReader(InputStream in) throws IOException {
 445  0 return new BufferedReader(new InputStreamReader(in));
 446    }
 447    }
 448   
 449    /*
 450    * Redistribution and use of this software and associated documentation
 451    * ("Software"), with or without modification, are permitted provided that the
 452    * following conditions are met:
 453    *
 454    * 1. Redistributions of source code must retain copyright statements and
 455    * notices. Redistributions must also contain a copy of this document.
 456    *
 457    * 2. Redistributions in binary form must reproduce the above copyright notice,
 458    * this list of conditions and the following disclaimer in the documentation
 459    * and/or other materials provided with the distribution.
 460    *
 461    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 462    * from this Software without prior written permission of MetaStuff, Ltd. For
 463    * written permission, please contact dom4j-info@metastuff.com.
 464    *
 465    * 4. Products derived from this Software may not be called "DOM4J" nor may
 466    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 467    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 468    *
 469    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 470    *
 471    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 472    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 473    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 474    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 475    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 476    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 477    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 478    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 479    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 480    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 481    * POSSIBILITY OF SUCH DAMAGE.
 482    *
 483    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 484    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/pkg-summary.html0000644000175000017500000007344410242117615021676 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
package stats: LOC: 12.958   Methods: 643
NCLOC: 5.575   Classes: 35
Files: 30  
 
 Package Conditionals Statements Methods TOTAL
org.dom4j.io 46,3% 47,8% 44,3% 46,9%
coverage coverage
 
 Classes Conditionals Statements Methods TOTAL
HTMLWriter.FormatState - 0% 0% 0%
coverage
PruningDispatchHandler 0% 0% 0% 0%
coverage
PruningElementStack 0% 0% 0% 0%
coverage
SAXEventRecorder 0% 0% 0% 0%
coverage
SAXEventRecorder.SAXEvent 0% 0% 0% 0%
coverage
SAXModifier 0% 0% 0% 0%
coverage
SAXModifyContentHandler 0% 0% 0% 0%
coverage
SAXModifyElementHandler 0% 0% 0% 0%
coverage
SAXModifyException - 0% 0% 0%
coverage
SAXModifyReader - 0% 0% 0%
coverage
SAXValidator 0% 0% 0% 0%
coverage
XPPReader 0% 0% 0% 0%
coverage
DocumentSource 0% 14,3% 42,9% 16,7%
coverage coverage
DocumentInputSource - 21,4% 25% 22,7%
coverage coverage
ElementStack 28,6% 32,5% 47,1% 35,2%
coverage coverage
STAXEventWriter 75% 34,8% 35,3% 36,2%
coverage coverage
STAXEventWriter.AttributeIterator - 28,6% 50% 36,4%
coverage coverage
STAXEventWriter.NamespaceIterator - 28,6% 50% 36,4%
coverage coverage
HTMLWriter 29,5% 38,8% 42,9% 37,3%
coverage coverage
DocumentResult 0% 45,5% 60% 40%
coverage coverage
SAXHelper 21,4% 43,2% 66,7% 40,4%
coverage coverage
XMLResult - 42,9% 40% 41,7%
coverage coverage
STAXEventReader 32,7% 47,6% 41,7% 43,1%
coverage coverage
XPP3Reader 34,4% 53,1% 36,4% 46,7%
coverage coverage
OutputFormat 17,6% 55% 77,1% 51,7%
coverage coverage
SAXReader 50% 61,4% 57,1% 58,4%
coverage coverage
XMLWriter 59,5% 64,3% 57% 62,3%
coverage coverage
DispatchHandler 83,3% 64,1% 36,4% 62,9%
coverage coverage
SAXWriter 65,5% 62,2% 66,7% 63,6%
coverage coverage
DOMWriter 69,2% 65,6% 71,4% 67,2%
coverage coverage
SAXContentHandler 64,4% 79,2% 72,7% 73,8%
coverage coverage
DOMReader 82,4% 77,5% 72,7% 78,2%
coverage coverage
SAXReader.SAXEntityResolver 75% 100% 100% 90,9%
coverage coverage
JAXPHelper - 100% 66,7% 92,3%
coverage coverage
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/STAXEventWriter.html0000644000175000017500000054074110242117745022403 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 685   Methods: 42
NCLOC: 242   Classes: 3
 
 Source file Conditionals Statements Methods TOTAL
STAXEventWriter.java 75% 34% 38,1% 36,2%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.io.File;
 11    import java.io.FileWriter;
 12    import java.io.IOException;
 13    import java.io.OutputStream;
 14    import java.io.StringWriter;
 15    import java.io.Writer;
 16    import java.util.Iterator;
 17   
 18    import javax.xml.namespace.QName;
 19    import javax.xml.stream.XMLEventFactory;
 20    import javax.xml.stream.XMLOutputFactory;
 21    import javax.xml.stream.XMLStreamException;
 22    import javax.xml.stream.events.Characters;
 23    import javax.xml.stream.events.DTD;
 24    import javax.xml.stream.events.EndDocument;
 25    import javax.xml.stream.events.EndElement;
 26    import javax.xml.stream.events.EntityReference;
 27    import javax.xml.stream.events.ProcessingInstruction;
 28    import javax.xml.stream.events.StartDocument;
 29    import javax.xml.stream.events.StartElement;
 30    import javax.xml.stream.util.XMLEventConsumer;
 31   
 32    import org.dom4j.Attribute;
 33    import org.dom4j.Branch;
 34    import org.dom4j.CDATA;
 35    import org.dom4j.Comment;
 36    import org.dom4j.Document;
 37    import org.dom4j.DocumentType;
 38    import org.dom4j.Element;
 39    import org.dom4j.Entity;
 40    import org.dom4j.Namespace;
 41    import org.dom4j.Node;
 42    import org.dom4j.Text;
 43   
 44    /**
 45    * Writes DOM4J {@link Node}s to a StAX event stream. In addition the
 46    * <code>createXXX</code> methods are provided to directly create STAX events
 47    * from DOM4J nodes.
 48    *
 49    * @author Christian Niles
 50    */
 51    public class STAXEventWriter {
 52    /** The event stream to which events are written. */
 53    private XMLEventConsumer consumer;
 54   
 55    /** The event factory used to construct events. */
 56    private XMLEventFactory factory = XMLEventFactory.newInstance();
 57   
 58    private XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
 59   
 60  0 public STAXEventWriter() {
 61    }
 62   
 63    /**
 64    * Constructs a <code>STAXEventWriter</code> that writes events to the
 65    * provided file.
 66    *
 67    * @param file
 68    * The file to which events will be written.
 69    *
 70    * @throws XMLStreamException
 71    * If an error occurs creating an event writer from the file.
 72    * @throws IOException
 73    * If an error occurs openin the file for writing.
 74    */
 75  0 public STAXEventWriter(File file) throws XMLStreamException, IOException {
 76  0 consumer = outputFactory.createXMLEventWriter(new FileWriter(file));
 77    }
 78   
 79    /**
 80    * Constructs a <code>STAXEventWriter</code> that writes events to the
 81    * provided character stream.
 82    *
 83    * @param writer
 84    * The character stream to which events will be written.
 85    *
 86    * @throws XMLStreamException
 87    * If an error occurs constructing an event writer from the
 88    * character stream.
 89    */
 90  1 public STAXEventWriter(Writer writer) throws XMLStreamException {
 91  1 consumer = outputFactory.createXMLEventWriter(writer);
 92    }
 93   
 94    /**
 95    * Constructs a <code>STAXEventWriter</code> that writes events to the
 96    * provided stream.
 97    *
 98    * @param stream
 99    * The output stream to which events will be written.
 100    *
 101    * @throws XMLStreamException
 102    * If an error occurs constructing an event writer from the
 103    * stream.
 104    */
 105  0 public STAXEventWriter(OutputStream stream) throws XMLStreamException {
 106  0 consumer = outputFactory.createXMLEventWriter(stream);
 107    }
 108   
 109    /**
 110    * Constructs a <code>STAXEventWriter</code> that writes events to the
 111    * provided event stream.
 112    *
 113    * @param consumer
 114    * The event stream to which events will be written.
 115    */
 116  0 public STAXEventWriter(XMLEventConsumer consumer) {
 117  0 this.consumer = consumer;
 118    }
 119   
 120    /**
 121    * Returns a reference to the underlying event consumer to which events are
 122    * written.
 123    *
 124    * @return The underlying event consumer to which events are written.
 125    */
 126  0 public XMLEventConsumer getConsumer() {
 127  0 return consumer;
 128    }
 129   
 130    /**
 131    * Sets the underlying event consumer to which events are written.
 132    *
 133    * @param consumer
 134    * The event consumer to which events should be written.
 135    */
 136  0 public void setConsumer(XMLEventConsumer consumer) {
 137  0 this.consumer = consumer;
 138    }
 139   
 140    /**
 141    * Returns a reference to the event factory used to construct STAX events.
 142    *
 143    * @return The event factory used to construct STAX events.
 144    */
 145  0 public XMLEventFactory getEventFactory() {
 146  0 return factory;
 147    }
 148   
 149    /**
 150    * Sets the event factory used to construct STAX events.
 151    *
 152    * @param eventFactory
 153    * The new event factory.
 154    */
 155  0 public void setEventFactory(XMLEventFactory eventFactory) {
 156  0 this.factory = eventFactory;
 157    }
 158   
 159    /**
 160    * Writes a DOM4J {@link Node}to the stream. This method is simply a
 161    * gateway to the overloaded methods such as {@link#writeElement(Element)}.
 162    *
 163    * @param n
 164    * The DOM4J {@link Node}to write to the stream.
 165    *
 166    * @throws XMLStreamException
 167    * If an error occurs writing to the stream.
 168    */
 169  24 public void writeNode(Node n) throws XMLStreamException {
 170  24 switch (n.getNodeType()) {
 171  8 case Node.ELEMENT_NODE:
 172  8 writeElement((Element) n);
 173   
 174  8 break;
 175   
 176  16 case Node.TEXT_NODE:
 177  16 writeText((Text) n);
 178   
 179  16 break;
 180   
 181  0 case Node.ATTRIBUTE_NODE:
 182  0 writeAttribute((Attribute) n);
 183   
 184  0 break;
 185   
 186  0 case Node.NAMESPACE_NODE:
 187  0 writeNamespace((Namespace) n);
 188   
 189  0 break;
 190   
 191  0 case Node.COMMENT_NODE:
 192  0 writeComment((Comment) n);
 193   
 194  0 break;
 195   
 196  0 case Node.CDATA_SECTION_NODE:
 197  0 writeCDATA((CDATA) n);
 198   
 199  0 break;
 200   
 201  0 case Node.PROCESSING_INSTRUCTION_NODE:
 202  0 writeProcessingInstruction((org.dom4j.ProcessingInstruction) n);
 203   
 204  0 break;
 205   
 206  0 case Node.ENTITY_REFERENCE_NODE:
 207  0 writeEntity((Entity) n);
 208   
 209  0 break;
 210   
 211  0 case Node.DOCUMENT_NODE:
 212  0 writeDocument((Document) n);
 213   
 214  0 break;
 215   
 216  0 case Node.DOCUMENT_TYPE_NODE:
 217  0 writeDocumentType((DocumentType) n);
 218   
 219  0 break;
 220   
 221  0 default:
 222  0 throw new XMLStreamException("Unsupported DOM4J Node: " + n);
 223    }
 224    }
 225   
 226    /**
 227    * Writes each child node within the provided {@link Branch}instance. This
 228    * method simply iterates through the {@link Branch}'s nodes and calls
 229    * {@link #writeNode(Node)}.
 230    *
 231    * @param branch
 232    * The node whose children will be written to the stream.
 233    *
 234    * @throws XMLStreamException
 235    * If an error occurs writing to the stream.
 236    */
 237  9 public void writeChildNodes(Branch branch) throws XMLStreamException {
 238  9 for (int i = 0, s = branch.nodeCount(); i < s; i++) {
 239  24 Node n = branch.node(i);
 240  24 writeNode(n);
 241    }
 242    }
 243   
 244    /**
 245    * Writes a DOM4J {@link Element}node and its children to the stream.
 246    *
 247    * @param elem
 248    * The {@link Element}node to write to the stream.
 249    *
 250    * @throws XMLStreamException
 251    * If an error occurs writing to the stream.
 252    */
 253  8 public void writeElement(Element elem) throws XMLStreamException {
 254  8 consumer.add(createStartElement(elem));
 255  8 writeChildNodes(elem);
 256  8 consumer.add(createEndElement(elem));
 257    }
 258   
 259    /**
 260    * Constructs a STAX {@link StartElement}event from a DOM4J {@link
 261    * Element}.
 262    *
 263    * @param elem
 264    * The {@link Element}from which to construct the event.
 265    *
 266    * @return The newly constructed {@link StartElement}event.
 267    */
 268  8 public StartElement createStartElement(Element elem) {
 269    // create name
 270  8 QName tagName = createQName(elem.getQName());
 271   
 272    // create attribute & namespace iterators
 273  8 Iterator attrIter = new AttributeIterator(elem.attributeIterator());
 274  8 Iterator nsIter = new NamespaceIterator(elem.declaredNamespaces()
 275    .iterator());
 276   
 277    // create start event
 278  8 return factory.createStartElement(tagName, attrIter, nsIter);
 279    }
 280   
 281    /**
 282    * Constructs a STAX {@link EndElement}event from a DOM4J {@link Element}.
 283    *
 284    * @param elem
 285    * The {@link Element}from which to construct the event.
 286    *
 287    * @return The newly constructed {@link EndElement}event.
 288    */
 289  8 public EndElement createEndElement(Element elem) {
 290  8 QName tagName = createQName(elem.getQName());
 291  8 Iterator nsIter = new NamespaceIterator(elem.declaredNamespaces()
 292    .iterator());
 293   
 294  8 return factory.createEndElement(tagName, nsIter);
 295    }
 296   
 297    /**
 298    * Writes a DOM4J {@link Attribute}to the stream.
 299    *
 300    * @param attr
 301    * The {@link Attribute}to write to the stream.
 302    *
 303    * @throws XMLStreamException
 304    * If an error occurs writing to the stream.
 305    */
 306  0 public void writeAttribute(Attribute attr) throws XMLStreamException {
 307  0 consumer.add(createAttribute(attr));
 308    }
 309   
 310    /**
 311    * Constructs a STAX {@link javax.xml.stream.events.Attribute}event from a
 312    * DOM4J {@link Attribute}.
 313    *
 314    * @param attr
 315    * The {@link Attribute}from which to construct the event.
 316    *
 317    * @return The newly constructed {@link javax.xml.stream.events.Attribute}
 318    * event.
 319    */
 320  0 public javax.xml.stream.events.Attribute createAttribute(Attribute attr) {
 321  0 QName attrName = createQName(attr.getQName());
 322  0 String value = attr.getValue();
 323   
 324  0 return factory.createAttribute(attrName, value);
 325    }
 326   
 327    /**
 328    * Writes a DOM4J {@link Namespace}to the stream.
 329    *
 330    * @param ns
 331    * The {@link Namespace}to write to the stream.
 332    *
 333    * @throws XMLStreamException
 334    * If an error occurs writing to the stream.
 335    */
 336  0 public void writeNamespace(Namespace ns) throws XMLStreamException {
 337  0 consumer.add(createNamespace(ns));
 338    }
 339   
 340    /**
 341    * Constructs a STAX {@link javax.xml.stream.events.Namespace}event from a
 342    * DOM4J {@link Namespace}.
 343    *
 344    * @param ns
 345    * The {@link Namespace}from which to construct the event.
 346    *
 347    * @return The constructed {@link javax.xml.stream.events.Namespace}event.
 348    */
 349  0 public javax.xml.stream.events.Namespace createNamespace(Namespace ns) {
 350  0 String prefix = ns.getPrefix();
 351  0 String uri = ns.getURI();
 352   
 353  0 return factory.createNamespace(prefix, uri);
 354    }
 355   
 356    /**
 357    * Writes a DOM4J {@link Text}to the stream.
 358    *
 359    * @param text
 360    * The {@link Text}to write to the stream.
 361    *
 362    * @throws XMLStreamException
 363    * If an error occurs writing to the stream.
 364    */
 365  16 public void writeText(Text text) throws XMLStreamException {
 366  16 consumer.add(createCharacters(text));
 367    }
 368   
 369    /**
 370    * Constructs a STAX {@link Characters}event from a DOM4J {@link Text}.
 371    *
 372    * @param text
 373    * The {@link Text}from which to construct the event.
 374    *
 375    * @return The constructed {@link Characters}event.
 376    */
 377  16 public Characters createCharacters(Text text) {
 378  16 return factory.createCharacters(text.getText());
 379    }
 380   
 381    /**
 382    * Writes a DOM4J {@link CDATA}to the event stream.
 383    *
 384    * @param cdata
 385    * The {@link CDATA}to write to the stream.
 386    *
 387    * @throws XMLStreamException
 388    * If an error occurs writing to the stream.
 389    */
 390  0 public void writeCDATA(CDATA cdata) throws XMLStreamException {
 391  0 consumer.add(createCharacters(cdata));
 392    }
 393   
 394    /**
 395    * Constructs a STAX {@link Characters}event from a DOM4J {@link CDATA}.
 396    *
 397    * @param cdata
 398    * The {@link CDATA}from which to construct the event.
 399    *
 400    * @return The newly constructed {@link Characters}event.
 401    */
 402  0 public Characters createCharacters(CDATA cdata) {
 403  0 return factory.createCData(cdata.getText());
 404    }
 405   
 406    /**
 407    * Writes a DOM4J {@link Comment}to the stream.
 408    *
 409    * @param comment
 410    * The {@link Comment}to write to the stream.
 411    *
 412    * @throws XMLStreamException
 413    * If an error occurs writing to the stream.
 414    */
 415  0 public void writeComment(Comment comment) throws XMLStreamException {
 416  0 consumer.add(createComment(comment));
 417    }
 418   
 419    /**
 420    * Constructs a STAX {@link javax.xml.stream.events.Comment}event from a
 421    * DOM4J {@link Comment}.
 422    *
 423    * @param comment
 424    * The {@link Comment}from which to construct the event.
 425    *
 426    * @return The constructed {@link javax.xml.stream.events.Comment}event.
 427    */
 428  0 public javax.xml.stream.events.Comment createComment(Comment comment) {
 429  0 return factory.createComment(comment.getText());
 430    }
 431   
 432    /**
 433    * Writes a DOM4J {@link ProcessingInstruction}to the stream.
 434    *
 435    * @param pi
 436    * The {@link ProcessingInstruction}to write to the stream.
 437    *
 438    * @throws XMLStreamException
 439    * If an error occurs writing to the stream.
 440    */
 441  0 public void writeProcessingInstruction(org.dom4j.ProcessingInstruction pi)
 442    throws XMLStreamException {
 443  0 consumer.add(createProcessingInstruction(pi));
 444    }
 445   
 446    /**
 447    * Constructs a STAX {@link javax.xml.stream.events.ProcessingInstruction}
 448    * event from a DOM4J {@link ProcessingInstruction}.
 449    *
 450    * @param pi
 451    * The {@link ProcessingInstruction}from which to construct the
 452    * event.
 453    *
 454    * @return The constructed {@link
 455    * javax.xml.stream.events.ProcessingInstruction} event.
 456    */
 457  0 public ProcessingInstruction createProcessingInstruction(
 458    org.dom4j.ProcessingInstruction pi) {
 459  0 String target = pi.getTarget();
 460  0 String data = pi.getText();
 461   
 462  0 return factory.createProcessingInstruction(target, data);
 463    }
 464   
 465    /**
 466    * Writes a DOM4J {@link Entity}to the stream.
 467    *
 468    * @param entity
 469    * The {@link Entity}to write to the stream.
 470    *
 471    * @throws XMLStreamException
 472    * If an error occurs writing to the stream.
 473    */
 474  0 public void writeEntity(Entity entity) throws XMLStreamException {
 475  0 consumer.add(createEntityReference(entity));
 476    }
 477   
 478    /**
 479    * Constructs a STAX {@link EntityReference}event from a DOM4J {@link
 480    * Entity}.
 481    *
 482    * @param entity
 483    * The {@link Entity}from which to construct the event.
 484    *
 485    * @return The constructed {@link EntityReference}event.
 486    */
 487  0 private EntityReference createEntityReference(Entity entity) {
 488  0 return factory.createEntityReference(entity.getName(), null);
 489    }
 490   
 491    /**
 492    * Writes a DOM4J {@link DocumentType}to the stream.
 493    *
 494    * @param docType
 495    * The {@link DocumentType}to write to the stream.
 496    *
 497    * @throws XMLStreamException
 498    * If an error occurs writing to the stream.
 499    */
 500  0 public void writeDocumentType(DocumentType docType)
 501    throws XMLStreamException {
 502  0 consumer.add(createDTD(docType));
 503    }
 504   
 505    /**
 506    * Constructs a STAX {@link DTD}event from a DOM4J {@link DocumentType}.
 507    *
 508    * @param docType
 509    * The {@link DocumentType}from which to construct the event.
 510    *
 511    * @return The constructed {@link DTD}event.
 512    *
 513    * @throws RuntimeException
 514    * DOCUMENT ME!
 515    */
 516  0 public DTD createDTD(DocumentType docType) {
 517  0 StringWriter decl = new StringWriter();
 518   
 519  0 try {
 520  0 docType.write(decl);
 521    } catch (IOException e) {
 522  0 throw new RuntimeException("Error writing DTD", e);
 523    }
 524   
 525  0 return factory.createDTD(decl.toString());
 526    }
 527   
 528    /**
 529    * Writes a DOM4J {@link Document}node, and all its contents, to the
 530    * stream.
 531    *
 532    * @param doc
 533    * The {@link Document}to write to the stream.
 534    *
 535    * @throws XMLStreamException
 536    * If an error occurs writing to the stream.
 537    */
 538  1 public void writeDocument(Document doc) throws XMLStreamException {
 539  1 consumer.add(createStartDocument(doc));
 540   
 541  1 writeChildNodes(doc);
 542   
 543  1 consumer.add(createEndDocument(doc));
 544    }
 545   
 546    /**
 547    * Constructs a STAX {@link StartDocument}event from a DOM4J {@link
 548    * Document}.
 549    *
 550    * @param doc
 551    * The {@link Document}from which to construct the event.
 552    *
 553    * @return The constructed {@link StartDocument}event.
 554    */
 555  1 public StartDocument createStartDocument(Document doc) {
 556  1 String encoding = doc.getXMLEncoding();
 557   
 558  1 if (encoding != null) {
 559  1 return factory.createStartDocument(encoding);
 560    } else {
 561  0 return factory.createStartDocument();
 562    }
 563    }
 564   
 565    /**
 566    * Constructs a STAX {@link EndDocument}event from a DOM4J {@link
 567    * Document}.
 568    *
 569    * @param doc
 570    * The {@link Document}from which to construct the event.
 571    *
 572    * @return The constructed {@link EndDocument}event.
 573    */
 574  1 public EndDocument createEndDocument(Document doc) {
 575  1 return factory.createEndDocument();
 576    }
 577   
 578    /**
 579    * Constructs a STAX {@link QName}from a DOM4J {@link org.dom4j.QName}.
 580    *
 581    * @param qname
 582    * The {@link org.dom4j.QName}from which to construct the STAX
 583    * {@link QName}.
 584    *
 585    * @return The constructed {@link QName}.
 586    */
 587  16 public QName createQName(org.dom4j.QName qname) {
 588  16 return new QName(qname.getNamespaceURI(), qname.getName(), qname
 589    .getNamespacePrefix());
 590    }
 591   
 592    /**
 593    * Internal {@link Iterator}implementation used to pass DOM4J {@link
 594    * Attribute}s to the stream.
 595    */
 596    private class AttributeIterator implements Iterator {
 597    /** The underlying DOm4J attribute iterator. */
 598    private Iterator iter;
 599   
 600  8 public AttributeIterator(Iterator iter) {
 601  8 this.iter = iter;
 602    }
 603   
 604  8 public boolean hasNext() {
 605  8 return iter.hasNext();
 606    }
 607   
 608  0 public Object next() {
 609  0 Attribute attr = (Attribute) iter.next();
 610  0 QName attrName = createQName(attr.getQName());
 611  0 String value = attr.getValue();
 612   
 613  0 return factory.createAttribute(attrName, value);
 614    }
 615   
 616  0 public void remove() {
 617  0 throw new UnsupportedOperationException();
 618    }
 619    }
 620   
 621    /**
 622    * Internal {@link Iterator}implementation used to pass DOM4J {@link
 623    * Namespace}s to the stream.
 624    */
 625    private class NamespaceIterator implements Iterator {
 626    private Iterator iter;
 627   
 628  16 public NamespaceIterator(Iterator iter) {
 629  16 this.iter = iter;
 630    }
 631   
 632  16 public boolean hasNext() {
 633  16 return iter.hasNext();
 634    }
 635   
 636  0 public Object next() {
 637  0 Namespace ns = (Namespace) iter.next();
 638  0 String prefix = ns.getPrefix();
 639  0 String nsURI = ns.getURI();
 640   
 641  0 return factory.createNamespace(prefix, nsURI);
 642    }
 643   
 644  0 public void remove() {
 645  0 throw new UnsupportedOperationException();
 646    }
 647    }
 648    }
 649   
 650    /*
 651    * Redistribution and use of this software and associated documentation
 652    * ("Software"), with or without modification, are permitted provided that the
 653    * following conditions are met:
 654    *
 655    * 1. Redistributions of source code must retain copyright statements and
 656    * notices. Redistributions must also contain a copy of this document.
 657    *
 658    * 2. Redistributions in binary form must reproduce the above copyright notice,
 659    * this list of conditions and the following disclaimer in the documentation
 660    * and/or other materials provided with the distribution.
 661    *
 662    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 663    * from this Software without prior written permission of MetaStuff, Ltd. For
 664    * written permission, please contact dom4j-info@metastuff.com.
 665    *
 666    * 4. Products derived from this Software may not be called "DOM4J" nor may
 667    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 668    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 669    *
 670    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 671    *
 672    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 673    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 674    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 675    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 676    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 677    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 678    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 679    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 680    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 681    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 682    * POSSIBILITY OF SUCH DAMAGE.
 683    *
 684    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 685    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/SAXHelper.html0000644000175000017500000015411610242117706021212 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 195   Methods: 6
NCLOC: 86   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
SAXHelper.java 21,4% 43,2% 66,7% 40,4%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import org.xml.sax.SAXException;
 11    import org.xml.sax.SAXNotRecognizedException;
 12    import org.xml.sax.SAXNotSupportedException;
 13    import org.xml.sax.XMLReader;
 14    import org.xml.sax.helpers.XMLReaderFactory;
 15   
 16    /**
 17    * <p>
 18    * <code>SAXHelper</code> contains some helper methods for working with SAX
 19    * and XMLReader objects.
 20    * </p>
 21    *
 22    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 23    * @version $Revision: 1.18 $
 24    */
 25    class SAXHelper {
 26    private static boolean loggedWarning = true;
 27   
 28  0 protected SAXHelper() {
 29    }
 30   
 31  11590 public static boolean setParserProperty(XMLReader reader,
 32    String propertyName, Object value) {
 33  11590 try {
 34  11590 reader.setProperty(propertyName, value);
 35   
 36  5798 return true;
 37    } catch (SAXNotSupportedException e) {
 38    // ignore
 39    } catch (SAXNotRecognizedException e) {
 40    // ignore
 41    }
 42   
 43  5792 return false;
 44    }
 45   
 46  23168 public static boolean setParserFeature(XMLReader reader,
 47    String featureName, boolean value) {
 48  23168 try {
 49  23168 reader.setFeature(featureName, value);
 50   
 51  17376 return true;
 52    } catch (SAXNotSupportedException e) {
 53    // ignore
 54    } catch (SAXNotRecognizedException e) {
 55    // ignore
 56    }
 57   
 58  5792 return false;
 59    }
 60   
 61    /**
 62    * Creats a default XMLReader via the org.xml.sax.driver system property or
 63    * JAXP if the system property is not set.
 64    *
 65    * @param validating
 66    * DOCUMENT ME!
 67    *
 68    * @return DOCUMENT ME!
 69    *
 70    * @throws SAXException
 71    * DOCUMENT ME!
 72    */
 73  5758 public static XMLReader createXMLReader(boolean validating)
 74    throws SAXException {
 75  5764 XMLReader reader = null;
 76   
 77  5764 if (reader == null) {
 78  5764 reader = createXMLReaderViaJAXP(validating, true);
 79    }
 80   
 81  5764 if (reader == null) {
 82  0 try {
 83  0 reader = XMLReaderFactory.createXMLReader();
 84    } catch (Exception e) {
 85  0 if (isVerboseErrorReporting()) {
 86    // log all exceptions as warnings and carry
 87    // on as we have a default SAX parser we can use
 88  0 System.out.println("Warning: Caught exception attempting "
 89    + "to use SAX to load a SAX XMLReader ");
 90  0 System.out.println("Warning: Exception was: " + e);
 91  0 System.out
 92    .println("Warning: I will print the stack trace "
 93    + "then carry on using the default "
 94    + "SAX parser");
 95  0 e.printStackTrace();
 96    }
 97   
 98  0 throw new SAXException(e);
 99    }
 100    }
 101   
 102  5764 if (reader == null) {
 103  0 throw new SAXException("Couldn't create SAX reader");
 104    }
 105   
 106  5764 return reader;
 107    }
 108   
 109    /**
 110    * This method attempts to use JAXP to locate the SAX2 XMLReader
 111    * implementation. This method uses reflection to avoid being dependent
 112    * directly on the JAXP classes.
 113    *
 114    * @param validating
 115    * DOCUMENT ME!
 116    * @param namespaceAware
 117    * DOCUMENT ME!
 118    *
 119    * @return DOCUMENT ME!
 120    */
 121  5764 protected static XMLReader createXMLReaderViaJAXP(boolean validating,
 122    boolean namespaceAware) {
 123    // try use JAXP to load the XMLReader...
 124  5764 try {
 125  5764 return JAXPHelper.createXMLReader(validating, namespaceAware);
 126    } catch (Throwable e) {
 127  0 if (!loggedWarning) {
 128  0 loggedWarning = true;
 129   
 130  0 if (isVerboseErrorReporting()) {
 131    // log all exceptions as warnings and carry
 132    // on as we have a default SAX parser we can use
 133  0 System.out.println("Warning: Caught exception attempting "
 134    + "to use JAXP to load a SAX XMLReader");
 135  0 System.out.println("Warning: Exception was: " + e);
 136  0 e.printStackTrace();
 137    }
 138    }
 139    }
 140   
 141  0 return null;
 142    }
 143   
 144  0 protected static boolean isVerboseErrorReporting() {
 145  0 try {
 146  0 String flag = System.getProperty("org.dom4j.verbose");
 147   
 148  0 if ((flag != null) && flag.equalsIgnoreCase("true")) {
 149  0 return true;
 150    }
 151    } catch (Exception e) {
 152    // in case a security exception
 153    // happens in an applet or similar JVM
 154    }
 155   
 156  0 return true;
 157    }
 158    }
 159   
 160    /*
 161    * Redistribution and use of this software and associated documentation
 162    * ("Software"), with or without modification, are permitted provided that the
 163    * following conditions are met:
 164    *
 165    * 1. Redistributions of source code must retain copyright statements and
 166    * notices. Redistributions must also contain a copy of this document.
 167    *
 168    * 2. Redistributions in binary form must reproduce the above copyright notice,
 169    * this list of conditions and the following disclaimer in the documentation
 170    * and/or other materials provided with the distribution.
 171    *
 172    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 173    * from this Software without prior written permission of MetaStuff, Ltd. For
 174    * written permission, please contact dom4j-info@metastuff.com.
 175    *
 176    * 4. Products derived from this Software may not be called "DOM4J" nor may
 177    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 178    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 179    *
 180    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 181    *
 182    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 183    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 184    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 185    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 186    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 187    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 188    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 189    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 190    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 191    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 192    * POSSIBILITY OF SUCH DAMAGE.
 193    *
 194    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 195    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/DocumentInputSource.html0000644000175000017500000012050610242117543023371 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 148   Methods: 8
NCLOC: 45   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DocumentInputSource.java - 21,4% 25% 22,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.io.IOException;
 11    import java.io.Reader;
 12    import java.io.StringReader;
 13    import java.io.StringWriter;
 14   
 15    import org.dom4j.Document;
 16   
 17    import org.xml.sax.InputSource;
 18   
 19    /**
 20    * <p>
 21    * <code>DocumentInputSource</code> implements a SAX {@link InputSource}for a
 22    * {@link Document}.
 23    * </p>
 24    *
 25    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 26    * @version $Revision: 1.8 $
 27    */
 28    class DocumentInputSource extends InputSource {
 29    /** The document source */
 30    private Document document;
 31   
 32  0 public DocumentInputSource() {
 33    }
 34   
 35  8 public DocumentInputSource(Document document) {
 36  8 this.document = document;
 37  8 setSystemId(document.getName());
 38    }
 39   
 40    // Properties
 41    // -------------------------------------------------------------------------
 42   
 43    /**
 44    * DOCUMENT ME!
 45    *
 46    * @return the document which is being used as the SAX {@link InputSource}
 47    */
 48  8 public Document getDocument() {
 49  8 return document;
 50    }
 51   
 52    /**
 53    * Sets the document used as the SAX {@link InputSource}
 54    *
 55    * @param document
 56    * DOCUMENT ME!
 57    */
 58  0 public void setDocument(Document document) {
 59  0 this.document = document;
 60  0 setSystemId(document.getName());
 61    }
 62   
 63    // Overloaded methods
 64    // -------------------------------------------------------------------------
 65   
 66    /**
 67    * This method is not supported as this source is always a {@linkDocument}
 68    * instance.
 69    *
 70    * @param characterStream
 71    * DOCUMENT ME!
 72    *
 73    * @throws UnsupportedOperationException
 74    * as this method is unsupported
 75    */
 76  0 public void setCharacterStream(Reader characterStream)
 77    throws UnsupportedOperationException {
 78  0 throw new UnsupportedOperationException();
 79    }
 80   
 81    /**
 82    * Note this method is quite inefficent, it turns the in memory XML tree
 83    * object model into a single block of text which can then be read by other
 84    * XML parsers. Should only be used with care.
 85    *
 86    * @return DOCUMENT ME!
 87    */
 88  0 public Reader getCharacterStream() {
 89  0 try {
 90  0 StringWriter out = new StringWriter();
 91  0 XMLWriter writer = new XMLWriter(out);
 92  0 writer.write(document);
 93  0 writer.flush();
 94   
 95  0 return new StringReader(out.toString());
 96    } catch (final IOException e) {
 97    // this should never really happen
 98    // but for completeness we'll return a Reader
 99    // with the embedded exception inside it
 100  0 return new Reader() {
 101  0 public int read(char[] ch, int offset, int length)
 102    throws IOException {
 103  0 throw e;
 104    }
 105   
 106  0 public void close() throws IOException {
 107    }
 108    };
 109    }
 110    }
 111    }
 112   
 113    /*
 114    * Redistribution and use of this software and associated documentation
 115    * ("Software"), with or without modification, are permitted provided that the
 116    * following conditions are met:
 117    *
 118    * 1. Redistributions of source code must retain copyright statements and
 119    * notices. Redistributions must also contain a copy of this document.
 120    *
 121    * 2. Redistributions in binary form must reproduce the above copyright notice,
 122    * this list of conditions and the following disclaimer in the documentation
 123    * and/or other materials provided with the distribution.
 124    *
 125    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 126    * from this Software without prior written permission of MetaStuff, Ltd. For
 127    * written permission, please contact dom4j-info@metastuff.com.
 128    *
 129    * 4. Products derived from this Software may not be called "DOM4J" nor may
 130    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 131    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 132    *
 133    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 134    *
 135    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 136    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 137    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 138    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 139    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 140    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 141    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 142    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 143    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 144    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 145    * POSSIBILITY OF SUCH DAMAGE.
 146    *
 147    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 148    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/DOMReader.html0000644000175000017500000025532710242117543021166 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 313   Methods: 11
NCLOC: 173   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DOMReader.java 82,4% 77,5% 72,7% 78,2%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.util.ArrayList;
 11    import java.util.List;
 12   
 13    import org.dom4j.Branch;
 14    import org.dom4j.Document;
 15    import org.dom4j.DocumentFactory;
 16    import org.dom4j.Element;
 17    import org.dom4j.Namespace;
 18    import org.dom4j.QName;
 19    import org.dom4j.tree.NamespaceStack;
 20   
 21    /**
 22    * <p>
 23    * <code>DOMReader</code> navigates a W3C DOM tree and creates a DOM4J tree
 24    * from it.
 25    * </p>
 26    *
 27    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 28    * @version $Revision: 1.17 $
 29    */
 30    public class DOMReader {
 31    /** <code>DocumentFactory</code> used to create new document objects */
 32    private DocumentFactory factory;
 33   
 34    /** stack of <code>Namespace</code> and <code>QName</code> objects */
 35    private NamespaceStack namespaceStack;
 36   
 37  20 public DOMReader() {
 38  20 this.factory = DocumentFactory.getInstance();
 39  20 this.namespaceStack = new NamespaceStack(factory);
 40    }
 41   
 42  0 public DOMReader(DocumentFactory factory) {
 43  0 this.factory = factory;
 44  0 this.namespaceStack = new NamespaceStack(factory);
 45    }
 46   
 47    /**
 48    * DOCUMENT ME!
 49    *
 50    * @return the <code>DocumentFactory</code> used to create document
 51    * objects
 52    */
 53  20 public DocumentFactory getDocumentFactory() {
 54  20 return factory;
 55    }
 56   
 57    /**
 58    * <p>
 59    * This sets the <code>DocumentFactory</code> used to create new
 60    * documents. This method allows the building of custom DOM4J tree objects
 61    * to be implemented easily using a custom derivation of
 62    * {@link DocumentFactory}
 63    * </p>
 64    *
 65    * @param docFactory
 66    * <code>DocumentFactory</code> used to create DOM4J objects
 67    */
 68  0 public void setDocumentFactory(DocumentFactory docFactory) {
 69  0 this.factory = docFactory;
 70  0 this.namespaceStack.setDocumentFactory(factory);
 71    }
 72   
 73  20 public Document read(org.w3c.dom.Document domDocument) {
 74  20 if (domDocument instanceof Document) {
 75  0 return (Document) domDocument;
 76    }
 77   
 78  20 Document document = createDocument();
 79   
 80  20 clearNamespaceStack();
 81   
 82  20 org.w3c.dom.NodeList nodeList = domDocument.getChildNodes();
 83   
 84  20 for (int i = 0, size = nodeList.getLength(); i < size; i++) {
 85  26 readTree(nodeList.item(i), document);
 86    }
 87   
 88  20 return document;
 89    }
 90   
 91    // Implementation methods
 92  14094 protected void readTree(org.w3c.dom.Node node, Branch current) {
 93  14094 Element element = null;
 94  14094 Document document = null;
 95   
 96  14094 if (current instanceof Element) {
 97  14068 element = (Element) current;
 98    } else {
 99  26 document = (Document) current;
 100    }
 101   
 102  14094 switch (node.getNodeType()) {
 103  5119 case org.w3c.dom.Node.ELEMENT_NODE:
 104  5119 readElement(node, current);
 105   
 106  5119 break;
 107   
 108  2 case org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE:
 109   
 110  2 if (current instanceof Element) {
 111  0 Element currentEl = (Element) current;
 112  0 currentEl.addProcessingInstruction(node.getNodeName(), node
 113    .getNodeValue());
 114    } else {
 115  2 Document currentDoc = (Document) current;
 116  2 currentDoc.addProcessingInstruction(node.getNodeName(),
 117    node.getNodeValue());
 118    }
 119   
 120  2 break;
 121   
 122  70 case org.w3c.dom.Node.COMMENT_NODE:
 123   
 124  70 if (current instanceof Element) {
 125  66 ((Element) current).addComment(node.getNodeValue());
 126    } else {
 127  4 ((Document) current).addComment(node.getNodeValue());
 128    }
 129   
 130  70 break;
 131   
 132  0 case org.w3c.dom.Node.DOCUMENT_TYPE_NODE:
 133   
 134  0 org.w3c.dom.DocumentType domDocType
 135    = (org.w3c.dom.DocumentType) node;
 136  0 document.addDocType(domDocType.getName(), domDocType
 137    .getPublicId(), domDocType.getSystemId());
 138   
 139  0 break;
 140   
 141  8873 case org.w3c.dom.Node.TEXT_NODE:
 142  8873 element.addText(node.getNodeValue());
 143   
 144  8873 break;
 145   
 146  30 case org.w3c.dom.Node.CDATA_SECTION_NODE:
 147  30 element.addCDATA(node.getNodeValue());
 148   
 149  30 break;
 150   
 151  0 case org.w3c.dom.Node.ENTITY_REFERENCE_NODE:
 152   
 153    // is there a better way to get the value of an entity?
 154  0 org.w3c.dom.Node firstChild = node.getFirstChild();
 155   
 156  0 if (firstChild != null) {
 157  0 element.addEntity(node.getNodeName(), firstChild
 158    .getNodeValue());
 159    } else {
 160  0 element.addEntity(node.getNodeName(), "");
 161    }
 162   
 163  0 break;
 164   
 165  0 case org.w3c.dom.Node.ENTITY_NODE:
 166  0 element.addEntity(node.getNodeName(), node.getNodeValue());
 167   
 168  0 break;
 169   
 170  0 default:
 171  0 System.out.println("WARNING: Unknown DOM node type: "
 172    + node.getNodeType());
 173    }
 174    }
 175   
 176  5119 protected void readElement(org.w3c.dom.Node node, Branch current) {
 177  5119 int previouslyDeclaredNamespaces = namespaceStack.size();
 178   
 179  5119 String namespaceUri = node.getNamespaceURI();
 180  5119 String elementPrefix = node.getPrefix();
 181   
 182  5119 if (elementPrefix == null) {
 183  4751 elementPrefix = "";
 184    }
 185   
 186  5119 org.w3c.dom.NamedNodeMap attributeList = node.getAttributes();
 187   
 188  5119 if ((attributeList != null) && (namespaceUri == null)) {
 189    // test if we have an "xmlns" attribute
 190  4686 org.w3c.dom.Node attribute = attributeList.getNamedItem("xmlns");
 191   
 192  4686 if (attribute != null) {
 193  2 namespaceUri = attribute.getNodeValue();
 194  2 elementPrefix = "";
 195    }
 196    }
 197   
 198  5119 QName qName = namespaceStack.getQName(namespaceUri,
 199    node.getLocalName(), node.getNodeName());
 200  5119 Element element = current.addElement(qName);
 201   
 202  5119 if (attributeList != null) {
 203  5119 int size = attributeList.getLength();
 204  5119 List attributes = new ArrayList(size);
 205   
 206  5119 for (int i = 0; i < size; i++) {
 207  2829 org.w3c.dom.Node attribute = attributeList.item(i);
 208   
 209    // Define all namespaces first then process attributes later
 210  2829 String name = attribute.getNodeName();
 211   
 212  2829 if (name.startsWith("xmlns")) {
 213  52 String prefix = getPrefix(name);
 214  52 String uri = attribute.getNodeValue();
 215   
 216  52 Namespace namespace = namespaceStack.addNamespace(prefix,
 217    uri);
 218  52 element.add(namespace);
 219    } else {
 220  2777 attributes.add(attribute);
 221    }
 222    }
 223   
 224    // now add the attributes, the namespaces should be available
 225  5119 size = attributes.size();
 226   
 227  5119 for (int i = 0; i < size; i++) {
 228  2777 org.w3c.dom.Node attribute = (org.w3c.dom.Node) attributes
 229    .get(i);
 230  2777 QName attributeQName = namespaceStack.getQName(attribute
 231    .getNamespaceURI(), attribute.getLocalName(), attribute
 232    .getNodeName());
 233  2777 element.addAttribute(attributeQName, attribute.getNodeValue());
 234    }
 235    }
 236   
 237    // Recurse on child nodes
 238  5119 org.w3c.dom.NodeList children = node.getChildNodes();
 239   
 240  5119 for (int i = 0, size = children.getLength(); i < size; i++) {
 241  14068 org.w3c.dom.Node child = children.item(i);
 242  14068 readTree(child, element);
 243    }
 244   
 245    // pop namespaces from the stack
 246  5119 while (namespaceStack.size() > previouslyDeclaredNamespaces) {
 247  52 namespaceStack.pop();
 248    }
 249    }
 250   
 251  0 protected Namespace getNamespace(String prefix, String uri) {
 252  0 return getDocumentFactory().createNamespace(prefix, uri);
 253    }
 254   
 255  20 protected Document createDocument() {
 256  20 return getDocumentFactory().createDocument();
 257    }
 258   
 259  20 protected void clearNamespaceStack() {
 260  20 namespaceStack.clear();
 261   
 262  20 if (!namespaceStack.contains(Namespace.XML_NAMESPACE)) {
 263  20 namespaceStack.push(Namespace.XML_NAMESPACE);
 264    }
 265    }
 266   
 267  52 private String getPrefix(String xmlnsDecl) {
 268  52 int index = xmlnsDecl.indexOf(':', 5);
 269   
 270  52 if (index != -1) {
 271  30 return xmlnsDecl.substring(index + 1);
 272    } else {
 273  22 return "";
 274    }
 275    }
 276    }
 277   
 278    /*
 279    * Redistribution and use of this software and associated documentation
 280    * ("Software"), with or without modification, are permitted provided that the
 281    * following conditions are met:
 282    *
 283    * 1. Redistributions of source code must retain copyright statements and
 284    * notices. Redistributions must also contain a copy of this document.
 285    *
 286    * 2. Redistributions in binary form must reproduce the above copyright notice,
 287    * this list of conditions and the following disclaimer in the documentation
 288    * and/or other materials provided with the distribution.
 289    *
 290    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 291    * from this Software without prior written permission of MetaStuff, Ltd. For
 292    * written permission, please contact dom4j-info@metastuff.com.
 293    *
 294    * 4. Products derived from this Software may not be called "DOM4J" nor may
 295    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 296    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 297    *
 298    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 299    *
 300    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 301    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 302    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 303    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 304    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 305    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 306    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 307    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 308    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 309    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 310    * POSSIBILITY OF SUCH DAMAGE.
 311    *
 312    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 313    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/DocumentSource.html0000644000175000017500000014240210242117651022350 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 184   Methods: 7
NCLOC: 56   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DocumentSource.java 0% 14,3% 42,9% 16,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import javax.xml.transform.sax.SAXSource;
 11   
 12    import org.dom4j.Document;
 13    import org.dom4j.Node;
 14   
 15    import org.xml.sax.InputSource;
 16    import org.xml.sax.XMLFilter;
 17    import org.xml.sax.XMLReader;
 18   
 19    /**
 20    * <p>
 21    * <code>DocumentSource</code> implements a JAXP {@link SAXSource}for a
 22    * {@linkDocument}.
 23    * </p>
 24    *
 25    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 26    * @version $Revision: 1.10 $
 27    */
 28    public class DocumentSource extends SAXSource {
 29    /**
 30    * If {@link javax.xml.transform.TransformerFactory#getFeature}returns
 31    * <code>true</code> when passed this value as an argument then the
 32    * Transformer natively supports <i>dom4j </i>.
 33    */
 34    public static final String DOM4J_FEATURE
 35    = "http://org.dom4j.io.DoucmentSource/feature";
 36   
 37    /** The XMLReader to use */
 38    private XMLReader xmlReader = new SAXWriter();
 39   
 40    /**
 41    * Creates a JAXP {@link SAXSource}for the given {@link Node}.
 42    *
 43    * @param node
 44    * DOCUMENT ME!
 45    */
 46  0 public DocumentSource(Node node) {
 47  0 setDocument(node.getDocument());
 48    }
 49   
 50    /**
 51    * Creates a JAXP {@link SAXSource}for the given {@link Document}.
 52    *
 53    * @param document
 54    * DOCUMENT ME!
 55    */
 56  8 public DocumentSource(Document document) {
 57  8 setDocument(document);
 58    }
 59   
 60    // Properties
 61    // -------------------------------------------------------------------------
 62   
 63    /**
 64    * DOCUMENT ME!
 65    *
 66    * @return the document which is being used as the JAXP {@link SAXSource}
 67    */
 68  0 public Document getDocument() {
 69  0 DocumentInputSource source = (DocumentInputSource) getInputSource();
 70  0 return source.getDocument();
 71    }
 72   
 73    /**
 74    * Sets the document used as the JAXP {@link SAXSource}
 75    *
 76    * @param document
 77    * DOCUMENT ME!
 78    */
 79  8 public void setDocument(Document document) {
 80  8 super.setInputSource(new DocumentInputSource(document));
 81    }
 82   
 83    // Overloaded methods
 84    // -------------------------------------------------------------------------
 85   
 86    /**
 87    * DOCUMENT ME!
 88    *
 89    * @return the XMLReader to be used for the JAXP {@link SAXSource}.
 90    */
 91  8 public XMLReader getXMLReader() {
 92  8 return xmlReader;
 93    }
 94   
 95    /**
 96    * This method is not supported as this source is always a {@linkDocument}
 97    * instance.
 98    *
 99    * @param inputSource
 100    * DOCUMENT ME!
 101    *
 102    * @throws UnsupportedOperationException
 103    * as this method is unsupported
 104    */
 105  0 public void setInputSource(InputSource inputSource)
 106    throws UnsupportedOperationException {
 107  0 if (inputSource instanceof DocumentInputSource) {
 108  0 super.setInputSource((DocumentInputSource) inputSource);
 109    } else {
 110  0 throw new UnsupportedOperationException();
 111    }
 112    }
 113   
 114    /**
 115    * Sets the XMLReader used for the JAXP {@link SAXSource}.
 116    *
 117    * @param reader
 118    * DOCUMENT ME!
 119    *
 120    * @throws UnsupportedOperationException
 121    * DOCUMENT ME!
 122    */
 123  0 public void setXMLReader(XMLReader reader)
 124    throws UnsupportedOperationException {
 125  0 if (reader instanceof SAXWriter) {
 126  0 this.xmlReader = (SAXWriter) reader;
 127  0 } else if (reader instanceof XMLFilter) {
 128  0 XMLFilter filter = (XMLFilter) reader;
 129   
 130  0 while (true) {
 131  0 XMLReader parent = filter.getParent();
 132   
 133  0 if (parent instanceof XMLFilter) {
 134  0 filter = (XMLFilter) parent;
 135    } else {
 136  0 break;
 137    }
 138    }
 139   
 140    // install filter in SAXWriter....
 141  0 filter.setParent(xmlReader);
 142  0 xmlReader = filter;
 143    } else {
 144  0 throw new UnsupportedOperationException();
 145    }
 146    }
 147    }
 148   
 149    /*
 150    * Redistribution and use of this software and associated documentation
 151    * ("Software"), with or without modification, are permitted provided that the
 152    * following conditions are met:
 153    *
 154    * 1. Redistributions of source code must retain copyright statements and
 155    * notices. Redistributions must also contain a copy of this document.
 156    *
 157    * 2. Redistributions in binary form must reproduce the above copyright notice,
 158    * this list of conditions and the following disclaimer in the documentation
 159    * and/or other materials provided with the distribution.
 160    *
 161    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 162    * from this Software without prior written permission of MetaStuff, Ltd. For
 163    * written permission, please contact dom4j-info@metastuff.com.
 164    *
 165    * 4. Products derived from this Software may not be called "DOM4J" nor may
 166    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 167    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 168    *
 169    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 170    *
 171    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 172    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 173    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 174    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 175    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 176    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 177    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 178    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 179    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 180    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 181    * POSSIBILITY OF SUCH DAMAGE.
 182    *
 183    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 184    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/SAXModifyException.html0000644000175000017500000004610210242117652023074 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 64   Methods: 1
NCLOC: 6   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
SAXModifyException.java - 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    /**
 11    * Exception internally thrown by the SAX Modification classes. This is a
 12    * RuntimeException since the {@link org.dom4j.ElementHandler}methods do not
 13    * throw Exceptions.
 14    *
 15    * @author Wonne Keysers (Realsoftware.be)
 16    */
 17    class SAXModifyException extends RuntimeException {
 18    /**
 19    * DOCUMENT ME!
 20    *
 21    * @param cause
 22    * The causing {@link java.lang.Throwable}
 23    */
 24  0 protected SAXModifyException(Throwable cause) {
 25  0 super(cause);
 26    }
 27    }
 28   
 29    /*
 30    * Redistribution and use of this software and associated documentation
 31    * ("Software"), with or without modification, are permitted provided that the
 32    * following conditions are met:
 33    *
 34    * 1. Redistributions of source code must retain copyright statements and
 35    * notices. Redistributions must also contain a copy of this document.
 36    *
 37    * 2. Redistributions in binary form must reproduce the above copyright notice,
 38    * this list of conditions and the following disclaimer in the documentation
 39    * and/or other materials provided with the distribution.
 40    *
 41    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 42    * from this Software without prior written permission of MetaStuff, Ltd. For
 43    * written permission, please contact dom4j-info@metastuff.com.
 44    *
 45    * 4. Products derived from this Software may not be called "DOM4J" nor may
 46    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 47    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 48    *
 49    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 50    *
 51    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 52    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 53    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 54    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 55    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 56    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 57    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 58    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 59    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 60    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 61    * POSSIBILITY OF SUCH DAMAGE.
 62    *
 63    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 64    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/SAXEventRecorder.html0000644000175000017500000051345310242117721022542 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 603   Methods: 29
NCLOC: 383   Classes: 2
 
 Source file Conditionals Statements Methods TOTAL
SAXEventRecorder.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.io.Externalizable;
 11    import java.io.IOException;
 12    import java.io.ObjectInput;
 13    import java.io.ObjectOutput;
 14    import java.util.ArrayList;
 15    import java.util.HashMap;
 16    import java.util.Iterator;
 17    import java.util.List;
 18    import java.util.Map;
 19   
 20    import org.dom4j.Namespace;
 21    import org.dom4j.QName;
 22    import org.xml.sax.Attributes;
 23    import org.xml.sax.ContentHandler;
 24    import org.xml.sax.DTDHandler;
 25    import org.xml.sax.SAXException;
 26    import org.xml.sax.ext.DeclHandler;
 27    import org.xml.sax.ext.LexicalHandler;
 28    import org.xml.sax.helpers.AttributesImpl;
 29    import org.xml.sax.helpers.DefaultHandler;
 30   
 31    /**
 32    * <p>
 33    * Records SAX events such that they may be "replayed" at a later time. Provides
 34    * an alternative serialization approach when externalizing a DOM4J document.
 35    * Rather than serializing a document as text and re-parsing, the sax events may
 36    * be serialized instead.
 37    * </p>
 38    * Example usage:
 39    *
 40    * <pre>
 41    *
 42    *
 43    *
 44    * SAXEventRecorder recorder = new SAXEventRecorder();
 45    * SAXWriter saxWriter = new SAXWriter(recorder, recorder);
 46    * saxWriter.write(document);
 47    * out.writeObject(recorder);
 48    * ...
 49    * SAXEventRecorder recorder = (SAXEventRecorder)in.readObject();
 50    * SAXContentHandler saxContentHandler = new SAXContentHandler();
 51    * recorder.replay(saxContentHandler);
 52    * Document document = saxContentHandler.getDocument();
 53    *
 54    *
 55    *
 56    * </pre>
 57    *
 58    * @author Todd Wolff (Bluestem Software)
 59    */
 60    public class SAXEventRecorder extends DefaultHandler implements LexicalHandler,
 61    DeclHandler, DTDHandler, Externalizable {
 62    public static final long serialVersionUID = 1;
 63   
 64    private static final byte STRING = 0;
 65   
 66    private static final byte OBJECT = 1;
 67   
 68    private static final byte NULL = 2;
 69   
 70    private List events = new ArrayList();
 71   
 72    private Map prefixMappings = new HashMap();
 73   
 74    private static final String XMLNS = "xmlns";
 75   
 76    private static final String EMPTY_STRING = "";
 77   
 78  0 public SAXEventRecorder() {
 79    }
 80   
 81  0 public void replay(ContentHandler handler) throws SAXException {
 82  0 SAXEvent saxEvent;
 83  0 Iterator itr = events.iterator();
 84   
 85  0 while (itr.hasNext()) {
 86  0 saxEvent = (SAXEvent) itr.next();
 87   
 88  0 switch (saxEvent.event) {
 89    // replay to ContentHandler
 90  0 case SAXEvent.PROCESSING_INSTRUCTION:
 91  0 handler.processingInstruction((String) saxEvent.getParm(0),
 92    (String) saxEvent.getParm(1));
 93   
 94  0 break;
 95   
 96  0 case SAXEvent.START_PREFIX_MAPPING:
 97  0 handler.startPrefixMapping((String) saxEvent.getParm(0),
 98    (String) saxEvent.getParm(1));
 99   
 100  0 break;
 101   
 102  0 case SAXEvent.END_PREFIX_MAPPING:
 103  0 handler.endPrefixMapping((String) saxEvent.getParm(0));
 104   
 105  0 break;
 106   
 107  0 case SAXEvent.START_DOCUMENT:
 108  0 handler.startDocument();
 109   
 110  0 break;
 111   
 112  0 case SAXEvent.END_DOCUMENT:
 113  0 handler.endDocument();
 114   
 115  0 break;
 116   
 117  0 case SAXEvent.START_ELEMENT:
 118   
 119  0 AttributesImpl attributes = new AttributesImpl();
 120  0 List attParmList = (List) saxEvent.getParm(3);
 121   
 122  0 if (attParmList != null) {
 123  0 Iterator attsItr = attParmList.iterator();
 124   
 125  0 while (attsItr.hasNext()) {
 126  0 String[] attParms = (String[]) attsItr.next();
 127  0 attributes.addAttribute(attParms[0], attParms[1],
 128    attParms[2], attParms[3], attParms[4]);
 129    }
 130    }
 131   
 132  0 handler.startElement((String) saxEvent.getParm(0),
 133    (String) saxEvent.getParm(1), (String) saxEvent
 134    .getParm(2), attributes);
 135   
 136  0 break;
 137   
 138  0 case SAXEvent.END_ELEMENT:
 139  0 handler.endElement((String) saxEvent.getParm(0),
 140    (String) saxEvent.getParm(1), (String) saxEvent
 141    .getParm(2));
 142   
 143  0 break;
 144   
 145  0 case SAXEvent.CHARACTERS:
 146   
 147  0 char[] chars = (char[]) saxEvent.getParm(0);
 148  0 int start = ((Integer) saxEvent.getParm(1)).intValue();
 149  0 int end = ((Integer) saxEvent.getParm(2)).intValue();
 150  0 handler.characters(chars, start, end);
 151   
 152  0 break;
 153   
 154    // replay to LexicalHandler
 155  0 case SAXEvent.START_DTD:
 156  0 ((LexicalHandler) handler).startDTD((String) saxEvent
 157    .getParm(0), (String) saxEvent.getParm(1),
 158    (String) saxEvent.getParm(2));
 159   
 160  0 break;
 161   
 162  0 case SAXEvent.END_DTD:
 163  0 ((LexicalHandler) handler).endDTD();
 164   
 165  0 break;
 166   
 167  0 case SAXEvent.START_ENTITY:
 168  0 ((LexicalHandler) handler).startEntity((String) saxEvent
 169    .getParm(0));
 170   
 171  0 break;
 172   
 173  0 case SAXEvent.END_ENTITY:
 174  0 ((LexicalHandler) handler).endEntity((String) saxEvent
 175    .getParm(0));
 176   
 177  0 break;
 178   
 179  0 case SAXEvent.START_CDATA:
 180  0 ((LexicalHandler) handler).startCDATA();
 181   
 182  0 break;
 183   
 184  0 case SAXEvent.END_CDATA:
 185  0 ((LexicalHandler) handler).endCDATA();
 186   
 187  0 break;
 188   
 189  0 case SAXEvent.COMMENT:
 190   
 191  0 char[] cchars = (char[]) saxEvent.getParm(0);
 192  0 int cstart = ((Integer) saxEvent.getParm(1)).intValue();
 193  0 int cend = ((Integer) saxEvent.getParm(2)).intValue();
 194  0 ((LexicalHandler) handler).comment(cchars, cstart, cend);
 195   
 196  0 break;
 197   
 198    // replay to DeclHandler
 199  0 case SAXEvent.ELEMENT_DECL:
 200  0 ((DeclHandler) handler).elementDecl((String) saxEvent
 201    .getParm(0), (String) saxEvent.getParm(1));
 202   
 203  0 break;
 204   
 205  0 case SAXEvent.ATTRIBUTE_DECL:
 206  0 ((DeclHandler) handler).attributeDecl((String) saxEvent
 207    .getParm(0), (String) saxEvent.getParm(1),
 208    (String) saxEvent.getParm(2), (String) saxEvent
 209    .getParm(3), (String) saxEvent.getParm(4));
 210   
 211  0 break;
 212   
 213  0 case SAXEvent.INTERNAL_ENTITY_DECL:
 214  0 ((DeclHandler) handler).internalEntityDecl(
 215    (String) saxEvent.getParm(0), (String) saxEvent
 216    .getParm(1));
 217   
 218  0 break;
 219   
 220  0 case SAXEvent.EXTERNAL_ENTITY_DECL:
 221  0 ((DeclHandler) handler).externalEntityDecl(
 222    (String) saxEvent.getParm(0), (String) saxEvent
 223    .getParm(1), (String) saxEvent.getParm(2));
 224   
 225  0 break;
 226   
 227  0 default:
 228  0 throw new SAXException("Unrecognized event: "
 229    + saxEvent.event);
 230    }
 231    }
 232    }
 233   
 234    // ContentHandler interface
 235    // -------------------------------------------------------------------------
 236  0 public void processingInstruction(String target, String data)
 237    throws SAXException {
 238  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.PROCESSING_INSTRUCTION);
 239  0 saxEvent.addParm(target);
 240  0 saxEvent.addParm(data);
 241  0 events.add(saxEvent);
 242    }
 243   
 244  0 public void startPrefixMapping(String prefix, String uri)
 245    throws SAXException {
 246  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.START_PREFIX_MAPPING);
 247  0 saxEvent.addParm(prefix);
 248  0 saxEvent.addParm(uri);
 249  0 events.add(saxEvent);
 250    }
 251   
 252  0 public void endPrefixMapping(String prefix) throws SAXException {
 253  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.END_PREFIX_MAPPING);
 254  0 saxEvent.addParm(prefix);
 255  0 events.add(saxEvent);
 256    }
 257   
 258  0 public void startDocument() throws SAXException {
 259  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.START_DOCUMENT);
 260  0 events.add(saxEvent);
 261    }
 262   
 263  0 public void endDocument() throws SAXException {
 264  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.END_DOCUMENT);
 265  0 events.add(saxEvent);
 266    }
 267   
 268  0 public void startElement(String namespaceURI, String localName,
 269    String qualifiedName, Attributes attributes) throws SAXException {
 270  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.START_ELEMENT);
 271  0 saxEvent.addParm(namespaceURI);
 272  0 saxEvent.addParm(localName);
 273  0 saxEvent.addParm(qualifiedName);
 274   
 275  0 QName qName = null;
 276  0 if (namespaceURI != null) {
 277  0 qName = new QName(localName, Namespace.get(namespaceURI));
 278    } else {
 279  0 qName = new QName(localName);
 280    }
 281   
 282  0 if ((attributes != null) && (attributes.getLength() > 0)) {
 283  0 List attParmList = new ArrayList(attributes.getLength());
 284  0 String[] attParms = null;
 285   
 286  0 for (int i = 0; i < attributes.getLength(); i++) {
 287   
 288  0 String attLocalName = attributes.getLocalName(i);
 289   
 290  0 if (attLocalName.startsWith(XMLNS)) {
 291   
 292    // if SAXWriter is writing a DOMDocument, namespace
 293    // decls are treated as attributes. record a start
 294    // prefix mapping event
 295  0 String prefix = null;
 296  0 if (attLocalName.length() > 5) {
 297  0 prefix = attLocalName.substring(6);
 298    } else {
 299  0 prefix = EMPTY_STRING;
 300    }
 301   
 302  0 SAXEvent prefixEvent = new SAXEvent(
 303    SAXEvent.START_PREFIX_MAPPING);
 304  0 prefixEvent.addParm(prefix);
 305  0 prefixEvent.addParm(attributes.getValue(i));
 306  0 events.add(prefixEvent);
 307   
 308    // 'register' the prefix so that we can generate
 309    // an end prefix mapping event within endElement
 310  0 List prefixes = (List) prefixMappings.get(qName);
 311  0 if (prefixes == null) {
 312  0 prefixes = new ArrayList();
 313  0 prefixMappings.put(qName, prefixes);
 314    }
 315  0 prefixes.add(prefix);
 316   
 317    } else {
 318   
 319  0 attParms = new String[5];
 320  0 attParms[0] = attributes.getURI(i);
 321  0 attParms[1] = attLocalName;
 322  0 attParms[2] = attributes.getQName(i);
 323  0 attParms[3] = attributes.getType(i);
 324  0 attParms[4] = attributes.getValue(i);
 325  0 attParmList.add(attParms);
 326   
 327    }
 328   
 329    }
 330   
 331  0 saxEvent.addParm(attParmList);
 332    }
 333   
 334  0 events.add(saxEvent);
 335    }
 336   
 337  0 public void endElement(String namespaceURI, String localName, String qName)
 338    throws SAXException {
 339   
 340  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.END_ELEMENT);
 341  0 saxEvent.addParm(namespaceURI);
 342  0 saxEvent.addParm(localName);
 343  0 saxEvent.addParm(qName);
 344  0 events.add(saxEvent);
 345   
 346    // check to see if a we issued a start prefix mapping event
 347    // for DOMDocument namespace decls
 348   
 349  0 QName elementName = null;
 350  0 if (namespaceURI != null) {
 351  0 elementName = new QName(localName, Namespace.get(namespaceURI));
 352    } else {
 353  0 elementName = new QName(localName);
 354    }
 355   
 356  0 List prefixes = (List) prefixMappings.get(elementName);
 357  0 if (prefixes != null) {
 358  0 Iterator itr = prefixes.iterator();
 359  0 while (itr.hasNext()) {
 360  0 SAXEvent prefixEvent =
 361    new SAXEvent(SAXEvent.END_PREFIX_MAPPING);
 362  0 prefixEvent.addParm(itr.next());
 363  0 events.add(prefixEvent);
 364    }
 365    }
 366   
 367    }
 368   
 369  0 public void characters(char[] ch, int start, int end) throws SAXException {
 370  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.CHARACTERS);
 371  0 saxEvent.addParm(ch);
 372  0 saxEvent.addParm(new Integer(start));
 373  0 saxEvent.addParm(new Integer(end));
 374  0 events.add(saxEvent);
 375    }
 376   
 377    // LexicalHandler interface
 378    // -------------------------------------------------------------------------
 379  0 public void startDTD(String name, String publicId, String systemId)
 380    throws SAXException {
 381  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.START_DTD);
 382  0 saxEvent.addParm(name);
 383  0 saxEvent.addParm(publicId);
 384  0 saxEvent.addParm(systemId);
 385  0 events.add(saxEvent);
 386    }
 387   
 388  0 public void endDTD() throws SAXException {
 389  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.END_DTD);
 390  0 events.add(saxEvent);
 391    }
 392   
 393  0 public void startEntity(String name) throws SAXException {
 394  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.START_ENTITY);
 395  0 saxEvent.addParm(name);
 396  0 events.add(saxEvent);
 397    }
 398   
 399  0 public void endEntity(String name) throws SAXException {
 400  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.END_ENTITY);
 401  0 saxEvent.addParm(name);
 402  0 events.add(saxEvent);
 403    }
 404   
 405  0 public void startCDATA() throws SAXException {
 406  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.START_CDATA);
 407  0 events.add(saxEvent);
 408    }
 409   
 410  0 public void endCDATA() throws SAXException {
 411  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.END_CDATA);
 412  0 events.add(saxEvent);
 413    }
 414   
 415  0 public void comment(char[] ch, int start, int end) throws SAXException {
 416  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.COMMENT);
 417  0 saxEvent.addParm(ch);
 418  0 saxEvent.addParm(new Integer(start));
 419  0 saxEvent.addParm(new Integer(end));
 420  0 events.add(saxEvent);
 421    }
 422   
 423    // DeclHandler interface
 424    // -------------------------------------------------------------------------
 425  0 public void elementDecl(String name, String model) throws SAXException {
 426  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.ELEMENT_DECL);
 427  0 saxEvent.addParm(name);
 428  0 saxEvent.addParm(model);
 429  0 events.add(saxEvent);
 430    }
 431   
 432  0 public void attributeDecl(String eName, String aName, String type,
 433    String valueDefault, String value) throws SAXException {
 434  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.ATTRIBUTE_DECL);
 435  0 saxEvent.addParm(eName);
 436  0 saxEvent.addParm(aName);
 437  0 saxEvent.addParm(type);
 438  0 saxEvent.addParm(valueDefault);
 439  0 saxEvent.addParm(value);
 440  0 events.add(saxEvent);
 441    }
 442   
 443  0 public void internalEntityDecl(String name, String value)
 444    throws SAXException {
 445  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.INTERNAL_ENTITY_DECL);
 446  0 saxEvent.addParm(name);
 447  0 saxEvent.addParm(value);
 448  0 events.add(saxEvent);
 449    }
 450   
 451  0 public void externalEntityDecl(String name, String publicId, String sysId)
 452    throws SAXException {
 453  0 SAXEvent saxEvent = new SAXEvent(SAXEvent.EXTERNAL_ENTITY_DECL);
 454  0 saxEvent.addParm(name);
 455  0 saxEvent.addParm(publicId);
 456  0 saxEvent.addParm(sysId);
 457  0 events.add(saxEvent);
 458    }
 459   
 460  0 public void writeExternal(ObjectOutput out) throws IOException {
 461  0 if (events == null) {
 462  0 out.writeByte(NULL);
 463    } else {
 464  0 out.writeByte(OBJECT);
 465  0 out.writeObject(events);
 466    }
 467    }
 468   
 469  0 public void readExternal(ObjectInput in) throws ClassNotFoundException,
 470    IOException {
 471  0 if (in.readByte() != NULL) {
 472  0 events = (List) in.readObject();
 473    }
 474    }
 475   
 476    // SAXEvent inner class
 477    // -------------------------------------------------------------------------
 478    static class SAXEvent implements Externalizable {
 479    public static final long serialVersionUID = 1;
 480   
 481    static final byte PROCESSING_INSTRUCTION = 1;
 482   
 483    static final byte START_PREFIX_MAPPING = 2;
 484   
 485    static final byte END_PREFIX_MAPPING = 3;
 486   
 487    static final byte START_DOCUMENT = 4;
 488   
 489    static final byte END_DOCUMENT = 5;
 490   
 491    static final byte START_ELEMENT = 6;
 492   
 493    static final byte END_ELEMENT = 7;
 494   
 495    static final byte CHARACTERS = 8;
 496   
 497    static final byte START_DTD = 9;
 498   
 499    static final byte END_DTD = 10;
 500   
 501    static final byte START_ENTITY = 11;
 502   
 503    static final byte END_ENTITY = 12;
 504   
 505    static final byte START_CDATA = 13;
 506   
 507    static final byte END_CDATA = 14;
 508   
 509    static final byte COMMENT = 15;
 510   
 511    static final byte ELEMENT_DECL = 16;
 512   
 513    static final byte ATTRIBUTE_DECL = 17;
 514   
 515    static final byte INTERNAL_ENTITY_DECL = 18;
 516   
 517    static final byte EXTERNAL_ENTITY_DECL = 19;
 518   
 519    protected byte event;
 520   
 521    protected List parms;
 522   
 523  0 public SAXEvent() {
 524    }
 525   
 526  0 SAXEvent(byte event) {
 527  0 this.event = event;
 528    }
 529   
 530  0 void addParm(Object parm) {
 531  0 if (parms == null) {
 532  0 parms = new ArrayList(3);
 533    }
 534   
 535  0 parms.add(parm);
 536    }
 537   
 538  0 Object getParm(int index) {
 539  0 if ((parms != null) && (index < parms.size())) {
 540  0 return parms.get(index);
 541    } else {
 542  0 return null;
 543    }
 544    }
 545   
 546  0 public void writeExternal(ObjectOutput out) throws IOException {
 547  0 out.writeByte(event);
 548   
 549  0 if (parms == null) {
 550  0 out.writeByte(NULL);
 551    } else {
 552  0 out.writeByte(OBJECT);
 553  0 out.writeObject(parms);
 554    }
 555    }
 556   
 557  0 public void readExternal(ObjectInput in) throws ClassNotFoundException,
 558    IOException {
 559  0 event = in.readByte();
 560   
 561  0 if (in.readByte() != NULL) {
 562  0 parms = (List) in.readObject();
 563    }
 564    }
 565    }
 566    }
 567   
 568    /*
 569    * Redistribution and use of this software and associated documentation
 570    * ("Software"), with or without modification, are permitted provided that the
 571    * following conditions are met:
 572    *
 573    * 1. Redistributions of source code must retain copyright statements and
 574    * notices. Redistributions must also contain a copy of this document.
 575    *
 576    * 2. Redistributions in binary form must reproduce the above copyright notice,
 577    * this list of conditions and the following disclaimer in the documentation
 578    * and/or other materials provided with the distribution.
 579    *
 580    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 581    * from this Software without prior written permission of MetaStuff, Ltd. For
 582    * written permission, please contact dom4j-info@metastuff.com.
 583    *
 584    * 4. Products derived from this Software may not be called "DOM4J" nor may
 585    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 586    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 587    *
 588    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 589    *
 590    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 591    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 592    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 593    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 594    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 595    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 596    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 597    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 598    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 599    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 600    * POSSIBILITY OF SUCH DAMAGE.
 601    *
 602    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 603    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/SAXReader.html0000644000175000017500000103310110242117571021164 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 1.042   Methods: 58
NCLOC: 382   Classes: 2
 
 Source file Conditionals Statements Methods TOTAL
SAXReader.java 51,9% 62,6% 58,6% 59,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.io.File;
 11    import java.io.FileInputStream;
 12    import java.io.FileNotFoundException;
 13    import java.io.InputStream;
 14    import java.io.Reader;
 15    import java.io.Serializable;
 16    import java.net.URL;
 17   
 18    import org.dom4j.Document;
 19    import org.dom4j.DocumentException;
 20    import org.dom4j.DocumentFactory;
 21    import org.dom4j.ElementHandler;
 22   
 23    import org.xml.sax.EntityResolver;
 24    import org.xml.sax.ErrorHandler;
 25    import org.xml.sax.InputSource;
 26    import org.xml.sax.SAXException;
 27    import org.xml.sax.SAXParseException;
 28    import org.xml.sax.XMLFilter;
 29    import org.xml.sax.XMLReader;
 30    import org.xml.sax.helpers.DefaultHandler;
 31    import org.xml.sax.helpers.XMLReaderFactory;
 32   
 33    /**
 34    * <p>
 35    * <code>SAXReader</code> creates a DOM4J tree from SAX parsing events.
 36    * </p>
 37    *
 38    * <p>
 39    * The actual SAX parser that is used by this class is configurable so you can
 40    * use your favourite SAX parser if you wish. DOM4J comes configured with its
 41    * own SAX parser so you do not need to worry about configuring the SAX parser.
 42    * </p>
 43    *
 44    * <p>
 45    * To explicitly configure the SAX parser that is used via Java code you can use
 46    * a constructor or use the {@link #setXMLReader(XMLReader)}or {@link
 47    * #setXMLReaderClassName(String)} methods.
 48    * </p>
 49    *
 50    * <p>
 51    * If the parser is not specified explicitly then the standard SAX policy of
 52    * using the <code>org.xml.sax.driver</code> system property is used to
 53    * determine the implementation class of {@link XMLReader}.
 54    * </p>
 55    *
 56    * <p>
 57    * If the <code>org.xml.sax.driver</code> system property is not defined then
 58    * JAXP is used via reflection (so that DOM4J is not explicitly dependent on the
 59    * JAXP classes) to load the JAXP configured SAXParser. If there is any error
 60    * creating a JAXP SAXParser an informational message is output and then the
 61    * default (Aelfred) SAX parser is used instead.
 62    * </p>
 63    *
 64    * <p>
 65    * If you are trying to use JAXP to explicitly set your SAX parser and are
 66    * experiencing problems, you can turn on verbose error reporting by defining
 67    * the system property <code>org.dom4j.verbose</code> to be "true" which will
 68    * output a more detailed description of why JAXP could not find a SAX parser
 69    * </p>
 70    *
 71    * <p>
 72    * For more information on JAXP please go to <a
 73    * href="http://java.sun.com/xml/">Sun's Java &amp; XML site </a>
 74    * </p>
 75    *
 76    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 77    * @version $Revision: 1.58 $
 78    */
 79    public class SAXReader {
 80    private static final String SAX_STRING_INTERNING =
 81    "http://xml.org/sax/features/string-interning";
 82    private static final String SAX_NAMESPACE_PREFIXES =
 83    "http://xml.org/sax/features/namespace-prefixes";
 84    private static final String SAX_NAMESPACES =
 85    "http://xml.org/sax/features/namespaces";
 86    private static final String SAX_DECL_HANDLER =
 87    "http://xml.org/sax/properties/declaration-handler";
 88    private static final String SAX_LEXICAL_HANDLER =
 89    "http://xml.org/sax/properties/lexical-handler";
 90    private static final String SAX_LEXICALHANDLER =
 91    "http://xml.org/sax/handlers/LexicalHandler";
 92   
 93    /** <code>DocumentFactory</code> used to create new document objects */
 94    private DocumentFactory factory;
 95   
 96    /** <code>XMLReader</code> used to parse the SAX events */
 97    private XMLReader xmlReader;
 98   
 99    /** Whether validation should occur */
 100    private boolean validating;
 101   
 102    /** DispatchHandler to call when each <code>Element</code> is encountered */
 103    private DispatchHandler dispatchHandler;
 104   
 105    /** ErrorHandler class to use */
 106    private ErrorHandler errorHandler;
 107   
 108    /** The entity resolver */
 109    private EntityResolver entityResolver;
 110   
 111    /** Should element & attribute names and namespace URIs be interned? */
 112    private boolean stringInternEnabled = true;
 113   
 114    /** Should internal DTD declarations be expanded into a List in the DTD */
 115    private boolean includeInternalDTDDeclarations = false;
 116   
 117    /** Should external DTD declarations be expanded into a List in the DTD */
 118    private boolean includeExternalDTDDeclarations = false;
 119   
 120    /** Whether adjacent text nodes should be merged */
 121    private boolean mergeAdjacentText = false;
 122   
 123    /** Holds value of property stripWhitespaceText. */
 124    private boolean stripWhitespaceText = false;
 125   
 126    /** Should we ignore comments */
 127    private boolean ignoreComments = false;
 128   
 129    /** Encoding of InputSource - null means system default encoding */
 130    private String encoding = null;
 131   
 132    // private boolean includeExternalGeneralEntities = false;
 133    // private boolean includeExternalParameterEntities = false;
 134   
 135    /** The SAX filter used to filter SAX events */
 136    private XMLFilter xmlFilter;
 137   
 138  5741 public SAXReader() {
 139    }
 140   
 141  1 public SAXReader(boolean validating) {
 142  1 this.validating = validating;
 143    }
 144   
 145  55 public SAXReader(DocumentFactory factory) {
 146  55 this.factory = factory;
 147    }
 148   
 149  0 public SAXReader(DocumentFactory factory, boolean validating) {
 150  0 this.factory = factory;
 151  0 this.validating = validating;
 152    }
 153   
 154  0 public SAXReader(XMLReader xmlReader) {
 155  0 this.xmlReader = xmlReader;
 156    }
 157   
 158  0 public SAXReader(XMLReader xmlReader, boolean validating) {
 159  0 this.xmlReader = xmlReader;
 160  0 this.validating = validating;
 161    }
 162   
 163  1 public SAXReader(String xmlReaderClassName) throws SAXException {
 164  1 if (xmlReaderClassName != null) {
 165  1 this.xmlReader = XMLReaderFactory
 166    .createXMLReader(xmlReaderClassName);
 167    }
 168    }
 169   
 170  0 public SAXReader(String xmlReaderClassName, boolean validating)
 171    throws SAXException {
 172  0 if (xmlReaderClassName != null) {
 173  0 this.xmlReader = XMLReaderFactory
 174    .createXMLReader(xmlReaderClassName);
 175    }
 176   
 177  0 this.validating = validating;
 178    }
 179   
 180    /**
 181    * Allows a SAX property to be set on the underlying SAX parser. This can be
 182    * useful to set parser-specific properties such as the location of schema
 183    * or DTD resources. Though use this method with caution as it has the
 184    * possibility of breaking the standard behaviour. An alternative to calling
 185    * this method is to correctly configure an XMLReader object instance and
 186    * call the {@link #setXMLReader(XMLReader)}method
 187    *
 188    * @param name
 189    * is the SAX property name
 190    * @param value
 191    * is the value of the SAX property
 192    *
 193    * @throws SAXException
 194    * if the XMLReader could not be created or the property could
 195    * not be changed.
 196    */
 197  0 public void setProperty(String name, Object value) throws SAXException {
 198  0 getXMLReader().setProperty(name, value);
 199    }
 200   
 201    /**
 202    * Sets a SAX feature on the underlying SAX parser. This can be useful to
 203    * set parser-specific features. Though use this method with caution as it
 204    * has the possibility of breaking the standard behaviour. An alternative to
 205    * calling this method is to correctly configure an XMLReader object
 206    * instance and call the {@link #setXMLReader(XMLReader)}method
 207    *
 208    * @param name
 209    * is the SAX feature name
 210    * @param value
 211    * is the value of the SAX feature
 212    *
 213    * @throws SAXException
 214    * if the XMLReader could not be created or the feature could
 215    * not be changed.
 216    */
 217  0 public void setFeature(String name, boolean value) throws SAXException {
 218  0 getXMLReader().setFeature(name, value);
 219    }
 220   
 221    /**
 222    * <p>
 223    * Reads a Document from the given <code>File</code>
 224    * </p>
 225    *
 226    * @param file
 227    * is the <code>File</code> to read from.
 228    *
 229    * @return the newly created Document instance
 230    *
 231    * @throws DocumentException
 232    * if an error occurs during parsing.
 233    */
 234  204 public Document read(File file) throws DocumentException {
 235  204 try {
 236    /*
 237    * We cannot convert the file to an URL because if the filename
 238    * contains '#' characters, there will be problems with the URL in
 239    * the InputSource (because a URL like
 240    * http://myhost.com/index#anchor is treated the same as
 241    * http://myhost.com/index) Thanks to Christian Oetterli
 242    */
 243  204 InputSource source = new InputSource(new FileInputStream(file));
 244  204 if (this.encoding != null) {
 245  0 source.setEncoding(this.encoding);
 246    }
 247  204 String path = file.getAbsolutePath();
 248   
 249  204 if (path != null) {
 250    // Code taken from Ant FileUtils
 251  204 StringBuffer sb = new StringBuffer("file://");
 252   
 253    // add an extra slash for filesystems with drive-specifiers
 254  204 if (!path.startsWith(File.separator)) {
 255  204 sb.append("/");
 256    }
 257   
 258  204 path = path.replace('\\', '/');
 259  204 sb.append(path);
 260   
 261  204 source.setSystemId(sb.toString());
 262    }
 263   
 264  204 return read(source);
 265    } catch (FileNotFoundException e) {
 266  0 throw new DocumentException(e.getMessage(), e);
 267    }
 268    }
 269   
 270    /**
 271    * <p>
 272    * Reads a Document from the given <code>URL</code> using SAX
 273    * </p>
 274    *
 275    * @param url
 276    * <code>URL</code> to read from.
 277    *
 278    * @return the newly created Document instance
 279    *
 280    * @throws DocumentException
 281    * if an error occurs during parsing.
 282    */
 283  0 public Document read(URL url) throws DocumentException {
 284  0 String systemID = url.toExternalForm();
 285   
 286  0 InputSource source = new InputSource(systemID);
 287  0 if (this.encoding != null) {
 288  0 source.setEncoding(this.encoding);
 289    }
 290   
 291  0 return read(source);
 292    }
 293   
 294    /**
 295    * <p>
 296    * Reads a Document from the given URL or filename using SAX.
 297    * </p>
 298    *
 299    * <p>
 300    * If the systemId contains a <code>':'</code> character then it is
 301    * assumed to be a URL otherwise its assumed to be a file name. If you want
 302    * finer grained control over this mechansim then please explicitly pass in
 303    * either a {@link URL}or a {@link File}instance instead of a {@link
 304    * String} to denote the source of the document.
 305    * </p>
 306    *
 307    * @param systemId
 308    * is a URL for a document or a file name.
 309    *
 310    * @return the newly created Document instance
 311    *
 312    * @throws DocumentException
 313    * if an error occurs during parsing.
 314    */
 315  1 public Document read(String systemId) throws DocumentException {
 316  1 InputSource source = new InputSource(systemId);
 317  1 if (this.encoding != null) {
 318  0 source.setEncoding(this.encoding);
 319    }
 320   
 321  1 return read(source);
 322    }
 323   
 324    /**
 325    * <p>
 326    * Reads a Document from the given stream using SAX
 327    * </p>
 328    *
 329    * @param in
 330    * <code>InputStream</code> to read from.
 331    *
 332    * @return the newly created Document instance
 333    *
 334    * @throws DocumentException
 335    * if an error occurs during parsing.
 336    */
 337  1 public Document read(InputStream in) throws DocumentException {
 338  1 InputSource source = new InputSource(in);
 339  1 if (this.encoding != null) {
 340  0 source.setEncoding(this.encoding);
 341    }
 342   
 343  1 return read(source);
 344    }
 345   
 346    /**
 347    * <p>
 348    * Reads a Document from the given <code>Reader</code> using SAX
 349    * </p>
 350    *
 351    * @param reader
 352    * is the reader for the input
 353    *
 354    * @return the newly created Document instance
 355    *
 356    * @throws DocumentException
 357    * if an error occurs during parsing.
 358    */
 359  31 public Document read(Reader reader) throws DocumentException {
 360  31 InputSource source = new InputSource(reader);
 361  31 if (this.encoding != null) {
 362  1 source.setEncoding(this.encoding);
 363    }
 364   
 365  31 return read(source);
 366    }
 367   
 368    /**
 369    * <p>
 370    * Reads a Document from the given stream using SAX
 371    * </p>
 372    *
 373    * @param in
 374    * <code>InputStream</code> to read from.
 375    * @param systemId
 376    * is the URI for the input
 377    *
 378    * @return the newly created Document instance
 379    *
 380    * @throws DocumentException
 381    * if an error occurs during parsing.
 382    */
 383  0 public Document read(InputStream in, String systemId)
 384    throws DocumentException {
 385  0 InputSource source = new InputSource(in);
 386  0 source.setSystemId(systemId);
 387  0 if (this.encoding != null) {
 388  0 source.setEncoding(this.encoding);
 389    }
 390   
 391  0 return read(source);
 392    }
 393   
 394    /**
 395    * <p>
 396    * Reads a Document from the given <code>Reader</code> using SAX
 397    * </p>
 398    *
 399    * @param reader
 400    * is the reader for the input
 401    * @param systemId
 402    * is the URI for the input
 403    *
 404    * @return the newly created Document instance
 405    *
 406    * @throws DocumentException
 407    * if an error occurs during parsing.
 408    */
 409  0 public Document read(Reader reader, String systemId)
 410    throws DocumentException {
 411  0 InputSource source = new InputSource(reader);
 412  0 source.setSystemId(systemId);
 413  0 if (this.encoding != null) {
 414  0 source.setEncoding(this.encoding);
 415    }
 416   
 417  0 return read(source);
 418    }
 419   
 420    /**
 421    * <p>
 422    * Reads a Document from the given <code>InputSource</code> using SAX
 423    * </p>
 424    *
 425    * @param in
 426    * <code>InputSource</code> to read from.
 427    *
 428    * @return the newly created Document instance
 429    *
 430    * @throws DocumentException
 431    * if an error occurs during parsing.
 432    */
 433  5792 public Document read(InputSource in) throws DocumentException {
 434  5792 try {
 435  5792 XMLReader reader = getXMLReader();
 436   
 437  5792 reader = installXMLFilter(reader);
 438   
 439  5792 EntityResolver thatEntityResolver = this.entityResolver;
 440   
 441  5792 if (thatEntityResolver == null) {
 442  5762 thatEntityResolver = createDefaultEntityResolver(in
 443    .getSystemId());
 444  5762 this.entityResolver = thatEntityResolver;
 445    }
 446   
 447  5792 reader.setEntityResolver(thatEntityResolver);
 448   
 449  5792 SAXContentHandler contentHandler = createContentHandler(reader);
 450  5792 contentHandler.setEntityResolver(thatEntityResolver);
 451  5792 contentHandler.setInputSource(in);
 452   
 453  5792 boolean internal = isIncludeInternalDTDDeclarations();
 454  5792 boolean external = isIncludeExternalDTDDeclarations();
 455   
 456  5792 contentHandler.setIncludeInternalDTDDeclarations(internal);
 457  5792 contentHandler.setIncludeExternalDTDDeclarations(external);
 458  5792 contentHandler.setMergeAdjacentText(isMergeAdjacentText());
 459  5792 contentHandler.setStripWhitespaceText(isStripWhitespaceText());
 460  5792 contentHandler.setIgnoreComments(isIgnoreComments());
 461  5792 reader.setContentHandler(contentHandler);
 462   
 463  5792 configureReader(reader, contentHandler);
 464   
 465  5792 reader.parse(in);
 466   
 467  5791 return contentHandler.getDocument();
 468    } catch (Exception e) {
 469  1 if (e instanceof SAXParseException) {
 470    // e.printStackTrace();
 471  0 SAXParseException parseException = (SAXParseException) e;
 472  0 String systemId = parseException.getSystemId();
 473   
 474  0 if (systemId == null) {
 475  0 systemId = "";
 476    }
 477   
 478  0 String message = "Error on line "
 479    + parseException.getLineNumber() + " of document "
 480    + systemId + " : " + parseException.getMessage();
 481   
 482  0 throw new DocumentException(message, e);
 483    } else {
 484  1 throw new DocumentException(e.getMessage(), e);
 485    }
 486    }
 487    }
 488   
 489    // Properties
 490    // -------------------------------------------------------------------------
 491   
 492    /**
 493    * DOCUMENT ME!
 494    *
 495    * @return the validation mode, true if validating will be done otherwise
 496    * false.
 497    */
 498  11556 public boolean isValidating() {
 499  11556 return validating;
 500    }
 501   
 502    /**
 503    * Sets the validation mode.
 504    *
 505    * @param validation
 506    * indicates whether or not validation should occur.
 507    */
 508  0 public void setValidation(boolean validation) {
 509  0 this.validating = validation;
 510    }
 511   
 512    /**
 513    * DOCUMENT ME!
 514    *
 515    * @return whether internal DTD declarations should be expanded into the
 516    * DocumentType object or not.
 517    */
 518  5792 public boolean isIncludeInternalDTDDeclarations() {
 519  5792 return includeInternalDTDDeclarations;
 520    }
 521   
 522    /**
 523    * Sets whether internal DTD declarations should be expanded into the
 524    * DocumentType object or not.
 525    *
 526    * @param include
 527    * whether or not DTD declarations should be expanded and
 528    * included into the DocumentType object.
 529    */
 530  5 public void setIncludeInternalDTDDeclarations(boolean include) {
 531  5 this.includeInternalDTDDeclarations = include;
 532    }
 533   
 534    /**
 535    * DOCUMENT ME!
 536    *
 537    * @return whether external DTD declarations should be expanded into the
 538    * DocumentType object or not.
 539    */
 540  5792 public boolean isIncludeExternalDTDDeclarations() {
 541  5792 return includeExternalDTDDeclarations;
 542    }
 543   
 544    /**
 545    * Sets whether DTD external declarations should be expanded into the
 546    * DocumentType object or not.
 547    *
 548    * @param include
 549    * whether or not DTD declarations should be expanded and
 550    * included into the DocumentType object.
 551    */
 552  4 public void setIncludeExternalDTDDeclarations(boolean include) {
 553  4 this.includeExternalDTDDeclarations = include;
 554    }
 555   
 556    /**
 557    * Sets whether String interning is enabled or disabled for element &
 558    * attribute names and namespace URIs. This proprety is enabled by default.
 559    *
 560    * @return DOCUMENT ME!
 561    */
 562  5792 public boolean isStringInternEnabled() {
 563  5792 return stringInternEnabled;
 564    }
 565   
 566    /**
 567    * Sets whether String interning is enabled or disabled for element &
 568    * attribute names and namespace URIs
 569    *
 570    * @param stringInternEnabled
 571    * DOCUMENT ME!
 572    */
 573  0 public void setStringInternEnabled(boolean stringInternEnabled) {
 574  0 this.stringInternEnabled = stringInternEnabled;
 575    }
 576   
 577    /**
 578    * Returns whether adjacent text nodes should be merged together.
 579    *
 580    * @return Value of property mergeAdjacentText.
 581    */
 582  5792 public boolean isMergeAdjacentText() {
 583  5792 return mergeAdjacentText;
 584    }
 585   
 586    /**
 587    * Sets whether or not adjacent text nodes should be merged together when
 588    * parsing.
 589    *
 590    * @param mergeAdjacentText
 591    * New value of property mergeAdjacentText.
 592    */
 593  7 public void setMergeAdjacentText(boolean mergeAdjacentText) {
 594  7 this.mergeAdjacentText = mergeAdjacentText;
 595    }
 596   
 597    /**
 598    * Sets whether whitespace between element start and end tags should be
 599    * ignored
 600    *
 601    * @return Value of property stripWhitespaceText.
 602    */
 603  5792 public boolean isStripWhitespaceText() {
 604  5792 return stripWhitespaceText;
 605    }
 606   
 607    /**
 608    * Sets whether whitespace between element start and end tags should be
 609    * ignored.
 610    *
 611    * @param stripWhitespaceText
 612    * New value of property stripWhitespaceText.
 613    */
 614  0 public void setStripWhitespaceText(boolean stripWhitespaceText) {
 615  0 this.stripWhitespaceText = stripWhitespaceText;
 616    }
 617   
 618    /**
 619    * Returns whether we should ignore comments or not.
 620    *
 621    * @return boolean
 622    */
 623  5792 public boolean isIgnoreComments() {
 624  5792 return ignoreComments;
 625    }
 626   
 627    /**
 628    * Sets whether we should ignore comments or not.
 629    *
 630    * @param ignoreComments
 631    * whether we should ignore comments or not.
 632    */
 633  0 public void setIgnoreComments(boolean ignoreComments) {
 634  0 this.ignoreComments = ignoreComments;
 635    }
 636   
 637    /**
 638    * DOCUMENT ME!
 639    *
 640    * @return the <code>DocumentFactory</code> used to create document
 641    * objects
 642    */
 643  5792 public DocumentFactory getDocumentFactory() {
 644  5792 if (factory == null) {
 645  5702 factory = DocumentFactory.getInstance();
 646    }
 647   
 648  5792 return factory;
 649    }
 650   
 651    /**
 652    * <p>
 653    * This sets the <code>DocumentFactory</code> used to create new
 654    * documents. This method allows the building of custom DOM4J tree objects
 655    * to be implemented easily using a custom derivation of
 656    * {@link DocumentFactory}
 657    * </p>
 658    *
 659    * @param documentFactory
 660    * <code>DocumentFactory</code> used to create DOM4J objects
 661    */
 662  8 public void setDocumentFactory(DocumentFactory documentFactory) {
 663  8 this.factory = documentFactory;
 664    }
 665   
 666    /**
 667    * DOCUMENT ME!
 668    *
 669    * @return the <code>ErrorHandler</code> used by SAX
 670    */
 671  0 public ErrorHandler getErrorHandler() {
 672  0 return errorHandler;
 673    }
 674   
 675    /**
 676    * Sets the <code>ErrorHandler</code> used by the SAX
 677    * <code>XMLReader</code>.
 678    *
 679    * @param errorHandler
 680    * is the <code>ErrorHandler</code> used by SAX
 681    */
 682  0 public void setErrorHandler(ErrorHandler errorHandler) {
 683  0 this.errorHandler = errorHandler;
 684    }
 685   
 686    /**
 687    * Returns the current entity resolver used to resolve entities
 688    *
 689    * @return DOCUMENT ME!
 690    */
 691  0 public EntityResolver getEntityResolver() {
 692  0 return entityResolver;
 693    }
 694   
 695    /**
 696    * Sets the entity resolver used to resolve entities.
 697    *
 698    * @param entityResolver
 699    * DOCUMENT ME!
 700    */
 701  3 public void setEntityResolver(EntityResolver entityResolver) {
 702  3 this.entityResolver = entityResolver;
 703    }
 704   
 705    /**
 706    * DOCUMENT ME!
 707    *
 708    * @return the <code>XMLReader</code> used to parse SAX events
 709    *
 710    * @throws SAXException
 711    * DOCUMENT ME!
 712    */
 713  5792 public XMLReader getXMLReader() throws SAXException {
 714  5792 if (xmlReader == null) {
 715  5764 xmlReader = createXMLReader();
 716    }
 717   
 718  5792 return xmlReader;
 719    }
 720   
 721    /**
 722    * Sets the <code>XMLReader</code> used to parse SAX events
 723    *
 724    * @param reader
 725    * is the <code>XMLReader</code> to parse SAX events
 726    */
 727  0 public void setXMLReader(XMLReader reader) {
 728  0 this.xmlReader = reader;
 729    }
 730   
 731    /**
 732    * Returns encoding used for InputSource (null means system default
 733    * encoding)
 734    *
 735    * @return encoding used for InputSource
 736    *
 737    */
 738  0 public String getEncoding() {
 739  0 return encoding;
 740    }
 741   
 742    /**
 743    * Sets encoding used for InputSource (null means system default encoding)
 744    *
 745    * @param encoding
 746    * is encoding used for InputSource
 747    */
 748  1 public void setEncoding(String encoding) {
 749  1 this.encoding = encoding;
 750    }
 751   
 752    /**
 753    * Sets the class name of the <code>XMLReader</code> to be used to parse
 754    * SAX events.
 755    *
 756    * @param xmlReaderClassName
 757    * is the class name of the <code>XMLReader</code> to parse SAX
 758    * events
 759    *
 760    * @throws SAXException
 761    * DOCUMENT ME!
 762    */
 763  0 public void setXMLReaderClassName(String xmlReaderClassName)
 764    throws SAXException {
 765  0 setXMLReader(XMLReaderFactory.createXMLReader(xmlReaderClassName));
 766    }
 767   
 768    /**
 769    * Adds the <code>ElementHandler</code> to be called when the specified
 770    * path is encounted.
 771    *
 772    * @param path
 773    * is the path to be handled
 774    * @param handler
 775    * is the <code>ElementHandler</code> to be called by the event
 776    * based processor.
 777    */
 778  21 public void addHandler(String path, ElementHandler handler) {
 779  21 getDispatchHandler().addHandler(path, handler);
 780    }
 781   
 782    /**
 783    * Removes the <code>ElementHandler</code> from the event based processor,
 784    * for the specified path.
 785    *
 786    * @param path
 787    * is the path to remove the <code>ElementHandler</code> for.
 788    */
 789  0 public void removeHandler(String path) {
 790  0 getDispatchHandler().removeHandler(path);
 791    }
 792   
 793    /**
 794    * When multiple <code>ElementHandler</code> instances have been
 795    * registered, this will set a default <code>ElementHandler</code> to be
 796    * called for any path which does <b>NOT </b> have a handler registered.
 797    *
 798    * @param handler
 799    * is the <code>ElementHandler</code> to be called by the event
 800    * based processor.
 801    */
 802  0 public void setDefaultHandler(ElementHandler handler) {
 803  0 getDispatchHandler().setDefaultHandler(handler);
 804    }
 805   
 806    /**
 807    * This method clears out all the existing handlers and default handler
 808    * setting things back as if no handler existed. Useful when reusing an
 809    * object instance.
 810    */
 811  0 public void resetHandlers() {
 812  0 getDispatchHandler().resetHandlers();
 813    }
 814   
 815    /**
 816    * Returns the SAX filter being used to filter SAX events.
 817    *
 818    * @return the SAX filter being used or null if no SAX filter is installed
 819    */
 820  5792 public XMLFilter getXMLFilter() {
 821  5792 return xmlFilter;
 822    }
 823   
 824    /**
 825    * Sets the SAX filter to be used when filtering SAX events
 826    *
 827    * @param filter
 828    * is the SAX filter to use or null to disable filtering
 829    */
 830  0 public void setXMLFilter(XMLFilter filter) {
 831  0 this.xmlFilter = filter;
 832    }
 833   
 834    // Implementation methods
 835    // -------------------------------------------------------------------------
 836   
 837    /**
 838    * Installs any XMLFilter objects required to allow the SAX event stream to
 839    * be filtered and preprocessed before it gets to dom4j.
 840    *
 841    * @param reader
 842    * DOCUMENT ME!
 843    *
 844    * @return the new XMLFilter if applicable or the original XMLReader if no
 845    * filter is being used.
 846    */
 847  5792 protected XMLReader installXMLFilter(XMLReader reader) {
 848  5792 XMLFilter filter = getXMLFilter();
 849   
 850  5792 if (filter != null) {
 851    // find the root XMLFilter
 852  0 XMLFilter root = filter;
 853   
 854  0 while (true) {
 855  0 XMLReader parent = root.getParent();
 856   
 857  0 if (parent instanceof XMLFilter) {
 858  0 root = (XMLFilter) parent;
 859    } else {
 860  0 break;
 861    }
 862    }
 863   
 864  0 root.setParent(reader);
 865   
 866  0 return filter;
 867    }
 868   
 869  5792 return reader;
 870    }
 871   
 872  21 protected DispatchHandler getDispatchHandler() {
 873  21 if (dispatchHandler == null) {
 874  21 dispatchHandler = new DispatchHandler();
 875    }
 876   
 877  21 return dispatchHandler;
 878    }
 879   
 880  0 protected void setDispatchHandler(DispatchHandler dispatchHandler) {
 881  0 this.dispatchHandler = dispatchHandler;
 882    }
 883   
 884    /**
 885    * Factory Method to allow alternate methods of creating and configuring
 886    * XMLReader objects
 887    *
 888    * @return DOCUMENT ME!
 889    *
 890    * @throws SAXException
 891    * DOCUMENT ME!
 892    */
 893  5764 protected XMLReader createXMLReader() throws SAXException {
 894  5764 return SAXHelper.createXMLReader(isValidating());
 895    }
 896   
 897    /**
 898    * Configures the XMLReader before use
 899    *
 900    * @param reader
 901    * DOCUMENT ME!
 902    * @param handler
 903    * DOCUMENT ME!
 904    *
 905    * @throws DocumentException
 906    * DOCUMENT ME!
 907    */
 908  5792 protected void configureReader(XMLReader reader, DefaultHandler handler)
 909    throws DocumentException {
 910    // configure lexical handling
 911  5792 SAXHelper.setParserProperty(reader, SAX_LEXICALHANDLER, handler);
 912   
 913    // try alternate property just in case
 914  5792 SAXHelper.setParserProperty(reader, SAX_LEXICAL_HANDLER, handler);
 915   
 916    // register the DeclHandler
 917  5792 if (includeInternalDTDDeclarations || includeExternalDTDDeclarations) {
 918  6 SAXHelper.setParserProperty(reader, SAX_DECL_HANDLER, handler);
 919    }
 920   
 921    // configure namespace support
 922  5792 SAXHelper.setParserFeature(reader, SAX_NAMESPACES, true);
 923   
 924  5792 SAXHelper.setParserFeature(reader, SAX_NAMESPACE_PREFIXES, false);
 925   
 926    // string interning
 927  5792 SAXHelper.setParserFeature(reader, SAX_STRING_INTERNING,
 928    isStringInternEnabled());
 929   
 930    // external entites
 931    /*
 932    * SAXHelper.setParserFeature( reader,
 933    * "http://xml.org/sax/properties/external-general-entities",
 934    * includeExternalGeneralEntities ); SAXHelper.setParserFeature( reader,
 935    * "http://xml.org/sax/properties/external-parameter-entities",
 936    * includeExternalParameterEntities );
 937    */
 938    // use Locator2 if possible
 939  5792 SAXHelper.setParserFeature(reader,
 940    "http://xml.org/sax/features/use-locator2", true);
 941   
 942  5792 try {
 943    // configure validation support
 944  5792 reader.setFeature("http://xml.org/sax/features/validation",
 945    isValidating());
 946   
 947  5792 if (errorHandler != null) {
 948  0 reader.setErrorHandler(errorHandler);
 949    } else {
 950  5792 reader.setErrorHandler(handler);
 951    }
 952    } catch (Exception e) {
 953  0 if (isValidating()) {
 954  0 throw new DocumentException("Validation not supported for"
 955    + " XMLReader: " + reader, e);
 956    }
 957    }
 958    }
 959   
 960    /**
 961    * Factory Method to allow user derived SAXContentHandler objects to be used
 962    *
 963    * @param reader
 964    * DOCUMENT ME!
 965    *
 966    * @return DOCUMENT ME!
 967    */
 968  5792 protected SAXContentHandler createContentHandler(XMLReader reader) {
 969  5792 return new SAXContentHandler(getDocumentFactory(), dispatchHandler);
 970    }
 971   
 972  5762 protected EntityResolver createDefaultEntityResolver(String systemId) {
 973  5762 String prefix = null;
 974   
 975  5762 if ((systemId != null) && (systemId.length() > 0)) {
 976  179 int idx = systemId.lastIndexOf('/');
 977   
 978  179 if (idx > 0) {
 979  178 prefix = systemId.substring(0, idx + 1);
 980    }
 981    }
 982   
 983  5762 return new SAXEntityResolver(prefix);
 984    }
 985   
 986    protected static class SAXEntityResolver implements EntityResolver,
 987    Serializable {
 988    protected String uriPrefix;
 989   
 990  5762 public SAXEntityResolver(String uriPrefix) {
 991  5762 this.uriPrefix = uriPrefix;
 992    }
 993   
 994  5 public InputSource resolveEntity(String publicId, String systemId) {
 995    // try create a relative URI reader...
 996  5 if ((systemId != null) && (systemId.length() > 0)) {
 997  5 if ((uriPrefix != null) && (systemId.indexOf(':') <= 0)) {
 998  2 systemId = uriPrefix + systemId;
 999    }
 1000    }
 1001   
 1002  5 return new InputSource(systemId);
 1003    }
 1004    }
 1005    }
 1006   
 1007    /*
 1008    * Redistribution and use of this software and associated documentation
 1009    * ("Software"), with or without modification, are permitted provided that the
 1010    * following conditions are met:
 1011    *
 1012    * 1. Redistributions of source code must retain copyright statements and
 1013    * notices. Redistributions must also contain a copy of this document.
 1014    *
 1015    * 2. Redistributions in binary form must reproduce the above copyright notice,
 1016    * this list of conditions and the following disclaimer in the documentation
 1017    * and/or other materials provided with the distribution.
 1018    *
 1019    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 1020    * from this Software without prior written permission of MetaStuff, Ltd. For
 1021    * written permission, please contact dom4j-info@metastuff.com.
 1022    *
 1023    * 4. Products derived from this Software may not be called "DOM4J" nor may
 1024    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 1025    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 1026    *
 1027    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 1028    *
 1029    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 1030    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 1031    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 1032    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 1033    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 1034    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 1035    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 1036    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 1037    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 1038    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 1039    * POSSIBILITY OF SUCH DAMAGE.
 1040    *
 1041    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 1042    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/SAXModifyContentHandler.html0000644000175000017500000023722710242117733024060 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 287   Methods: 27
NCLOC: 180   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
SAXModifyContentHandler.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.io.IOException;
 11   
 12    import org.dom4j.DocumentFactory;
 13    import org.dom4j.Element;
 14    import org.dom4j.ElementHandler;
 15   
 16    import org.xml.sax.Attributes;
 17    import org.xml.sax.Locator;
 18    import org.xml.sax.SAXException;
 19   
 20    /**
 21    * This extension of the SAXContentHandler writes SAX events immediately to the
 22    * provided XMLWriter, unless some {@link org.dom4.ElementHandler}is still
 23    * handling the current Element.
 24    *
 25    * @author Wonne Keysers (Realsoftware.be)
 26    *
 27    * @see org.dom4j.io.SAXContentHandler
 28    */
 29    class SAXModifyContentHandler extends SAXContentHandler {
 30    private XMLWriter xmlWriter;
 31   
 32  0 public SAXModifyContentHandler() {
 33    }
 34   
 35  0 public SAXModifyContentHandler(DocumentFactory documentFactory) {
 36  0 super(documentFactory);
 37    }
 38   
 39  0 public SAXModifyContentHandler(DocumentFactory documentFactory,
 40    ElementHandler elementHandler) {
 41  0 super(documentFactory, elementHandler);
 42    }
 43   
 44  0 public SAXModifyContentHandler(DocumentFactory documentFactory,
 45    ElementHandler elementHandler, ElementStack elementStack) {
 46  0 super(documentFactory, elementHandler, elementStack);
 47    }
 48   
 49  0 public void setXMLWriter(XMLWriter writer) {
 50  0 this.xmlWriter = writer;
 51    }
 52   
 53  0 public void startCDATA() throws SAXException {
 54  0 super.startCDATA();
 55   
 56  0 if (!activeHandlers() && (xmlWriter != null)) {
 57  0 xmlWriter.startCDATA();
 58    }
 59    }
 60   
 61  0 public void startDTD(String name, String publicId, String systemId)
 62    throws SAXException {
 63  0 super.startDTD(name, publicId, systemId);
 64   
 65  0 if (xmlWriter != null) {
 66  0 xmlWriter.startDTD(name, publicId, systemId);
 67    }
 68    }
 69   
 70  0 public void endDTD() throws org.xml.sax.SAXException {
 71  0 super.endDTD();
 72   
 73  0 if (xmlWriter != null) {
 74  0 xmlWriter.endDTD();
 75    }
 76    }
 77   
 78  0 public void comment(char[] characters, int parm2, int parm3)
 79    throws SAXException {
 80  0 super.comment(characters, parm2, parm3);
 81   
 82  0 if (!activeHandlers() && (xmlWriter != null)) {
 83  0 xmlWriter.comment(characters, parm2, parm3);
 84    }
 85    }
 86   
 87  0 public void startEntity(String name) throws SAXException {
 88  0 super.startEntity(name);
 89   
 90  0 if (xmlWriter != null) {
 91  0 xmlWriter.startEntity(name);
 92    }
 93    }
 94   
 95  0 public void endCDATA() throws org.xml.sax.SAXException {
 96  0 super.endCDATA();
 97   
 98  0 if (!activeHandlers() && (xmlWriter != null)) {
 99  0 xmlWriter.endCDATA();
 100    }
 101    }
 102   
 103  0 public void endEntity(String name) throws SAXException {
 104  0 super.endEntity(name);
 105   
 106  0 if (xmlWriter != null) {
 107  0 xmlWriter.endEntity(name);
 108    }
 109    }
 110   
 111  0 public void unparsedEntityDecl(String name, String publicId,
 112    String systemId, String notation) throws SAXException {
 113  0 super.unparsedEntityDecl(name, publicId, systemId, notation);
 114   
 115  0 if (!activeHandlers() && (xmlWriter != null)) {
 116  0 xmlWriter.unparsedEntityDecl(name, publicId, systemId, notation);
 117    }
 118    }
 119   
 120  0 public void notationDecl(String name, String publicId, String systemId)
 121    throws SAXException {
 122  0 super.notationDecl(name, publicId, systemId);
 123   
 124  0 if (xmlWriter != null) {
 125  0 xmlWriter.notationDecl(name, publicId, systemId);
 126    }
 127    }
 128   
 129  0 public void startElement(String uri, String localName, String qName,
 130    Attributes atts) throws SAXException {
 131  0 super.startElement(uri, localName, qName, atts);
 132   
 133  0 if (!activeHandlers() && (xmlWriter != null)) {
 134  0 xmlWriter.startElement(uri, localName, qName, atts);
 135    }
 136    }
 137   
 138  0 public void startDocument() throws SAXException {
 139  0 super.startDocument();
 140   
 141  0 if (xmlWriter != null) {
 142  0 xmlWriter.startDocument();
 143    }
 144    }
 145   
 146  0 public void ignorableWhitespace(char[] parm1, int parm2, int parm3)
 147    throws SAXException {
 148  0 super.ignorableWhitespace(parm1, parm2, parm3);
 149   
 150  0 if (!activeHandlers() && (xmlWriter != null)) {
 151  0 xmlWriter.ignorableWhitespace(parm1, parm2, parm3);
 152    }
 153    }
 154   
 155  0 public void processingInstruction(String target, String data)
 156    throws SAXException {
 157  0 super.processingInstruction(target, data);
 158   
 159  0 if (!activeHandlers() && (xmlWriter != null)) {
 160  0 xmlWriter.processingInstruction(target, data);
 161    }
 162    }
 163   
 164  0 public void setDocumentLocator(Locator locator) {
 165  0 super.setDocumentLocator(locator);
 166   
 167  0 if (xmlWriter != null) {
 168  0 xmlWriter.setDocumentLocator(locator);
 169    }
 170    }
 171   
 172  0 public void skippedEntity(String name) throws SAXException {
 173  0 super.skippedEntity(name);
 174   
 175  0 if (!activeHandlers() && (xmlWriter != null)) {
 176  0 xmlWriter.skippedEntity(name);
 177    }
 178    }
 179   
 180  0 public void endDocument() throws SAXException {
 181  0 super.endDocument();
 182   
 183  0 if (xmlWriter != null) {
 184  0 xmlWriter.endDocument();
 185    }
 186    }
 187   
 188  0 public void startPrefixMapping(String prefix, String uri)
 189    throws SAXException {
 190  0 super.startPrefixMapping(prefix, uri);
 191   
 192  0 if (xmlWriter != null) {
 193  0 xmlWriter.startPrefixMapping(prefix, uri);
 194    }
 195    }
 196   
 197  0 public void endElement(String uri, String localName, String qName)
 198    throws SAXException {
 199  0 ElementHandler currentHandler = getElementStack().getDispatchHandler()
 200    .getHandler(getElementStack().getPath());
 201   
 202  0 super.endElement(uri, localName, qName);
 203   
 204  0 if (!activeHandlers()) {
 205  0 if (xmlWriter != null) {
 206  0 if (currentHandler == null) {
 207  0 xmlWriter.endElement(uri, localName, qName);
 208  0 } else if (currentHandler instanceof SAXModifyElementHandler) {
 209  0 SAXModifyElementHandler modifyHandler
 210    = (SAXModifyElementHandler) currentHandler;
 211  0 Element modifiedElement = modifyHandler
 212    .getModifiedElement();
 213   
 214  0 try {
 215  0 xmlWriter.write(modifiedElement);
 216    } catch (IOException ex) {
 217  0 throw new SAXModifyException(ex);
 218    }
 219    }
 220    }
 221    }
 222    }
 223   
 224  0 public void endPrefixMapping(String prefix) throws SAXException {
 225  0 super.endPrefixMapping(prefix);
 226   
 227  0 if (xmlWriter != null) {
 228  0 xmlWriter.endPrefixMapping(prefix);
 229    }
 230    }
 231   
 232  0 public void characters(char[] parm1, int parm2, int parm3)
 233    throws SAXException {
 234  0 super.characters(parm1, parm2, parm3);
 235   
 236  0 if (!activeHandlers() && (xmlWriter != null)) {
 237  0 xmlWriter.characters(parm1, parm2, parm3);
 238    }
 239    }
 240   
 241  0 protected XMLWriter getXMLWriter() {
 242  0 return this.xmlWriter;
 243    }
 244   
 245  0 private boolean activeHandlers() {
 246  0 DispatchHandler handler = getElementStack().getDispatchHandler();
 247   
 248  0 return handler.getActiveHandlerCount() > 0;
 249    }
 250    }
 251   
 252    /*
 253    * Redistribution and use of this software and associated documentation
 254    * ("Software"), with or without modification, are permitted provided that the
 255    * following conditions are met:
 256    *
 257    * 1. Redistributions of source code must retain copyright statements and
 258    * notices. Redistributions must also contain a copy of this document.
 259    *
 260    * 2. Redistributions in binary form must reproduce the above copyright notice,
 261    * this list of conditions and the following disclaimer in the documentation
 262    * and/or other materials provided with the distribution.
 263    *
 264    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 265    * from this Software without prior written permission of MetaStuff, Ltd. For
 266    * written permission, please contact dom4j-info@metastuff.com.
 267    *
 268    * 4. Products derived from this Software may not be called "DOM4J" nor may
 269    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 270    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 271    *
 272    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 273    *
 274    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 275    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 276    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 277    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 278    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 279    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 280    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 281    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 282    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 283    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 284    * POSSIBILITY OF SUCH DAMAGE.
 285    *
 286    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 287    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/PruningDispatchHandler.html0000644000175000017500000004632110242117755024021 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 64   Methods: 1
NCLOC: 10   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
PruningDispatchHandler.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import org.dom4j.ElementPath;
 11   
 12    /**
 13    * This extension on the {@link DispatchHandler}prunes the current {@link
 14    * org.dom4j.Element} when there are no {@link ElementHandler}objects active
 15    * the element.
 16    *
 17    * @author Wonne keysers (Realsoftware)
 18    */
 19    class PruningDispatchHandler extends DispatchHandler {
 20  0 public void onEnd(ElementPath elementPath) {
 21  0 super.onEnd(elementPath);
 22   
 23  0 if (getActiveHandlerCount() == 0) {
 24  0 elementPath.getCurrent().detach();
 25    }
 26    }
 27    }
 28   
 29    /*
 30    * Redistribution and use of this software and associated documentation
 31    * ("Software"), with or without modification, are permitted provided that the
 32    * following conditions are met:
 33    *
 34    * 1. Redistributions of source code must retain copyright statements and
 35    * notices. Redistributions must also contain a copy of this document.
 36    *
 37    * 2. Redistributions in binary form must reproduce the above copyright notice,
 38    * this list of conditions and the following disclaimer in the documentation
 39    * and/or other materials provided with the distribution.
 40    *
 41    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 42    * from this Software without prior written permission of MetaStuff, Ltd. For
 43    * written permission, please contact dom4j-info@metastuff.com.
 44    *
 45    * 4. Products derived from this Software may not be called "DOM4J" nor may
 46    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 47    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 48    *
 49    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 50    *
 51    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 52    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 53    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 54    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 55    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 56    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 57    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 58    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 59    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 60    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 61    * POSSIBILITY OF SUCH DAMAGE.
 62    *
 63    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 64    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/ElementStack.html0000644000175000017500000016630110242117751021775 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 218   Methods: 17
NCLOC: 92   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
ElementStack.java 28,6% 32,5% 47,1% 35,2%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import org.dom4j.Element;
 11    import org.dom4j.ElementHandler;
 12    import org.dom4j.ElementPath;
 13   
 14    /**
 15    * <p>
 16    * <code>ElementStack</code> is used internally inside the {@link
 17    * SAXContentHandler} to maintain a stack of {@link Element}instances. It opens
 18    * an integration possibility allowing derivations to prune the tree when a node
 19    * is complete.
 20    * </p>
 21    *
 22    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 23    * @version $Revision: 1.14 $
 24    */
 25    class ElementStack implements ElementPath {
 26    /** stack of <code>Element</code> objects */
 27    protected Element[] stack;
 28   
 29    /** index of the item at the top of the stack or -1 if the stack is empty */
 30    protected int lastElementIndex = -1;
 31   
 32    private DispatchHandler handler = null;
 33   
 34  5811 public ElementStack() {
 35  5811 this(50);
 36    }
 37   
 38  5811 public ElementStack(int defaultCapacity) {
 39  5811 stack = new Element[defaultCapacity];
 40    }
 41   
 42  18 public void setDispatchHandler(DispatchHandler dispatchHandler) {
 43  18 this.handler = dispatchHandler;
 44    }
 45   
 46  0 public DispatchHandler getDispatchHandler() {
 47  0 return this.handler;
 48    }
 49   
 50    /**
 51    * Peeks at the top element on the stack without changing the contents of
 52    * the stack.
 53    */
 54  11628 public void clear() {
 55  11628 lastElementIndex = -1;
 56    }
 57   
 58    /**
 59    * Peeks at the top element on the stack without changing the contents of
 60    * the stack.
 61    *
 62    * @return the current element on the stack
 63    */
 64  86859 public Element peekElement() {
 65  86859 if (lastElementIndex < 0) {
 66  5814 return null;
 67    }
 68   
 69  81045 return stack[lastElementIndex];
 70    }
 71   
 72    /**
 73    * Pops the element off the stack
 74    *
 75    * @return the element that has just been popped off the stack
 76    */
 77  86721 public Element popElement() {
 78  86721 if (lastElementIndex < 0) {
 79  0 return null;
 80    }
 81   
 82  86721 return stack[lastElementIndex--];
 83    }
 84   
 85    /**
 86    * Pushes a new element onto the stack
 87    *
 88    * @param element
 89    * DOCUMENT ME!
 90    */
 91  86721 public void pushElement(Element element) {
 92  86721 int length = stack.length;
 93   
 94  86721 if (++lastElementIndex >= length) {
 95  0 reallocate(length * 2);
 96    }
 97   
 98  86721 stack[lastElementIndex] = element;
 99    }
 100   
 101    /**
 102    * Reallocates the stack to the given size
 103    *
 104    * @param size
 105    * DOCUMENT ME!
 106    */
 107  0 protected void reallocate(int size) {
 108  0 Element[] oldStack = stack;
 109  0 stack = new Element[size];
 110  0 System.arraycopy(oldStack, 0, stack, 0, oldStack.length);
 111    }
 112   
 113    // The ElementPath Interface
 114    //
 115  0 public int size() {
 116  0 return lastElementIndex + 1;
 117    }
 118   
 119  0 public Element getElement(int depth) {
 120  0 Element element;
 121   
 122  0 try {
 123  0 element = (Element) stack[depth];
 124    } catch (ArrayIndexOutOfBoundsException e) {
 125  0 element = null;
 126    }
 127   
 128  0 return element;
 129    }
 130   
 131  0 public String getPath() {
 132  0 if (handler == null) {
 133  0 setDispatchHandler(new DispatchHandler());
 134    }
 135   
 136  0 return handler.getPath();
 137    }
 138   
 139  138 public Element getCurrent() {
 140  138 return peekElement();
 141    }
 142   
 143  0 public void addHandler(String path, ElementHandler elementHandler) {
 144  0 this.handler.addHandler(getHandlerPath(path), elementHandler);
 145    }
 146   
 147  0 public void removeHandler(String path) {
 148  0 this.handler.removeHandler(getHandlerPath(path));
 149    }
 150   
 151    /**
 152    * DOCUMENT ME!
 153    *
 154    * @param path
 155    * DOCUMENT ME!
 156    *
 157    * @return true when an <code>ElementHandler</code> is registered for the
 158    * specified path.
 159    */
 160  0 public boolean containsHandler(String path) {
 161  0 return this.handler.containsHandler(path);
 162    }
 163   
 164  0 private String getHandlerPath(String path) {
 165  0 String handlerPath;
 166   
 167  0 if (this.handler == null) {
 168  0 setDispatchHandler(new DispatchHandler());
 169    }
 170   
 171  0 if (path.startsWith("/")) {
 172  0 handlerPath = path;
 173  0 } else if (getPath().equals("/")) {
 174  0 handlerPath = getPath() + path;
 175    } else {
 176  0 handlerPath = getPath() + "/" + path;
 177    }
 178   
 179  0 return handlerPath;
 180    }
 181    }
 182   
 183    /*
 184    * Redistribution and use of this software and associated documentation
 185    * ("Software"), with or without modification, are permitted provided that the
 186    * following conditions are met:
 187    *
 188    * 1. Redistributions of source code must retain copyright statements and
 189    * notices. Redistributions must also contain a copy of this document.
 190    *
 191    * 2. Redistributions in binary form must reproduce the above copyright notice,
 192    * this list of conditions and the following disclaimer in the documentation
 193    * and/or other materials provided with the distribution.
 194    *
 195    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 196    * from this Software without prior written permission of MetaStuff, Ltd. For
 197    * written permission, please contact dom4j-info@metastuff.com.
 198    *
 199    * 4. Products derived from this Software may not be called "DOM4J" nor may
 200    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 201    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 202    *
 203    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 204    *
 205    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 206    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 207    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 208    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 209    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 210    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 211    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 212    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 213    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 214    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 215    * POSSIBILITY OF SUCH DAMAGE.
 216    *
 217    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 218    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/SAXWriter.html0000644000175000017500000076313410242117726021257 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 945   Methods: 48
NCLOC: 436   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
SAXWriter.java 65,5% 62,2% 66,7% 63,6%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.io.IOException;
 11    import java.util.HashMap;
 12    import java.util.Iterator;
 13    import java.util.List;
 14    import java.util.Map;
 15   
 16    import org.dom4j.Attribute;
 17    import org.dom4j.Branch;
 18    import org.dom4j.CDATA;
 19    import org.dom4j.CharacterData;
 20    import org.dom4j.Comment;
 21    import org.dom4j.Document;
 22    import org.dom4j.DocumentType;
 23    import org.dom4j.Element;
 24    import org.dom4j.Entity;
 25    import org.dom4j.Namespace;
 26    import org.dom4j.Node;
 27    import org.dom4j.ProcessingInstruction;
 28    import org.dom4j.Text;
 29    import org.dom4j.tree.NamespaceStack;
 30   
 31    import org.xml.sax.Attributes;
 32    import org.xml.sax.ContentHandler;
 33    import org.xml.sax.DTDHandler;
 34    import org.xml.sax.EntityResolver;
 35    import org.xml.sax.ErrorHandler;
 36    import org.xml.sax.InputSource;
 37    import org.xml.sax.SAXException;
 38    import org.xml.sax.SAXNotRecognizedException;
 39    import org.xml.sax.SAXNotSupportedException;
 40    import org.xml.sax.XMLReader;
 41    import org.xml.sax.ext.LexicalHandler;
 42    import org.xml.sax.helpers.AttributesImpl;
 43    import org.xml.sax.helpers.LocatorImpl;
 44   
 45    /**
 46    * <p>
 47    * <code>SAXWriter</code> writes a DOM4J tree to a SAX ContentHandler.
 48    * </p>
 49    *
 50    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 51    * @version $Revision: 1.24 $
 52    */
 53    public class SAXWriter implements XMLReader {
 54    protected static final String[] LEXICAL_HANDLER_NAMES = {
 55    "http://xml.org/sax/properties/lexical-handler",
 56    "http://xml.org/sax/handlers/LexicalHandler" };
 57   
 58    protected static final String FEATURE_NAMESPACE_PREFIXES
 59    = "http://xml.org/sax/features/namespace-prefixes";
 60   
 61    protected static final String FEATURE_NAMESPACES
 62    = "http://xml.org/sax/features/namespaces";
 63   
 64    /** <code>ContentHandler</code> to which SAX events are raised */
 65    private ContentHandler contentHandler;
 66   
 67    /** <code>DTDHandler</code> fired when a document has a DTD */
 68    private DTDHandler dtdHandler;
 69   
 70    /** <code>EntityResolver</code> fired when a document has a DTD */
 71    private EntityResolver entityResolver;
 72   
 73    private ErrorHandler errorHandler;
 74   
 75    /** <code>LexicalHandler</code> fired on Entity and CDATA sections */
 76    private LexicalHandler lexicalHandler;
 77   
 78    /** <code>AttributesImpl</code> used when generating the Attributes */
 79    private AttributesImpl attributes = new AttributesImpl();
 80   
 81    /** Stores the features */
 82    private Map features = new HashMap();
 83   
 84    /** Stores the properties */
 85    private Map properties = new HashMap();
 86   
 87    /** Whether namespace declarations are exported as attributes or not */
 88    private boolean declareNamespaceAttributes;
 89   
 90  20 public SAXWriter() {
 91  20 properties.put(FEATURE_NAMESPACE_PREFIXES, Boolean.FALSE);
 92  20 properties.put(FEATURE_NAMESPACE_PREFIXES, Boolean.TRUE);
 93    }
 94   
 95  0 public SAXWriter(ContentHandler contentHandler) {
 96  0 this();
 97  0 this.contentHandler = contentHandler;
 98    }
 99   
 100  0 public SAXWriter(ContentHandler contentHandler,
 101    LexicalHandler lexicalHandler) {
 102  0 this();
 103  0 this.contentHandler = contentHandler;
 104  0 this.lexicalHandler = lexicalHandler;
 105    }
 106   
 107  12 public SAXWriter(ContentHandler contentHandler,
 108    LexicalHandler lexicalHandler, EntityResolver entityResolver) {
 109  12 this();
 110  12 this.contentHandler = contentHandler;
 111  12 this.lexicalHandler = lexicalHandler;
 112  12 this.entityResolver = entityResolver;
 113    }
 114   
 115    /**
 116    * A polymorphic method to write any Node to this SAX stream
 117    *
 118    * @param node
 119    * DOCUMENT ME!
 120    *
 121    * @throws SAXException
 122    * DOCUMENT ME!
 123    */
 124  39 public void write(Node node) throws SAXException {
 125  39 int nodeType = node.getNodeType();
 126   
 127  39 switch (nodeType) {
 128  0 case Node.ELEMENT_NODE:
 129  0 write((Element) node);
 130   
 131  0 break;
 132   
 133  0 case Node.ATTRIBUTE_NODE:
 134  0 write((Attribute) node);
 135   
 136  0 break;
 137   
 138  0 case Node.TEXT_NODE:
 139  0 write(node.getText());
 140   
 141  0 break;
 142   
 143  0 case Node.CDATA_SECTION_NODE:
 144  0 write((CDATA) node);
 145   
 146  0 break;
 147   
 148  0 case Node.ENTITY_REFERENCE_NODE:
 149  0 write((Entity) node);
 150   
 151  0 break;
 152   
 153  0 case Node.PROCESSING_INSTRUCTION_NODE:
 154  0 write((ProcessingInstruction) node);
 155   
 156  0 break;
 157   
 158  0 case Node.COMMENT_NODE:
 159  0 write((Comment) node);
 160   
 161  0 break;
 162   
 163  0 case Node.DOCUMENT_NODE:
 164  0 write((Document) node);
 165   
 166  0 break;
 167   
 168  0 case Node.DOCUMENT_TYPE_NODE:
 169  0 write((DocumentType) node);
 170   
 171  0 break;
 172   
 173  39 case Node.NAMESPACE_NODE:
 174   
 175    // Will be output with attributes
 176    // write((Namespace) node);
 177  39 break;
 178   
 179  0 default:
 180  0 throw new SAXException("Invalid node type: " + node);
 181    }
 182    }
 183   
 184    /**
 185    * Generates SAX events for the given Document and all its content
 186    *
 187    * @param document
 188    * is the Document to parse
 189    *
 190    * @throws SAXException
 191    * if there is a SAX error processing the events
 192    */
 193  20 public void write(Document document) throws SAXException {
 194  20 if (document != null) {
 195  20 checkForNullHandlers();
 196   
 197  20 documentLocator(document);
 198  20 startDocument();
 199  20 entityResolver(document);
 200  20 dtdHandler(document);
 201   
 202  20 writeContent(document, new NamespaceStack());
 203  20 endDocument();
 204    }
 205    }
 206   
 207    /**
 208    * Generates SAX events for the given Element and all its content
 209    *
 210    * @param element
 211    * is the Element to parse
 212    *
 213    * @throws SAXException
 214    * if there is a SAX error processing the events
 215    */
 216  0 public void write(Element element) throws SAXException {
 217  0 write(element, new NamespaceStack());
 218    }
 219   
 220    /**
 221    * <p>
 222    * Writes the opening tag of an {@link Element}, including its {@link
 223    * Attribute}s but without its content.
 224    * </p>
 225    *
 226    * @param element
 227    * <code>Element</code> to output.
 228    *
 229    * @throws SAXException
 230    * DOCUMENT ME!
 231    */
 232  0 public void writeOpen(Element element) throws SAXException {
 233  0 startElement(element, null);
 234    }
 235   
 236    /**
 237    * <p>
 238    * Writes the closing tag of an {@link Element}
 239    * </p>
 240    *
 241    * @param element
 242    * <code>Element</code> to output.
 243    *
 244    * @throws SAXException
 245    * DOCUMENT ME!
 246    */
 247  0 public void writeClose(Element element) throws SAXException {
 248  0 endElement(element);
 249    }
 250   
 251    /**
 252    * Generates SAX events for the given text
 253    *
 254    * @param text
 255    * is the text to send to the SAX ContentHandler
 256    *
 257    * @throws SAXException
 258    * if there is a SAX error processing the events
 259    */
 260  12162 public void write(String text) throws SAXException {
 261  12162 if (text != null) {
 262  12162 char[] chars = text.toCharArray();
 263  12162 contentHandler.characters(chars, 0, chars.length);
 264    }
 265    }
 266   
 267    /**
 268    * Generates SAX events for the given CDATA
 269    *
 270    * @param cdata
 271    * is the CDATA to parse
 272    *
 273    * @throws SAXException
 274    * if there is a SAX error processing the events
 275    */
 276  30 public void write(CDATA cdata) throws SAXException {
 277  30 String text = cdata.getText();
 278   
 279  30 if (lexicalHandler != null) {
 280  30 lexicalHandler.startCDATA();
 281  30 write(text);
 282  30 lexicalHandler.endCDATA();
 283    } else {
 284  0 write(text);
 285    }
 286    }
 287   
 288    /**
 289    * Generates SAX events for the given Comment
 290    *
 291    * @param comment
 292    * is the Comment to parse
 293    *
 294    * @throws SAXException
 295    * if there is a SAX error processing the events
 296    */
 297  71 public void write(Comment comment) throws SAXException {
 298  71 if (lexicalHandler != null) {
 299  71 String text = comment.getText();
 300  71 char[] chars = text.toCharArray();
 301  71 lexicalHandler.comment(chars, 0, chars.length);
 302    }
 303    }
 304   
 305    /**
 306    * Generates SAX events for the given Entity
 307    *
 308    * @param entity
 309    * is the Entity to parse
 310    *
 311    * @throws SAXException
 312    * if there is a SAX error processing the events
 313    */
 314  0 public void write(Entity entity) throws SAXException {
 315  0 String text = entity.getText();
 316   
 317  0 if (lexicalHandler != null) {
 318  0 String name = entity.getName();
 319  0 lexicalHandler.startEntity(name);
 320  0 write(text);
 321  0 lexicalHandler.endEntity(name);
 322    } else {
 323  0 write(text);
 324    }
 325    }
 326   
 327    /**
 328    * Generates SAX events for the given ProcessingInstruction
 329    *
 330    * @param pi
 331    * is the ProcessingInstruction to parse
 332    *
 333    * @throws SAXException
 334    * if there is a SAX error processing the events
 335    */
 336  2 public void write(ProcessingInstruction pi) throws SAXException {
 337  2 String target = pi.getTarget();
 338  2 String text = pi.getText();
 339  2 contentHandler.processingInstruction(target, text);
 340    }
 341   
 342    /**
 343    * Should namespace declarations be converted to "xmlns" attributes. This
 344    * property defaults to <code>false</code> as per the SAX specification.
 345    * This property is set via the SAX feature
 346    * "http://xml.org/sax/features/namespace-prefixes"
 347    *
 348    * @return DOCUMENT ME!
 349    */
 350  0 public boolean isDeclareNamespaceAttributes() {
 351  0 return declareNamespaceAttributes;
 352    }
 353   
 354    /**
 355    * Sets whether namespace declarations should be exported as "xmlns"
 356    * attributes or not. This property is set from the SAX feature
 357    * "http://xml.org/sax/features/namespace-prefixes"
 358    *
 359    * @param declareNamespaceAttrs
 360    * DOCUMENT ME!
 361    */
 362  8 public void setDeclareNamespaceAttributes(boolean declareNamespaceAttrs) {
 363  8 this.declareNamespaceAttributes = declareNamespaceAttrs;
 364    }
 365   
 366    // XMLReader methods
 367    // -------------------------------------------------------------------------
 368   
 369    /**
 370    * DOCUMENT ME!
 371    *
 372    * @return the <code>ContentHandler</code> called when SAX events are
 373    * raised
 374    */
 375  0 public ContentHandler getContentHandler() {
 376  0 return contentHandler;
 377    }
 378   
 379    /**
 380    * Sets the <code>ContentHandler</code> called when SAX events are raised
 381    *
 382    * @param contentHandler
 383    * is the <code>ContentHandler</code> called when SAX events
 384    * are raised
 385    */
 386  8 public void setContentHandler(ContentHandler contentHandler) {
 387  8 this.contentHandler = contentHandler;
 388    }
 389   
 390    /**
 391    * DOCUMENT ME!
 392    *
 393    * @return the <code>DTDHandler</code>
 394    */
 395  0 public DTDHandler getDTDHandler() {
 396  0 return dtdHandler;
 397    }
 398   
 399    /**
 400    * Sets the <code>DTDHandler</code>.
 401    *
 402    * @param handler
 403    * DOCUMENT ME!
 404    */
 405  8 public void setDTDHandler(DTDHandler handler) {
 406  8 this.dtdHandler = handler;
 407    }
 408   
 409    /**
 410    * DOCUMENT ME!
 411    *
 412    * @return the <code>ErrorHandler</code>
 413    */
 414  1 public ErrorHandler getErrorHandler() {
 415  1 return errorHandler;
 416    }
 417   
 418    /**
 419    * Sets the <code>ErrorHandler</code>.
 420    *
 421    * @param errorHandler
 422    * DOCUMENT ME!
 423    */
 424  1 public void setErrorHandler(ErrorHandler errorHandler) {
 425  1 this.errorHandler = errorHandler;
 426    }
 427   
 428    /**
 429    * DOCUMENT ME!
 430    *
 431    * @return the <code>EntityResolver</code> used when a Document contains a
 432    * DTD
 433    */
 434  0 public EntityResolver getEntityResolver() {
 435  0 return entityResolver;
 436    }
 437   
 438    /**
 439    * Sets the <code>EntityResolver</code>.
 440    *
 441    * @param entityResolver
 442    * is the <code>EntityResolver</code>
 443    */
 444  0 public void setEntityResolver(EntityResolver entityResolver) {
 445  0 this.entityResolver = entityResolver;
 446    }
 447   
 448    /**
 449    * DOCUMENT ME!
 450    *
 451    * @return the <code>LexicalHandler</code> used when a Document contains a
 452    * DTD
 453    */
 454  0 public LexicalHandler getLexicalHandler() {
 455  0 return lexicalHandler;
 456    }
 457   
 458    /**
 459    * Sets the <code>LexicalHandler</code>.
 460    *
 461    * @param lexicalHandler
 462    * is the <code>LexicalHandler</code>
 463    */
 464  15 public void setLexicalHandler(LexicalHandler lexicalHandler) {
 465  15 this.lexicalHandler = lexicalHandler;
 466    }
 467   
 468    /**
 469    * Sets the <code>XMLReader</code> used to write SAX events to
 470    *
 471    * @param xmlReader
 472    * is the <code>XMLReader</code>
 473    */
 474  0 public void setXMLReader(XMLReader xmlReader) {
 475  0 setContentHandler(xmlReader.getContentHandler());
 476  0 setDTDHandler(xmlReader.getDTDHandler());
 477  0 setEntityResolver(xmlReader.getEntityResolver());
 478  0 setErrorHandler(xmlReader.getErrorHandler());
 479    }
 480   
 481    /**
 482    * Looks up the value of a feature.
 483    *
 484    * @param name
 485    * DOCUMENT ME!
 486    *
 487    * @return DOCUMENT ME!
 488    *
 489    * @throws SAXNotRecognizedException
 490    * DOCUMENT ME!
 491    * @throws SAXNotSupportedException
 492    * DOCUMENT ME!
 493    */
 494  0 public boolean getFeature(String name) throws SAXNotRecognizedException,
 495    SAXNotSupportedException {
 496  0 Boolean answer = (Boolean) features.get(name);
 497   
 498  0 return (answer != null) && answer.booleanValue();
 499    }
 500   
 501    /**
 502    * This implementation does actually use any features but just stores them
 503    * for later retrieval
 504    *
 505    * @param name
 506    * DOCUMENT ME!
 507    * @param value
 508    * DOCUMENT ME!
 509    *
 510    * @throws SAXNotRecognizedException
 511    * DOCUMENT ME!
 512    * @throws SAXNotSupportedException
 513    * DOCUMENT ME!
 514    */
 515  8 public void setFeature(String name, boolean value)
 516    throws SAXNotRecognizedException, SAXNotSupportedException {
 517  8 if (FEATURE_NAMESPACE_PREFIXES.equals(name)) {
 518  8 setDeclareNamespaceAttributes(value);
 519  0 } else if (FEATURE_NAMESPACE_PREFIXES.equals(name)) {
 520  0 if (!value) {
 521  0 String msg = "Namespace feature is always supported in dom4j";
 522  0 throw new SAXNotSupportedException(msg);
 523    }
 524    }
 525   
 526  8 features.put(name, (value) ? Boolean.TRUE : Boolean.FALSE);
 527    }
 528   
 529    /**
 530    * Sets the given SAX property
 531    *
 532    * @param name
 533    * DOCUMENT ME!
 534    * @param value
 535    * DOCUMENT ME!
 536    */
 537  29 public void setProperty(String name, Object value) {
 538  29 for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
 539  50 if (LEXICAL_HANDLER_NAMES[i].equals(name)) {
 540  15 setLexicalHandler((LexicalHandler) value);
 541   
 542  15 return;
 543    }
 544    }
 545   
 546  14 properties.put(name, value);
 547    }
 548   
 549    /**
 550    * Gets the given SAX property
 551    *
 552    * @param name
 553    * DOCUMENT ME!
 554    *
 555    * @return DOCUMENT ME!
 556    *
 557    * @throws SAXNotRecognizedException
 558    * DOCUMENT ME!
 559    * @throws SAXNotSupportedException
 560    * DOCUMENT ME!
 561    */
 562  0 public Object getProperty(String name) throws SAXNotRecognizedException,
 563    SAXNotSupportedException {
 564  0 for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
 565  0 if (LEXICAL_HANDLER_NAMES[i].equals(name)) {
 566  0 return getLexicalHandler();
 567    }
 568    }
 569   
 570  0 return properties.get(name);
 571    }
 572   
 573    /**
 574    * This method is not supported.
 575    *
 576    * @param systemId
 577    * DOCUMENT ME!
 578    *
 579    * @throws SAXNotSupportedException
 580    * DOCUMENT ME!
 581    */
 582  0 public void parse(String systemId) throws SAXNotSupportedException {
 583  0 throw new SAXNotSupportedException("This XMLReader can only accept"
 584    + " <dom4j> InputSource objects");
 585    }
 586   
 587    /**
 588    * Parses an XML document. This method can only accept DocumentInputSource
 589    * inputs otherwise a {@link SAXNotSupportedException}exception is thrown.
 590    *
 591    * @param input
 592    * DOCUMENT ME!
 593    *
 594    * @throws SAXException
 595    * DOCUMENT ME!
 596    * @throws SAXNotSupportedException
 597    * if the input source is not wrapping a dom4j document
 598    */
 599  8 public void parse(InputSource input) throws SAXException {
 600  8 if (input instanceof DocumentInputSource) {
 601  8 DocumentInputSource documentInput = (DocumentInputSource) input;
 602  8 Document document = documentInput.getDocument();
 603  8 write(document);
 604    } else {
 605  0 throw new SAXNotSupportedException(
 606    "This XMLReader can only accept "
 607    + "<dom4j> InputSource objects");
 608    }
 609    }
 610   
 611    // Implementation methods
 612    // -------------------------------------------------------------------------
 613  4973 protected void writeContent(Branch branch, NamespaceStack namespaceStack)
 614    throws SAXException {
 615  4973 for (Iterator iter = branch.nodeIterator(); iter.hasNext();) {
 616  17227 Object object = iter.next();
 617   
 618  17227 if (object instanceof Element) {
 619  4953 write((Element) object, namespaceStack);
 620  12274 } else if (object instanceof CharacterData) {
 621  12233 if (object instanceof Text) {
 622  12132 Text text = (Text) object;
 623  12132 write(text.getText());
 624  101 } else if (object instanceof CDATA) {
 625  30 write((CDATA) object);
 626  71 } else if (object instanceof Comment) {
 627  71 write((Comment) object);
 628    } else {
 629  0 throw new SAXException("Invalid Node in DOM4J content: "
 630    + object + " of type: " + object.getClass());
 631    }
 632  41 } else if (object instanceof String) {
 633  0 write((String) object);
 634  41 } else if (object instanceof Entity) {
 635  0 write((Entity) object);
 636  41 } else if (object instanceof ProcessingInstruction) {
 637  2 write((ProcessingInstruction) object);
 638  39 } else if (object instanceof Namespace) {
 639  39 write((Namespace) object);
 640    } else {
 641  0 throw new SAXException("Invalid Node in DOM4J content: "
 642    + object);
 643    }
 644    }
 645    }
 646   
 647    /**
 648    * The {@link org.xml.sax.Locator}is only really useful when parsing a
 649    * textual document as its main purpose is to identify the line and column
 650    * number. Since we are processing an in memory tree which will probably
 651    * have its line number information removed, we'll just use -1 for the line
 652    * and column numbers.
 653    *
 654    * @param document
 655    * DOCUMENT ME!
 656    *
 657    * @throws SAXException
 658    * DOCUMENT ME!
 659    */
 660  20 protected void documentLocator(Document document) throws SAXException {
 661  20 LocatorImpl locator = new LocatorImpl();
 662   
 663  20 String publicID = null;
 664  20 String systemID = null;
 665  20 DocumentType docType = document.getDocType();
 666   
 667  20 if (docType != null) {
 668  0 publicID = docType.getPublicID();
 669  0 systemID = docType.getSystemID();
 670    }
 671   
 672  20 if (publicID != null) {
 673  0 locator.setPublicId(publicID);
 674    }
 675   
 676  20 if (systemID != null) {
 677  0 locator.setSystemId(systemID);
 678    }
 679   
 680  20 locator.setLineNumber(-1);
 681  20 locator.setColumnNumber(-1);
 682   
 683  20 contentHandler.setDocumentLocator(locator);
 684    }
 685   
 686  20 protected void entityResolver(Document document) throws SAXException {
 687  20 if (entityResolver != null) {
 688  12 DocumentType docType = document.getDocType();
 689   
 690  12 if (docType != null) {
 691  0 String publicID = docType.getPublicID();
 692  0 String systemID = docType.getSystemID();
 693   
 694  0 if ((publicID != null) || (systemID != null)) {
 695  0 try {
 696  0 entityResolver.resolveEntity(publicID, systemID);
 697    } catch (IOException e) {
 698  0 throw new SAXException("Could not resolve publicID: "
 699    + publicID + " systemID: " + systemID, e);
 700    }
 701    }
 702    }
 703    }
 704    }
 705   
 706    /**
 707    * We do not yet support DTD or XML Schemas so this method does nothing
 708    * right now.
 709    *
 710    * @param document
 711    * DOCUMENT ME!
 712    *
 713    * @throws SAXException
 714    * DOCUMENT ME!
 715    */
 716  20 protected void dtdHandler(Document document) throws SAXException {
 717    }
 718   
 719  20 protected void startDocument() throws SAXException {
 720  20 contentHandler.startDocument();
 721    }
 722   
 723  20 protected void endDocument() throws SAXException {
 724  20 contentHandler.endDocument();
 725    }
 726   
 727  4953 protected void write(Element element, NamespaceStack namespaceStack)
 728    throws SAXException {
 729  4953 int stackSize = namespaceStack.size();
 730  4953 AttributesImpl namespaceAttributes = startPrefixMapping(element,
 731    namespaceStack);
 732  4953 startElement(element, namespaceAttributes);
 733  4953 writeContent(element, namespaceStack);
 734  4953 endElement(element);
 735  4953 endPrefixMapping(namespaceStack, stackSize);
 736    }
 737   
 738    /**
 739    * Fires a SAX startPrefixMapping event for all the namespaceStack which
 740    * have just come into scope
 741    *
 742    * @param element
 743    * DOCUMENT ME!
 744    * @param namespaceStack
 745    * DOCUMENT ME!
 746    *
 747    * @return DOCUMENT ME!
 748    *
 749    * @throws SAXException
 750    * DOCUMENT ME!
 751    */
 752  4953 protected AttributesImpl startPrefixMapping(Element element,
 753    NamespaceStack namespaceStack) throws SAXException {
 754  4953 AttributesImpl namespaceAttributes = null;
 755   
 756    // start with the namespace of the element
 757  4953 Namespace elementNamespace = element.getNamespace();
 758   
 759  4953 if ((elementNamespace != null)
 760    && !isIgnoreableNamespace(elementNamespace, namespaceStack)) {
 761  36 namespaceStack.push(elementNamespace);
 762  36 contentHandler.startPrefixMapping(elementNamespace.getPrefix(),
 763    elementNamespace.getURI());
 764  36 namespaceAttributes = addNamespaceAttribute(namespaceAttributes,
 765    elementNamespace);
 766    }
 767   
 768  4953 List declaredNamespaces = element.declaredNamespaces();
 769   
 770  4953 for (int i = 0, size = declaredNamespaces.size(); i < size; i++) {
 771  39 Namespace namespace = (Namespace) declaredNamespaces.get(i);
 772   
 773  39 if (!isIgnoreableNamespace(namespace, namespaceStack)) {
 774  3 namespaceStack.push(namespace);
 775  3 contentHandler.startPrefixMapping(namespace.getPrefix(),
 776    namespace.getURI());
 777  3 namespaceAttributes = addNamespaceAttribute(
 778    namespaceAttributes, namespace);
 779    }
 780    }
 781   
 782  4953 return namespaceAttributes;
 783    }
 784   
 785    /**
 786    * Fires a SAX endPrefixMapping event for all the namespaceStack which have
 787    * gone out of scope
 788    *
 789    * @param stack
 790    * DOCUMENT ME!
 791    * @param stackSize
 792    * DOCUMENT ME!
 793    *
 794    * @throws SAXException
 795    * DOCUMENT ME!
 796    */
 797  4953 protected void endPrefixMapping(NamespaceStack stack, int stackSize)
 798    throws SAXException {
 799  4953 while (stack.size() > stackSize) {
 800  39 Namespace namespace = stack.pop();
 801   
 802  39 if (namespace != null) {
 803  39 contentHandler.endPrefixMapping(namespace.getPrefix());
 804    }
 805    }
 806    }
 807   
 808  4953 protected void startElement(Element element,
 809    AttributesImpl namespaceAttributes) throws SAXException {
 810  4953 contentHandler.startElement(element.getNamespaceURI(), element
 811    .getName(), element.getQualifiedName(), createAttributes(
 812    element, namespaceAttributes));
 813    }
 814   
 815  4953 protected void endElement(Element element) throws SAXException {
 816  4953 contentHandler.endElement(element.getNamespaceURI(), element.getName(),
 817    element.getQualifiedName());
 818    }
 819   
 820  4953 protected Attributes createAttributes(Element element,
 821    Attributes namespaceAttributes) throws SAXException {
 822  4953 attributes.clear();
 823   
 824  4953 if (namespaceAttributes != null) {
 825  12 attributes.setAttributes(namespaceAttributes);
 826    }
 827   
 828  4953 for (Iterator iter = element.attributeIterator(); iter.hasNext();) {
 829  2609 Attribute attribute = (Attribute) iter.next();
 830  2609 attributes.addAttribute(attribute.getNamespaceURI(), attribute
 831    .getName(), attribute.getQualifiedName(), "CDATA",
 832    attribute.getValue());
 833    }
 834   
 835  4953 return attributes;
 836    }
 837   
 838    /**
 839    * If isDelcareNamespaceAttributes() is enabled then this method will add
 840    * the given namespace declaration to the supplied attributes object,
 841    * creating one if it does not exist.
 842    *
 843    * @param attrs
 844    * DOCUMENT ME!
 845    * @param namespace
 846    * DOCUMENT ME!
 847    *
 848    * @return DOCUMENT ME!
 849    */
 850  39 protected AttributesImpl addNamespaceAttribute(AttributesImpl attrs,
 851    Namespace namespace) {
 852  39 if (declareNamespaceAttributes) {
 853  13 if (attrs == null) {
 854  12 attrs = new AttributesImpl();
 855    }
 856   
 857  13 String prefix = namespace.getPrefix();
 858  13 String qualifiedName = "xmlns";
 859   
 860  13 if ((prefix != null) && (prefix.length() > 0)) {
 861  8 qualifiedName = "xmlns:" + prefix;
 862    }
 863   
 864  13 String uri = "";
 865  13 String localName = prefix;
 866  13 String type = "CDATA";
 867  13 String value = namespace.getURI();
 868   
 869  13 attrs.addAttribute(uri, localName, qualifiedName, type, value);
 870    }
 871   
 872  39 return attrs;
 873    }
 874   
 875    /**
 876    * DOCUMENT ME!
 877    *
 878    * @param namespace
 879    * DOCUMENT ME!
 880    * @param namespaceStack
 881    * DOCUMENT ME!
 882    *
 883    * @return true if the given namespace is an ignorable namespace (such as
 884    * Namespace.NO_NAMESPACE or Namespace.XML_NAMESPACE) or if the
 885    * namespace has already been declared in the current scope
 886    */
 887  4992 protected boolean isIgnoreableNamespace(Namespace namespace,
 888    NamespaceStack namespaceStack) {
 889  4992 if (namespace.equals(Namespace.NO_NAMESPACE)
 890    || namespace.equals(Namespace.XML_NAMESPACE)) {
 891  4761 return true;
 892    }
 893   
 894  231 String uri = namespace.getURI();
 895   
 896  231 if ((uri == null) || (uri.length() <= 0)) {
 897  0 return true;
 898    }
 899   
 900  231 return namespaceStack.contains(namespace);
 901    }
 902   
 903    /**
 904    * Ensures non-null content handlers?
 905    */
 906  20 protected void checkForNullHandlers() {
 907    }
 908    }
 909   
 910    /*
 911    * Redistribution and use of this software and associated documentation
 912    * ("Software"), with or without modification, are permitted provided that the
 913    * following conditions are met:
 914    *
 915    * 1. Redistributions of source code must retain copyright statements and
 916    * notices. Redistributions must also contain a copy of this document.
 917    *
 918    * 2. Redistributions in binary form must reproduce the above copyright notice,
 919    * this list of conditions and the following disclaimer in the documentation
 920    * and/or other materials provided with the distribution.
 921    *
 922    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 923    * from this Software without prior written permission of MetaStuff, Ltd. For
 924    * written permission, please contact dom4j-info@metastuff.com.
 925    *
 926    * 4. Products derived from this Software may not be called "DOM4J" nor may
 927    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 928    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 929    *
 930    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 931    *
 932    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 933    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 934    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 935    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 936    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 937    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 938    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 939    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 940    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 941    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 942    * POSSIBILITY OF SUCH DAMAGE.
 943    *
 944    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 945    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/XPP3Reader.html0000644000175000017500000043430510242117722021273 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 541   Methods: 22
NCLOC: 213   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
XPP3Reader.java 34,4% 53,1% 36,4% 46,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.io.BufferedReader;
 11    import java.io.CharArrayReader;
 12    import java.io.File;
 13    import java.io.FileReader;
 14    import java.io.IOException;
 15    import java.io.InputStream;
 16    import java.io.InputStreamReader;
 17    import java.io.Reader;
 18    import java.net.URL;
 19   
 20    import org.dom4j.Document;
 21    import org.dom4j.DocumentException;
 22    import org.dom4j.DocumentFactory;
 23    import org.dom4j.Element;
 24    import org.dom4j.ElementHandler;
 25    import org.dom4j.QName;
 26   
 27    import org.xmlpull.v1.XmlPullParser;
 28    import org.xmlpull.v1.XmlPullParserException;
 29    import org.xmlpull.v1.XmlPullParserFactory;
 30   
 31    /**
 32    * <p>
 33    * <code>XPP3Reader</code> is a Reader of DOM4J documents that uses the fast
 34    * <a href="http://www.extreme.indiana.edu/soap/xpp/">XML Pull Parser 3.x </a>.
 35    * It is very fast for use in SOAP style environments.
 36    * </p>
 37    *
 38    * @author <a href="mailto:pelle@neubia.com">Pelle Braendgaard </a>
 39    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 40    * @version $Revision: 1.3 $
 41    */
 42    public class XPP3Reader {
 43    /** <code>DocumentFactory</code> used to create new document objects */
 44    private DocumentFactory factory;
 45   
 46    /** <code>XmlPullParser</code> used to parse XML */
 47    private XmlPullParser xppParser;
 48   
 49    /** <code>XmlPullParser</code> used to parse XML */
 50    private XmlPullParserFactory xppFactory;
 51   
 52    /** DispatchHandler to call when each <code>Element</code> is encountered */
 53    private DispatchHandler dispatchHandler;
 54   
 55  2 public XPP3Reader() {
 56    }
 57   
 58  0 public XPP3Reader(DocumentFactory factory) {
 59  0 this.factory = factory;
 60    }
 61   
 62    /**
 63    * <p>
 64    * Reads a Document from the given <code>File</code>
 65    * </p>
 66    *
 67    * @param file
 68    * is the <code>File</code> to read from.
 69    *
 70    * @return the newly created Document instance
 71    *
 72    * @throws DocumentException
 73    * if an error occurs during parsing.
 74    * @throws IOException
 75    * if a URL could not be made for the given File
 76    * @throws XmlPullParserException
 77    * DOCUMENT ME!
 78    */
 79  2 public Document read(File file) throws DocumentException, IOException,
 80    XmlPullParserException {
 81  2 String systemID = file.getAbsolutePath();
 82   
 83  2 return read(new BufferedReader(new FileReader(file)), systemID);
 84    }
 85   
 86    /**
 87    * <p>
 88    * Reads a Document from the given <code>URL</code>
 89    * </p>
 90    *
 91    * @param url
 92    * <code>URL</code> to read from.
 93    *
 94    * @return the newly created Document instance
 95    *
 96    * @throws DocumentException
 97    * if an error occurs during parsing.
 98    * @throws IOException
 99    * DOCUMENT ME!
 100    * @throws XmlPullParserException
 101    * DOCUMENT ME!
 102    */
 103  0 public Document read(URL url) throws DocumentException, IOException,
 104    XmlPullParserException {
 105  0 String systemID = url.toExternalForm();
 106   
 107  0 return read(createReader(url.openStream()), systemID);
 108    }
 109   
 110    /**
 111    * <p>
 112    * Reads a Document from the given URL or filename.
 113    * </p>
 114    *
 115    * <p>
 116    * If the systemID contains a <code>':'</code> character then it is
 117    * assumed to be a URL otherwise its assumed to be a file name. If you want
 118    * finer grained control over this mechansim then please explicitly pass in
 119    * either a {@link URL}or a {@link File}instance instead of a {@link
 120    * String} to denote the source of the document.
 121    * </p>
 122    *
 123    * @param systemID
 124    * is a URL for a document or a file name.
 125    *
 126    * @return the newly created Document instance
 127    *
 128    * @throws DocumentException
 129    * if an error occurs during parsing.
 130    * @throws IOException
 131    * if a URL could not be made for the given File
 132    * @throws XmlPullParserException
 133    * DOCUMENT ME!
 134    */
 135  0 public Document read(String systemID) throws DocumentException,
 136    IOException, XmlPullParserException {
 137  0 if (systemID.indexOf(':') >= 0) {
 138    // lets assume its a URL
 139  0 return read(new URL(systemID));
 140    } else {
 141    // lets assume that we are given a file name
 142  0 return read(new File(systemID));
 143    }
 144    }
 145   
 146    /**
 147    * <p>
 148    * Reads a Document from the given stream
 149    * </p>
 150    *
 151    * @param in
 152    * <code>InputStream</code> to read from.
 153    *
 154    * @return the newly created Document instance
 155    *
 156    * @throws DocumentException
 157    * if an error occurs during parsing.
 158    * @throws IOException
 159    * DOCUMENT ME!
 160    * @throws XmlPullParserException
 161    * DOCUMENT ME!
 162    */
 163  0 public Document read(InputStream in) throws DocumentException, IOException,
 164    XmlPullParserException {
 165  0 return read(createReader(in));
 166    }
 167   
 168    /**
 169    * <p>
 170    * Reads a Document from the given <code>Reader</code>
 171    * </p>
 172    *
 173    * @param reader
 174    * is the reader for the input
 175    *
 176    * @return the newly created Document instance
 177    *
 178    * @throws DocumentException
 179    * if an error occurs during parsing.
 180    * @throws IOException
 181    * DOCUMENT ME!
 182    * @throws XmlPullParserException
 183    * DOCUMENT ME!
 184    */
 185  2 public Document read(Reader reader) throws DocumentException, IOException,
 186    XmlPullParserException {
 187  2 getXPPParser().setInput(reader);
 188   
 189  2 return parseDocument();
 190    }
 191   
 192    /**
 193    * <p>
 194    * Reads a Document from the given array of characters
 195    * </p>
 196    *
 197    * @param text
 198    * is the text to parse
 199    *
 200    * @return the newly created Document instance
 201    *
 202    * @throws DocumentException
 203    * if an error occurs during parsing.
 204    * @throws IOException
 205    * DOCUMENT ME!
 206    * @throws XmlPullParserException
 207    * DOCUMENT ME!
 208    */
 209  0 public Document read(char[] text) throws DocumentException, IOException,
 210    XmlPullParserException {
 211  0 getXPPParser().setInput(new CharArrayReader(text));
 212   
 213  0 return parseDocument();
 214    }
 215   
 216    /**
 217    * <p>
 218    * Reads a Document from the given stream
 219    * </p>
 220    *
 221    * @param in
 222    * <code>InputStream</code> to read from.
 223    * @param systemID
 224    * is the URI for the input
 225    *
 226    * @return the newly created Document instance
 227    *
 228    * @throws DocumentException
 229    * if an error occurs during parsing.
 230    * @throws IOException
 231    * DOCUMENT ME!
 232    * @throws XmlPullParserException
 233    * DOCUMENT ME!
 234    */
 235  0 public Document read(InputStream in, String systemID)
 236    throws DocumentException, IOException, XmlPullParserException {
 237  0 return read(createReader(in), systemID);
 238    }
 239   
 240    /**
 241    * <p>
 242    * Reads a Document from the given <code>Reader</code>
 243    * </p>
 244    *
 245    * @param reader
 246    * is the reader for the input
 247    * @param systemID
 248    * is the URI for the input
 249    *
 250    * @return the newly created Document instance
 251    *
 252    * @throws DocumentException
 253    * if an error occurs during parsing.
 254    * @throws IOException
 255    * DOCUMENT ME!
 256    * @throws XmlPullParserException
 257    * DOCUMENT ME!
 258    */
 259  2 public Document read(Reader reader, String systemID)
 260    throws DocumentException, IOException, XmlPullParserException {
 261  2 Document document = read(reader);
 262  2 document.setName(systemID);
 263   
 264  2 return document;
 265    }
 266   
 267    // Properties
 268    // -------------------------------------------------------------------------
 269  4 public XmlPullParser getXPPParser() throws XmlPullParserException {
 270  4 if (xppParser == null) {
 271  2 xppParser = getXPPFactory().newPullParser();
 272    }
 273   
 274  4 return xppParser;
 275    }
 276   
 277  2 public XmlPullParserFactory getXPPFactory() throws XmlPullParserException {
 278  2 if (xppFactory == null) {
 279  2 xppFactory = XmlPullParserFactory.newInstance();
 280    }
 281   
 282  2 xppFactory.setNamespaceAware(true);
 283   
 284  2 return xppFactory;
 285    }
 286   
 287  0 public void setXPPFactory(XmlPullParserFactory xPPfactory) {
 288  0 this.xppFactory = xPPfactory;
 289    }
 290   
 291    /**
 292    * DOCUMENT ME!
 293    *
 294    * @return the <code>DocumentFactory</code> used to create document
 295    * objects
 296    */
 297  2 public DocumentFactory getDocumentFactory() {
 298  2 if (factory == null) {
 299  2 factory = DocumentFactory.getInstance();
 300    }
 301   
 302  2 return factory;
 303    }
 304   
 305    /**
 306    * <p>
 307    * This sets the <code>DocumentFactory</code> used to create new
 308    * documents. This method allows the building of custom DOM4J tree objects
 309    * to be implemented easily using a custom derivation of
 310    * {@link DocumentFactory}
 311    * </p>
 312    *
 313    * @param documentFactory
 314    * <code>DocumentFactory</code> used to create DOM4J objects
 315    */
 316  0 public void setDocumentFactory(DocumentFactory documentFactory) {
 317  0 this.factory = documentFactory;
 318    }
 319   
 320    /**
 321    * Adds the <code>ElementHandler</code> to be called when the specified
 322    * path is encounted.
 323    *
 324    * @param path
 325    * is the path to be handled
 326    * @param handler
 327    * is the <code>ElementHandler</code> to be called by the event
 328    * based processor.
 329    */
 330  0 public void addHandler(String path, ElementHandler handler) {
 331  0 getDispatchHandler().addHandler(path, handler);
 332    }
 333   
 334    /**
 335    * Removes the <code>ElementHandler</code> from the event based processor,
 336    * for the specified path.
 337    *
 338    * @param path
 339    * is the path to remove the <code>ElementHandler</code> for.
 340    */
 341  0 public void removeHandler(String path) {
 342  0 getDispatchHandler().removeHandler(path);
 343    }
 344   
 345    /**
 346    * When multiple <code>ElementHandler</code> instances have been
 347    * registered, this will set a default <code>ElementHandler</code> to be
 348    * called for any path which does <b>NOT </b> have a handler registered.
 349    *
 350    * @param handler
 351    * is the <code>ElementHandler</code> to be called by the event
 352    * based processor.
 353    */
 354  0 public void setDefaultHandler(ElementHandler handler) {
 355  0 getDispatchHandler().setDefaultHandler(handler);
 356    }
 357   
 358    // Implementation methods
 359    // -------------------------------------------------------------------------
 360  2 protected Document parseDocument() throws DocumentException, IOException,
 361    XmlPullParserException {
 362  2 DocumentFactory df = getDocumentFactory();
 363  2 Document document = df.createDocument();
 364  2 Element parent = null;
 365  2 XmlPullParser pp = getXPPParser();
 366  2 pp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
 367   
 368  2 while (true) {
 369  72 int type = pp.nextToken();
 370   
 371  72 switch (type) {
 372  0 case XmlPullParser.PROCESSING_INSTRUCTION: {
 373  0 String text = pp.getText();
 374  0 int loc = text.indexOf(" ");
 375   
 376  0 if (loc >= 0) {
 377  0 String target = text.substring(0, loc);
 378  0 String txt = text.substring(loc + 1);
 379  0 document.addProcessingInstruction(target, txt);
 380    } else {
 381  0 document.addProcessingInstruction(text, "");
 382    }
 383   
 384  0 break;
 385    }
 386   
 387  0 case XmlPullParser.COMMENT: {
 388  0 if (parent != null) {
 389  0 parent.addComment(pp.getText());
 390    } else {
 391  0 document.addComment(pp.getText());
 392    }
 393   
 394  0 break;
 395    }
 396   
 397  0 case XmlPullParser.CDSECT: {
 398  0 if (parent != null) {
 399  0 parent.addCDATA(pp.getText());
 400    } else {
 401  0 String msg = "Cannot have text content outside of the "
 402    + "root document";
 403  0 throw new DocumentException(msg);
 404    }
 405   
 406  0 break;
 407    }
 408   
 409  2 case XmlPullParser.ENTITY_REF:
 410  2 break;
 411   
 412  2 case XmlPullParser.END_DOCUMENT:
 413  2 return document;
 414   
 415  16 case XmlPullParser.START_TAG: {
 416  16 QName qname = (pp.getPrefix() == null) ? df.createQName(pp
 417    .getName(), pp.getNamespace()) : df.createQName(pp
 418    .getName(), pp.getPrefix(), pp.getNamespace());
 419  16 Element newElement = df.createElement(qname);
 420  16 int nsStart = pp.getNamespaceCount(pp.getDepth() - 1);
 421  16 int nsEnd = pp.getNamespaceCount(pp.getDepth());
 422   
 423  16 for (int i = nsStart; i < nsEnd; i++) {
 424  0 if (pp.getNamespacePrefix(i) != null) {
 425  0 newElement.addNamespace(pp.getNamespacePrefix(i),
 426    pp.getNamespaceUri(i));
 427    }
 428    }
 429   
 430  16 for (int i = 0; i < pp.getAttributeCount(); i++) {
 431  0 QName qa = (pp.getAttributePrefix(i) == null) ? df
 432    .createQName(pp.getAttributeName(i)) : df
 433    .createQName(pp.getAttributeName(i), pp
 434    .getAttributePrefix(i), pp
 435    .getAttributeNamespace(i));
 436  0 newElement.addAttribute(qa, pp.getAttributeValue(i));
 437    }
 438   
 439  16 if (parent != null) {
 440  14 parent.add(newElement);
 441    } else {
 442  2 document.add(newElement);
 443    }
 444   
 445  16 parent = newElement;
 446   
 447  16 break;
 448    }
 449   
 450  16 case XmlPullParser.END_TAG: {
 451  16 if (parent != null) {
 452  16 parent = parent.getParent();
 453    }
 454   
 455  16 break;
 456    }
 457   
 458  32 case XmlPullParser.TEXT: {
 459  32 String text = pp.getText();
 460   
 461  32 if (parent != null) {
 462  32 parent.addText(text);
 463    } else {
 464  0 String msg = "Cannot have text content outside of the "
 465    + "root document";
 466  0 throw new DocumentException(msg);
 467    }
 468   
 469  32 break;
 470    }
 471   
 472  4 default:
 473  4 break;
 474    }
 475    }
 476    }
 477   
 478  0 protected DispatchHandler getDispatchHandler() {
 479  0 if (dispatchHandler == null) {
 480  0 dispatchHandler = new DispatchHandler();
 481    }
 482   
 483  0 return dispatchHandler;
 484    }
 485   
 486  0 protected void setDispatchHandler(DispatchHandler dispatchHandler) {
 487  0 this.dispatchHandler = dispatchHandler;
 488    }
 489   
 490    /**
 491    * Factory method to create a Reader from the given InputStream.
 492    *
 493    * @param in
 494    * DOCUMENT ME!
 495    *
 496    * @return DOCUMENT ME!
 497    *
 498    * @throws IOException
 499    * DOCUMENT ME!
 500    */
 501  0 protected Reader createReader(InputStream in) throws IOException {
 502  0 return new BufferedReader(new InputStreamReader(in));
 503    }
 504    }
 505   
 506    /*
 507    * Redistribution and use of this software and associated documentation
 508    * ("Software"), with or without modification, are permitted provided that the
 509    * following conditions are met:
 510    *
 511    * 1. Redistributions of source code must retain copyright statements and
 512    * notices. Redistributions must also contain a copy of this document.
 513    *
 514    * 2. Redistributions in binary form must reproduce the above copyright notice,
 515    * this list of conditions and the following disclaimer in the documentation
 516    * and/or other materials provided with the distribution.
 517    *
 518    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 519    * from this Software without prior written permission of MetaStuff, Ltd. For
 520    * written permission, please contact dom4j-info@metastuff.com.
 521    *
 522    * 4. Products derived from this Software may not be called "DOM4J" nor may
 523    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 524    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 525    *
 526    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 527    *
 528    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 529    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 530    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 531    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 532    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 533    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 534    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 535    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 536    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 537    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 538    * POSSIBILITY OF SUCH DAMAGE.
 539    *
 540    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 541    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/SAXModifyElementHandler.html0000644000175000017500000012055610242117732024032 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 144   Methods: 4
NCLOC: 53   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
SAXModifyElementHandler.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import org.dom4j.Document;
 11    import org.dom4j.Element;
 12    import org.dom4j.ElementHandler;
 13    import org.dom4j.ElementPath;
 14   
 15    /**
 16    * This {@link org.dom4j.ElementHandler}is used to trigger {@link
 17    * ElementModifier} objects in order to modify (parts of) the Document on the
 18    * fly.
 19    *
 20    * <p>
 21    * When an element is completely parsed, a copy is handed to the associated (if
 22    * any) {@link ElementModifier}that on his turn returns the modified element
 23    * that has to come in the tree.
 24    * </p>
 25    *
 26    * @author Wonne Keysers (Realsoftware.be)
 27    */
 28    class SAXModifyElementHandler implements ElementHandler {
 29    private ElementModifier elemModifier;
 30   
 31    private Element modifiedElement;
 32   
 33  0 public SAXModifyElementHandler(ElementModifier elemModifier) {
 34  0 this.elemModifier = elemModifier;
 35    }
 36   
 37  0 public void onStart(ElementPath elementPath) {
 38  0 this.modifiedElement = elementPath.getCurrent();
 39    }
 40   
 41  0 public void onEnd(ElementPath elementPath) {
 42  0 try {
 43  0 Element origElement = elementPath.getCurrent();
 44  0 Element currentParent = origElement.getParent();
 45   
 46  0 if (currentParent != null) {
 47    // Clone sets parent + document to null
 48  0 Element clonedElem = (Element) origElement.clone();
 49   
 50    // Ask for modified element
 51  0 modifiedElement = elemModifier.modifyElement(clonedElem);
 52   
 53  0 if (modifiedElement != null) {
 54    // Restore parent + document
 55  0 modifiedElement.setParent(origElement.getParent());
 56  0 modifiedElement.setDocument(origElement.getDocument());
 57   
 58    // Replace old with new element in parent
 59  0 int contentIndex = currentParent.indexOf(origElement);
 60  0 currentParent.content().set(contentIndex, modifiedElement);
 61    }
 62   
 63    // Remove the old element
 64  0 origElement.detach();
 65    } else {
 66  0 if (origElement.isRootElement()) {
 67    // Clone sets parent + document to null
 68  0 Element clonedElem = (Element) origElement.clone();
 69   
 70    // Ask for modified element
 71  0 modifiedElement = elemModifier.modifyElement(clonedElem);
 72   
 73  0 if (modifiedElement != null) {
 74    // Restore parent + document
 75  0 modifiedElement.setDocument(origElement.getDocument());
 76   
 77    // Replace old with new element in parent
 78  0 Document doc = origElement.getDocument();
 79  0 doc.setRootElement(modifiedElement);
 80    }
 81   
 82    // Remove the old element
 83  0 origElement.detach();
 84    }
 85    }
 86   
 87    // Put the new element on the ElementStack, it might get pruned by
 88    // the PruningDispatchHandler
 89  0 if (elementPath instanceof ElementStack) {
 90  0 ElementStack elementStack = ((ElementStack) elementPath);
 91  0 elementStack.popElement();
 92  0 elementStack.pushElement(modifiedElement);
 93    }
 94    } catch (Exception ex) {
 95  0 throw new SAXModifyException(ex);
 96    }
 97    }
 98   
 99    /**
 100    * DOCUMENT ME!
 101    *
 102    * @return Returns the modified Element.
 103    */
 104  0 protected Element getModifiedElement() {
 105  0 return modifiedElement;
 106    }
 107    }
 108   
 109    /*
 110    * Redistribution and use of this software and associated documentation
 111    * ("Software"), with or without modification, are permitted provided that the
 112    * following conditions are met:
 113    *
 114    * 1. Redistributions of source code must retain copyright statements and
 115    * notices. Redistributions must also contain a copy of this document.
 116    *
 117    * 2. Redistributions in binary form must reproduce the above copyright notice,
 118    * this list of conditions and the following disclaimer in the documentation
 119    * and/or other materials provided with the distribution.
 120    *
 121    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 122    * from this Software without prior written permission of MetaStuff, Ltd. For
 123    * written permission, please contact dom4j-info@metastuff.com.
 124    *
 125    * 4. Products derived from this Software may not be called "DOM4J" nor may
 126    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 127    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 128    *
 129    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 130    *
 131    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 132    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 133    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 134    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 135    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 136    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 137    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 138    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 139    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 140    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 141    * POSSIBILITY OF SUCH DAMAGE.
 142    *
 143    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 144    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/PruningElementStack.html0000644000175000017500000012607410242117725023344 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 154   Methods: 6
NCLOC: 62   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
PruningElementStack.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import org.dom4j.Element;
 11    import org.dom4j.ElementHandler;
 12   
 13    /**
 14    * <p>
 15    * <code>PruningElementStack</code> is a stack of {@link Element}instances
 16    * which will prune the tree when a path expression is reached. This is useful
 17    * for parsing very large documents where children of the root element can be
 18    * processed individually rather than keeping them all in memory at the same
 19    * time.
 20    * </p>
 21    *
 22    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 23    * @version $Revision: 1.11 $
 24    */
 25    class PruningElementStack extends ElementStack {
 26    /** ElementHandler to call when pruning occurs */
 27    private ElementHandler elementHandler;
 28   
 29    /**
 30    * the element name path which denotes the node to remove from its parent
 31    * when it is complete (i.e. when it is popped from the stack). The first
 32    * entry in the path will be a child of the root node
 33    */
 34    private String[] path;
 35   
 36    /**
 37    * The level at which a path match can occur. We match when we have popped
 38    * the selected node so the and the lastElementIndex points to its parent so
 39    * this value should be path.length - 2
 40    */
 41    private int matchingElementIndex;
 42   
 43  0 public PruningElementStack(String[] path, ElementHandler elementHandler) {
 44  0 this.path = path;
 45  0 this.elementHandler = elementHandler;
 46  0 checkPath();
 47    }
 48   
 49  0 public PruningElementStack(String[] path, ElementHandler elementHandler,
 50    int defaultCapacity) {
 51  0 super(defaultCapacity);
 52  0 this.path = path;
 53  0 this.elementHandler = elementHandler;
 54  0 checkPath();
 55    }
 56   
 57  0 public Element popElement() {
 58  0 Element answer = super.popElement();
 59   
 60  0 if ((lastElementIndex == matchingElementIndex)
 61    && (lastElementIndex >= 0)) {
 62    // we are popping the correct level in the tree
 63    // lets check if the path fits
 64    //
 65    // NOTE: this is an inefficient way of doing it - we could
 66    // maintain a history of which parts matched?
 67  0 if (validElement(answer, lastElementIndex + 1)) {
 68  0 Element parent = null;
 69   
 70  0 for (int i = 0; i <= lastElementIndex; i++) {
 71  0 parent = stack[i];
 72   
 73  0 if (!validElement(parent, i)) {
 74  0 parent = null;
 75   
 76  0 break;
 77    }
 78    }
 79   
 80  0 if (parent != null) {
 81  0 pathMatches(parent, answer);
 82    }
 83    }
 84    }
 85   
 86  0 return answer;
 87    }
 88   
 89  0 protected void pathMatches(Element parent, Element selectedNode) {
 90  0 elementHandler.onEnd(this);
 91  0 parent.remove(selectedNode);
 92    }
 93   
 94  0 protected boolean validElement(Element element, int index) {
 95  0 String requiredName = path[index];
 96  0 String name = element.getName();
 97   
 98  0 if (requiredName == name) {
 99  0 return true;
 100    }
 101   
 102  0 if ((requiredName != null) && (name != null)) {
 103  0 return requiredName.equals(name);
 104    }
 105   
 106  0 return false;
 107    }
 108   
 109  0 private void checkPath() {
 110  0 if (path.length < 2) {
 111  0 throw new RuntimeException("Invalid path of length: " + path.length
 112    + " it must be greater than 2");
 113    }
 114   
 115  0 matchingElementIndex = path.length - 2;
 116    }
 117    }
 118   
 119    /*
 120    * Redistribution and use of this software and associated documentation
 121    * ("Software"), with or without modification, are permitted provided that the
 122    * following conditions are met:
 123    *
 124    * 1. Redistributions of source code must retain copyright statements and
 125    * notices. Redistributions must also contain a copy of this document.
 126    *
 127    * 2. Redistributions in binary form must reproduce the above copyright notice,
 128    * this list of conditions and the following disclaimer in the documentation
 129    * and/or other materials provided with the distribution.
 130    *
 131    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 132    * from this Software without prior written permission of MetaStuff, Ltd. For
 133    * written permission, please contact dom4j-info@metastuff.com.
 134    *
 135    * 4. Products derived from this Software may not be called "DOM4J" nor may
 136    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 137    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 138    *
 139    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 140    *
 141    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 142    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 143    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 144    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 145    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 146    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 147    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 148    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 149    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 150    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 151    * POSSIBILITY OF SUCH DAMAGE.
 152    *
 153    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 154    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/SAXModifyReader.html0000644000175000017500000010604110242117553022337 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 125   Methods: 13
NCLOC: 50   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
SAXModifyReader.java - 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import org.dom4j.DocumentFactory;
 11   
 12    import org.xml.sax.SAXException;
 13    import org.xml.sax.XMLReader;
 14   
 15    /**
 16    * The SAXModifier parses, updates and writes an XML document. <br>
 17    * The input that is parsed is directly written to the specified output, unless
 18    * the current xml element has an associated ElementHandler. <br>
 19    * The {@link org.dom4j.ElementHandler}objects make it possible to update the
 20    * document on the fly, without having read tje complete document.
 21    *
 22    * @author Wonne Keysers (Realsoftware.be)
 23    *
 24    * @see org.dom4j.io.SAXReader
 25    * @see org.dom4j.io.XMLWriters
 26    */
 27    class SAXModifyReader extends SAXReader {
 28    private XMLWriter xmlWriter;
 29   
 30    private boolean pruneElements;
 31   
 32  0 public SAXModifyReader() {
 33    }
 34   
 35  0 public SAXModifyReader(boolean validating) {
 36  0 super(validating);
 37    }
 38   
 39  0 public SAXModifyReader(DocumentFactory factory) {
 40  0 super(factory);
 41    }
 42   
 43  0 public SAXModifyReader(DocumentFactory factory, boolean validating) {
 44  0 super(factory, validating);
 45    }
 46   
 47  0 public SAXModifyReader(XMLReader xmlReader) {
 48  0 super(xmlReader);
 49    }
 50   
 51  0 public SAXModifyReader(XMLReader xmlReader, boolean validating) {
 52  0 super(xmlReader, validating);
 53    }
 54   
 55  0 public SAXModifyReader(String xmlReaderClassName) throws SAXException {
 56  0 super(xmlReaderClassName);
 57    }
 58   
 59  0 public SAXModifyReader(String xmlReaderClassName, boolean validating)
 60    throws SAXException {
 61  0 super(xmlReaderClassName, validating);
 62    }
 63   
 64  0 public void setXMLWriter(XMLWriter writer) {
 65  0 this.xmlWriter = writer;
 66    }
 67   
 68  0 public boolean isPruneElements() {
 69  0 return pruneElements;
 70    }
 71   
 72  0 public void setPruneElements(boolean pruneElements) {
 73  0 this.pruneElements = pruneElements;
 74    }
 75   
 76  0 protected SAXContentHandler createContentHandler(XMLReader reader) {
 77  0 SAXModifyContentHandler handler = new SAXModifyContentHandler(
 78    getDocumentFactory(), getDispatchHandler());
 79   
 80  0 handler.setXMLWriter(xmlWriter);
 81   
 82  0 return handler;
 83    }
 84   
 85  0 protected XMLWriter getXMLWriter() {
 86  0 return this.xmlWriter;
 87    }
 88    }
 89   
 90    /*
 91    * Redistribution and use of this software and associated documentation
 92    * ("Software"), with or without modification, are permitted provided that the
 93    * following conditions are met:
 94    *
 95    * 1. Redistributions of source code must retain copyright statements and
 96    * notices. Redistributions must also contain a copy of this document.
 97    *
 98    * 2. Redistributions in binary form must reproduce the above copyright notice,
 99    * this list of conditions and the following disclaimer in the documentation
 100    * and/or other materials provided with the distribution.
 101    *
 102    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 103    * from this Software without prior written permission of MetaStuff, Ltd. For
 104    * written permission, please contact dom4j-info@metastuff.com.
 105    *
 106    * 4. Products derived from this Software may not be called "DOM4J" nor may
 107    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 108    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 109    *
 110    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 111    *
 112    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 113    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 114    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 115    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 116    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 117    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 118    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 119    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 120    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 121    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 122    * POSSIBILITY OF SUCH DAMAGE.
 123    *
 124    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 125    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/HTMLWriter.html0000644000175000017500000066562010242117747021374 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 841   Methods: 32
NCLOC: 281   Classes: 2
 
 Source file Conditionals Statements Methods TOTAL
HTMLWriter.java 29,5% 37% 37,5% 35,5%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.io.IOException;
 11    import java.io.OutputStream;
 12    import java.io.StringWriter;
 13    import java.io.UnsupportedEncodingException;
 14    import java.io.Writer;
 15    import java.util.HashSet;
 16    import java.util.Iterator;
 17    import java.util.Set;
 18    import java.util.Stack;
 19   
 20    import org.dom4j.Document;
 21    import org.dom4j.DocumentHelper;
 22    import org.dom4j.Element;
 23    import org.dom4j.Entity;
 24    import org.dom4j.Node;
 25   
 26    import org.xml.sax.SAXException;
 27   
 28    /**
 29    * <p>
 30    * <code>HTMLWriter</code> takes a DOM4J tree and formats it to a stream as
 31    * HTML. This formatter is similar to XMLWriter but it outputs the text of CDATA
 32    * and Entity sections rather than the serialised format as in XML, it has an
 33    * XHTML mode, it retains whitespace in certain elements such as &lt;PRE&gt;,
 34    * and it supports certain elements which have no corresponding close tag such
 35    * as for &lt;BR&gt; and &lt;P&gt;.
 36    * </p>
 37    *
 38    * <p>
 39    * The OutputFormat passed in to the constructor is checked for isXHTML() and
 40    * isExpandEmptyElements(). See {@link OutputFormat OutputFormat}for details.
 41    * Here are the rules for <b>this class </b> based on an OutputFormat, "format",
 42    * passed in to the constructor: <br/><br/>
 43    *
 44    * <ul>
 45    * <li>If an element is in {@link #getOmitElementCloseSet()
 46    * getOmitElementCloseSet}, then it is treated specially:
 47    *
 48    * <ul>
 49    * <li>It never expands, since some browsers treat this as two separate
 50    * Horizontal Rules: &lt;HR&gt;&lt;/HR&gt;</li>
 51    * <li>If {@link org.dom4j.io.OutputFormat#isXHTML() format.isXHTML()}, then
 52    * it has a space before the closing single-tag slash, since Netscape 4.x-
 53    * treats this: &lt;HR /&gt; as an element named "HR" with an attribute named
 54    * "/", but that's better than when it refuses to recognize this: &lt;hr/&gt;
 55    * which it thinks is an element named "HR/".</li>
 56    * </ul>
 57    *
 58    * </li>
 59    * <li>If {@link org.dom4j.io.OutputFormat#isXHTML() format.isXHTML()}, all
 60    * elements must have either a close element, or be a closed single tag.</li>
 61    * <li>If {@link org.dom4j.io.OutputFormat#isExpandEmptyElements()
 62    * format.isExpandEmptyElements()}() is true, all elements are expanded except
 63    * as above.</li>
 64    * </ul>
 65    *
 66    * <b>Examples </b>
 67    * </p>
 68    *
 69    * <p>
 70    * </p>
 71    *
 72    * <p>
 73    * If isXHTML == true, CDATA sections look like this:
 74    *
 75    * <PRE>
 76    *
 77    * <b>&lt;myelement&gt;&lt;![CDATA[My data]]&gt;&lt;/myelement&gt; </b>
 78    *
 79    * </PRE>
 80    *
 81    * Otherwise, they look like this:
 82    *
 83    * <PRE>
 84    *
 85    * <b>&lt;myelement&gt;My data&lt;/myelement&gt; </b>
 86    *
 87    * </PRE>
 88    *
 89    * </p>
 90    *
 91    * <p>
 92    * Basically, {@link OutputFormat.isXHTML() OutputFormat.isXHTML()} ==
 93    * <code>true</code> will produce valid XML, while {@link
 94    * org.dom4j.io.OutputFormat#isExpandEmptyElements()
 95    * format.isExpandEmptyElements()} determines whether empty elements are
 96    * expanded if isXHTML is true, excepting the special HTML single tags.
 97    * </p>
 98    *
 99    * <p>
 100    * Also, HTMLWriter handles tags whose contents should be preformatted, that is,
 101    * whitespace-preserved. By default, this set includes the tags &lt;PRE&gt;,
 102    * &lt;SCRIPT&gt;, &lt;STYLE&gt;, and &lt;TEXTAREA&gt;, case insensitively. It
 103    * does not include &lt;IFRAME&gt;. Other tags, such as &lt;CODE&gt;,
 104    * &lt;KBD&gt;, &lt;TT&gt;, &lt;VAR&gt;, are usually rendered in a different
 105    * font in most browsers, but don't preserve whitespace, so they also don't
 106    * appear in the default list. HTML Comments are always whitespace-preserved.
 107    * However, the parser you use may store comments with linefeed-only text nodes
 108    * (\n) even if your platform uses another line.separator character, and
 109    * HTMLWriter outputs Comment nodes exactly as the DOM is set up by the parser.
 110    * See examples and discussion here: {@link#setPreformattedTags(java.util.Set)
 111    * setPreformattedTags}
 112    * </p>
 113    *
 114    * <p>
 115    * <b>Examples </b>
 116    * </p>
 117    * <blockquote>
 118    * <p>
 119    * <b>Pretty Printing </b>
 120    * </p>
 121    *
 122    * <p>
 123    * This example shows how to pretty print a string containing a valid HTML
 124    * document to a string. You can also just call the static methods of this
 125    * class: <br>
 126    * {@link #prettyPrintHTML(String) prettyPrintHTML(String)}or <br>
 127    * {@link #prettyPrintHTML(String,boolean,boolean,boolean,boolean)
 128    * prettyPrintHTML(String,boolean,boolean,boolean,boolean)} or, <br>
 129    * {@link #prettyPrintXHTML(String) prettyPrintXHTML(String)}for XHTML (note
 130    * the X)
 131    * </p>
 132    *
 133    * <pre>
 134    * String testPrettyPrint(String html) {
 135    * StringWriter sw = new StringWriter();
 136    * OutputFormat format = OutputFormat.createPrettyPrint();
 137    * // These are the default values for createPrettyPrint,
 138    * // so you needn't set them:
 139    * // format.setNewlines(true);
 140    * // format.setTrimText(true);&lt;/font&gt;
 141    * format.setXHTML(true);
 142    * HTMLWriter writer = new HTMLWriter(sw, format);
 143    * Document document = DocumentHelper.parseText(html);
 144    * writer.write(document);
 145    * writer.flush();
 146    * return sw.toString();
 147    * }
 148    * </pre>
 149    *
 150    * <p>
 151    * This example shows how to create a "squeezed" document, but one that will
 152    * work in browsers even if the browser line length is limited. No newlines are
 153    * included, no extra whitespace at all, except where it it required by
 154    * {@link #setPreformattedTags(java.util.Set) setPreformattedTags}.
 155    * </p>
 156    *
 157    * <pre>
 158    * String testCrunch(String html) {
 159    * StringWriter sw = new StringWriter();
 160    * OutputFormat format = OutputFormat.createPrettyPrint();
 161    * format.setNewlines(false);
 162    * format.setTrimText(true);
 163    * format.setIndent(&quot;&quot;);
 164    * format.setXHTML(true);
 165    * format.setExpandEmptyElements(false);
 166    * format.setNewLineAfterNTags(20);
 167    * org.dom4j.io.HTMLWriter writer = new HTMLWriter(sw, format);
 168    * org.dom4j.Document document = DocumentHelper.parseText(html);
 169    * writer.write(document);
 170    * writer.flush();
 171    * return sw.toString();
 172    * }
 173    * </pre>
 174    *
 175    * </blockquote>
 176    *
 177    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 178    * @author Laramie Crocker
 179    * @version $Revision: 1.21 $
 180    */
 181    public class HTMLWriter extends XMLWriter {
 182    private static String lineSeparator = System.getProperty("line.separator");
 183   
 184    protected static final HashSet DEFAULT_PREFORMATTED_TAGS;
 185   
 186    static {
 187    // If you change this list, update the javadoc examples, above in the
 188    // class javadoc, in writeElement, and in setPreformattedTags().
 189  1 DEFAULT_PREFORMATTED_TAGS = new HashSet();
 190  1 DEFAULT_PREFORMATTED_TAGS.add("PRE");
 191  1 DEFAULT_PREFORMATTED_TAGS.add("SCRIPT");
 192  1 DEFAULT_PREFORMATTED_TAGS.add("STYLE");
 193  1 DEFAULT_PREFORMATTED_TAGS.add("TEXTAREA");
 194    }
 195   
 196    protected static final OutputFormat DEFAULT_HTML_FORMAT;
 197   
 198    static {
 199  1 DEFAULT_HTML_FORMAT = new OutputFormat(" ", true);
 200  1 DEFAULT_HTML_FORMAT.setTrimText(true);
 201  1 DEFAULT_HTML_FORMAT.setSuppressDeclaration(true);
 202    }
 203   
 204    private Stack formatStack = new Stack();
 205   
 206    private String lastText = "";
 207   
 208    private int tagsOuput = 0;
 209   
 210    // legal values are 0+, but -1 signifies lazy initialization.
 211    private int newLineAfterNTags = -1;
 212   
 213    private HashSet preformattedTags = DEFAULT_PREFORMATTED_TAGS;
 214   
 215    /**
 216    * Used to store the qualified element names which should have no close
 217    * element tag
 218    */
 219    private HashSet omitElementCloseSet;
 220   
 221  1 public HTMLWriter(Writer writer) {
 222  1 super(writer, DEFAULT_HTML_FORMAT);
 223    }
 224   
 225  5 public HTMLWriter(Writer writer, OutputFormat format) {
 226  5 super(writer, format);
 227    }
 228   
 229  0 public HTMLWriter() throws UnsupportedEncodingException {
 230  0 super(DEFAULT_HTML_FORMAT);
 231    }
 232   
 233  0 public HTMLWriter(OutputFormat format) throws UnsupportedEncodingException {
 234  0 super(format);
 235    }
 236   
 237  0 public HTMLWriter(OutputStream out) throws UnsupportedEncodingException {
 238  0 super(out, DEFAULT_HTML_FORMAT);
 239    }
 240   
 241  0 public HTMLWriter(OutputStream out, OutputFormat format)
 242    throws UnsupportedEncodingException {
 243  0 super(out, format);
 244    }
 245   
 246  0 public void startCDATA() throws SAXException {
 247    }
 248   
 249  0 public void endCDATA() throws SAXException {
 250    }
 251   
 252    // Overloaded methods
 253    // added isXHTML() stuff so you get the CDATA brackets if you desire.
 254  1 protected void writeCDATA(String text) throws IOException {
 255    // XXX: Should we escape entities?
 256    // writer.write( escapeElementEntities( text ) );
 257  1 if (getOutputFormat().isXHTML()) {
 258  0 super.writeCDATA(text);
 259    } else {
 260  1 writer.write(text);
 261    }
 262   
 263  1 lastOutputNodeType = Node.CDATA_SECTION_NODE;
 264    }
 265   
 266  0 protected void writeEntity(Entity entity) throws IOException {
 267  0 writer.write(entity.getText());
 268  0 lastOutputNodeType = Node.ENTITY_REFERENCE_NODE;
 269    }
 270   
 271  3 protected void writeDeclaration() throws IOException {
 272    }
 273   
 274  4 protected void writeString(String text) throws IOException {
 275    /*
 276    * DOM stores \n at the end of text nodes that are newlines. This is
 277    * significant if we are in a PRE section. However, we only want to
 278    * output the system line.separator, not \n. This is a little brittle,
 279    * but this function appears to be called with these lineseparators as a
 280    * separate TEXT_NODE. If we are in a preformatted section, output the
 281    * right line.separator, otherwise ditch. If the single \n character is
 282    * not the text, then do the super thing to output the text.
 283    *
 284    * Also, we store the last text that was not a \n since it may be used
 285    * by writeElement in this class to line up preformatted tags.
 286    */
 287  4 if (text.equals("\n")) {
 288  0 if (!formatStack.empty()) {
 289  0 super.writeString(lineSeparator);
 290    }
 291   
 292  0 return;
 293    }
 294   
 295  4 lastText = text;
 296   
 297  4 if (formatStack.empty()) {
 298  4 super.writeString(text.trim());
 299    } else {
 300  0 super.writeString(text);
 301    }
 302    }
 303   
 304    /**
 305    * Overriden method to not close certain element names to avoid wierd
 306    * behaviour from browsers for versions up to 5.x
 307    *
 308    * @param qualifiedName
 309    * DOCUMENT ME!
 310    *
 311    * @throws IOException
 312    * DOCUMENT ME!
 313    */
 314  0 protected void writeClose(String qualifiedName) throws IOException {
 315  0 if (!omitElementClose(qualifiedName)) {
 316  0 super.writeClose(qualifiedName);
 317    }
 318    }
 319   
 320  2 protected void writeEmptyElementClose(String qualifiedName)
 321    throws IOException {
 322  2 if (getOutputFormat().isXHTML()) {
 323    // xhtml, always check with format object whether to expand or not.
 324  0 if (omitElementClose(qualifiedName)) {
 325    // it was a special omit tag, do it the XHTML way: "<br/>",
 326    // ignoring the expansion option, since <br></br> is OK XML,
 327    // but produces twice the linefeeds desired in the browser.
 328    // for netscape 4.7, though all are fine with it, write a space
 329    // before the close slash.
 330  0 writer.write(" />");
 331    } else {
 332  0 super.writeEmptyElementClose(qualifiedName);
 333    }
 334    } else {
 335    // html, not xhtml
 336  2 if (omitElementClose(qualifiedName)) {
 337    // it was a special omit tag, do it the old html way: "<br>".
 338  1 writer.write(">");
 339    } else {
 340    // it was NOT a special omit tag, check with format object
 341    // whether to expand or not.
 342  1 super.writeEmptyElementClose(qualifiedName);
 343    }
 344    }
 345    }
 346   
 347  2 protected boolean omitElementClose(String qualifiedName) {
 348  2 return internalGetOmitElementCloseSet().contains(
 349    qualifiedName.toUpperCase());
 350    }
 351   
 352  2 private HashSet internalGetOmitElementCloseSet() {
 353  2 if (omitElementCloseSet == null) {
 354  2 omitElementCloseSet = new HashSet();
 355  2 loadOmitElementCloseSet(omitElementCloseSet);
 356    }
 357   
 358  2 return omitElementCloseSet;
 359    }
 360   
 361    // If you change this, change the javadoc for getOmitElementCloseSet.
 362  2 protected void loadOmitElementCloseSet(Set set) {
 363  2 set.add("AREA");
 364  2 set.add("BASE");
 365  2 set.add("BR");
 366  2 set.add("COL");
 367  2 set.add("HR");
 368  2 set.add("IMG");
 369  2 set.add("INPUT");
 370  2 set.add("LINK");
 371  2 set.add("META");
 372  2 set.add("P");
 373  2 set.add("PARAM");
 374    }
 375   
 376    // let the people see the set, but not modify it.
 377   
 378    /**
 379    * A clone of the Set of elements that can have their close-tags omitted. By
 380    * default it should be "AREA", "BASE", "BR", "COL", "HR", "IMG", "INPUT",
 381    * "LINK", "META", "P", "PARAM"
 382    *
 383    * @return A clone of the Set.
 384    */
 385  0 public Set getOmitElementCloseSet() {
 386  0 return (Set) (internalGetOmitElementCloseSet().clone());
 387    }
 388   
 389    /**
 390    * To use the empty set, pass an empty Set, or null:
 391    *
 392    * <pre>
 393    *
 394    *
 395    * setOmitElementCloseSet(new HashSet());
 396    * or
 397    * setOmitElementCloseSet(null);
 398    *
 399    *
 400    * </pre>
 401    *
 402    * @param newSet
 403    * DOCUMENT ME!
 404    */
 405  0 public void setOmitElementCloseSet(Set newSet) {
 406    // resets, and safely empties it out if newSet is null.
 407  0 omitElementCloseSet = new HashSet();
 408   
 409  0 if (newSet != null) {
 410  0 omitElementCloseSet = new HashSet();
 411   
 412  0 Object aTag;
 413  0 Iterator iter = newSet.iterator();
 414   
 415  0 while (iter.hasNext()) {
 416  0 aTag = iter.next();
 417   
 418  0 if (aTag != null) {
 419  0 omitElementCloseSet.add(aTag.toString().toUpperCase());
 420    }
 421    }
 422    }
 423    }
 424   
 425    /**
 426    * @see #setPreformattedTags(java.util.Set) setPreformattedTags
 427    */
 428  0 public Set getPreformattedTags() {
 429  0 return (Set) (preformattedTags.clone());
 430    }
 431   
 432    /**
 433    * <p>
 434    * Override the default set, which includes PRE, SCRIPT, STYLE, and
 435    * TEXTAREA, case insensitively.
 436    * </p>
 437    *
 438    * <p>
 439    * <b>Setting Preformatted Tags </b>
 440    * </p>
 441    *
 442    * <p>
 443    * Pass in a Set of Strings, one for each tag name that should be treated
 444    * like a PRE tag. You may pass in null or an empty Set to assign the empty
 445    * set, in which case no tags will be treated as preformatted, except that
 446    * HTML Comments will continue to be preformatted. If a tag is included in
 447    * the set of preformatted tags, all whitespace within the tag will be
 448    * preserved, including whitespace on the same line preceding the close tag.
 449    * This will generally make the close tag not line up with the start tag,
 450    * but it preserves the intention of the whitespace within the tag.
 451    * </p>
 452    *
 453    * <p>
 454    * The browser considers leading whitespace before the close tag to be
 455    * significant, but leading whitespace before the open tag to be
 456    * insignificant. For example, if the HTML author doesn't put the close
 457    * TEXTAREA tag flush to the left margin, then the TEXTAREA control in the
 458    * browser will have spaces on the last line inside the control. This may be
 459    * the HTML author's intent. Similarly, in a PRE, the browser treats a
 460    * flushed left close PRE tag as different from a close tag with leading
 461    * whitespace. Again, this must be left up to the HTML author.
 462    * </p>
 463    *
 464    * <p>
 465    * <b>Examples </b>
 466    * </p>
 467    * <blockquote>
 468    * <p>
 469    * Here is an example of how you can set the PreformattedTags list using
 470    * setPreformattedTags to include IFRAME, as well as the default set, if you
 471    * have an instance of this class named myHTMLWriter:
 472    *
 473    * <pre>
 474    * Set current = myHTMLWriter.getPreformattedTags();
 475    * current.add(&quot;IFRAME&quot;);
 476    * myHTMLWriter.setPreformattedTags(current);
 477    *
 478    * //The set is now &lt;b&gt;PRE, SCRIPT, STYLE, TEXTAREA, IFRAME&lt;/b&gt;
 479    *
 480    *
 481    * </pre>
 482    *
 483    * Similarly, you can simply replace it with your own:
 484    *
 485    * <pre>
 486    *
 487    *
 488    * HashSet newset = new HashSet();
 489    * newset.add(&quot;PRE&quot;);
 490    * newset.add(&quot;TEXTAREA&quot;);
 491    * myHTMLWriter.setPreformattedTags(newset);
 492    *
 493    * //The set is now &lt;b&gt;{PRE, TEXTAREA}&lt;/b&gt;
 494    *
 495    *
 496    * </pre>
 497    *
 498    * You can remove all tags from the preformatted tags list, with an empty
 499    * set, like this:
 500    *
 501    * <pre>
 502    *
 503    *
 504    * myHTMLWriter.setPreformattedTags(new HashSet());
 505    *
 506    * //The set is now &lt;b&gt;{}&lt;/b&gt;
 507    *
 508    *
 509    * </pre>
 510    *
 511    * or with null, like this:
 512    *
 513    * <pre>
 514    *
 515    *
 516    * myHTMLWriter.setPreformattedTags(null);
 517    *
 518    * //The set is now &lt;b&gt;{}&lt;/b&gt;
 519    *
 520    *
 521    * </pre>
 522    *
 523    * </p>
 524    * </blockquote>
 525    *
 526    * @param newSet
 527    * DOCUMENT ME!
 528    */
 529  0 public void setPreformattedTags(Set newSet) {
 530    // no fancy merging, just set it, assuming they did a
 531    // getExcludeTrimTags() first if they wanted to preserve the default
 532    // set.
 533    // resets, and safely empties it out if newSet is null.
 534  0 preformattedTags = new HashSet();
 535   
 536  0 if (newSet != null) {
 537  0 Object aTag;
 538  0 Iterator iter = newSet.iterator();
 539   
 540  0 while (iter.hasNext()) {
 541  0 aTag = iter.next();
 542   
 543  0 if (aTag != null) {
 544  0 preformattedTags.add(aTag.toString().toUpperCase());
 545    }
 546    }
 547    }
 548    }
 549   
 550    /**
 551    * DOCUMENT ME!
 552    *
 553    * @param qualifiedName
 554    * DOCUMENT ME!
 555    *
 556    * @return true if the qualifiedName passed in matched (case-insensitively)
 557    * a tag in the preformattedTags set, or false if not found or if
 558    * the set is empty or null.
 559    *
 560    * @see #setPreformattedTags(java.util.Set) setPreformattedTags
 561    */
 562  9 public boolean isPreformattedTag(String qualifiedName) {
 563    // A null set implies that the user called setPreformattedTags(null),
 564    // which means they want no tags to be preformatted.
 565  9 return (preformattedTags != null)
 566    && (preformattedTags.contains(qualifiedName.toUpperCase()));
 567    }
 568   
 569    /**
 570    * This override handles any elements that should not remove whitespace,
 571    * such as &lt;PRE&gt;, &lt;SCRIPT&gt;, &lt;STYLE&gt;, and &lt;TEXTAREA&gt;.
 572    * Note: the close tags won't line up with the open tag, but we can't alter
 573    * that. See javadoc note at setPreformattedTags.
 574    *
 575    * @param element
 576    * DOCUMENT ME!
 577    *
 578    * @throws IOException
 579    * When the stream could not be written to.
 580    *
 581    * @see #setPreformattedTags(java.util.Set) setPreformattedTags
 582    */
 583  9 protected void writeElement(Element element) throws IOException {
 584  9 if (newLineAfterNTags == -1) { // lazy initialization check
 585  3 lazyInitNewLinesAfterNTags();
 586    }
 587   
 588  9 if (newLineAfterNTags > 0) {
 589  0 if ((tagsOuput > 0) && ((tagsOuput % newLineAfterNTags) == 0)) {
 590  0 super.writer.write(lineSeparator);
 591    }
 592    }
 593   
 594  9 tagsOuput++;
 595   
 596  9 String qualifiedName = element.getQualifiedName();
 597  9 String saveLastText = lastText;
 598  9 int size = element.nodeCount();
 599   
 600  9 if (isPreformattedTag(qualifiedName)) {
 601  0 OutputFormat currentFormat = getOutputFormat();
 602  0 boolean saveNewlines = currentFormat.isNewlines();
 603  0 boolean saveTrimText = currentFormat.isTrimText();
 604  0 String currentIndent = currentFormat.getIndent();
 605   
 606    // You could have nested PREs, or SCRIPTS within PRE... etc.,
 607    // therefore use push and pop.
 608  0 formatStack.push(new FormatState(saveNewlines, saveTrimText,
 609    currentIndent));
 610   
 611  0 try {
 612    // do this manually, since it won't be done while outputting
 613    // the tag.
 614  0 super.writePrintln();
 615   
 616  0 if ((saveLastText.trim().length() == 0)
 617    && (currentIndent != null)
 618    && (currentIndent.length() > 0)) {
 619    // We are indenting, but we want to line up with the close
 620    // tag. lastText was the indent (whitespace, no \n) before
 621    // the preformatted start tag. So write it out instead of
 622    // the current indent level. This makes it line up with its
 623    // close tag.
 624  0 super.writer.write(justSpaces(saveLastText));
 625    }
 626   
 627    // actually, newlines are handled in this class by writeString,
 628    // depending on if the stack is empty.
 629  0 currentFormat.setNewlines(false);
 630  0 currentFormat.setTrimText(false);
 631  0 currentFormat.setIndent("");
 632   
 633    // This line is the recursive one:
 634  0 super.writeElement(element);
 635    } finally {
 636  0 FormatState state = (FormatState) formatStack.pop();
 637  0 currentFormat.setNewlines(state.isNewlines());
 638  0 currentFormat.setTrimText(state.isTrimText());
 639  0 currentFormat.setIndent(state.getIndent());
 640    }
 641    } else {
 642  9 super.writeElement(element);
 643    }
 644    }
 645   
 646  0 private String justSpaces(String text) {
 647  0 int size = text.length();
 648  0 StringBuffer res = new StringBuffer(size);
 649  0 char c;
 650   
 651  0 for (int i = 0; i < size; i++) {
 652  0 c = text.charAt(i);
 653   
 654  0 switch (c) {
 655  0 case '\r':
 656  0 case '\n':
 657   
 658  0 continue;
 659   
 660  0 default:
 661  0 res.append(c);
 662    }
 663    }
 664   
 665  0 return res.toString();
 666    }
 667   
 668  3 private void lazyInitNewLinesAfterNTags() {
 669  3 if (getOutputFormat().isNewlines()) {
 670    // don't bother, newlines are going to happen anyway.
 671  2 newLineAfterNTags = 0;
 672    } else {
 673  1 newLineAfterNTags = getOutputFormat().getNewLineAfterNTags();
 674    }
 675    }
 676   
 677    // Convenience methods, static, with bunch-o-defaults
 678   
 679    /**
 680    * Convenience method to just get a String result.
 681    *
 682    * @param html
 683    * DOCUMENT ME!
 684    *
 685    * @return a pretty printed String from the source string, preserving
 686    * whitespace in the defaultPreformattedTags set, and leaving the
 687    * close tags off of the default omitElementCloseSet set. Use one of
 688    * the write methods if you want stream output.
 689    *
 690    * @throws java.io.IOException
 691    * @throws java.io.UnsupportedEncodingException
 692    * @throws org.dom4j.DocumentException
 693    */
 694  0 public static String prettyPrintHTML(String html)
 695    throws java.io.IOException, java.io.UnsupportedEncodingException,
 696    org.dom4j.DocumentException {
 697  0 return prettyPrintHTML(html, true, true, false, true);
 698    }
 699   
 700    /**
 701    * Convenience method to just get a String result, but <b>As XHTML </b>.
 702    *
 703    * @param html
 704    * DOCUMENT ME!
 705    *
 706    * @return a pretty printed String from the source string, preserving
 707    * whitespace in the defaultPreformattedTags set, but conforming to
 708    * XHTML: no close tags are omitted (though if empty, they will be
 709    * converted to XHTML empty tags: &lt;HR/&gt; Use one of the write
 710    * methods if you want stream output.
 711    *
 712    * @throws java.io.IOException
 713    * @throws java.io.UnsupportedEncodingException
 714    * @throws org.dom4j.DocumentException
 715    */
 716  0 public static String prettyPrintXHTML(String html)
 717    throws java.io.IOException, java.io.UnsupportedEncodingException,
 718    org.dom4j.DocumentException {
 719  0 return prettyPrintHTML(html, true, true, true, false);
 720    }
 721   
 722    /**
 723    * DOCUMENT ME!
 724    *
 725    * @param html
 726    * DOCUMENT ME!
 727    * @param newlines
 728    * DOCUMENT ME!
 729    * @param trim
 730    * DOCUMENT ME!
 731    * @param isXHTML
 732    * DOCUMENT ME!
 733    * @param expandEmpty
 734    * DOCUMENT ME!
 735    *
 736    * @return a pretty printed String from the source string, preserving
 737    * whitespace in the defaultPreformattedTags set, and leaving the
 738    * close tags off of the default omitElementCloseSet set. This
 739    * override allows you to specify various formatter options. Use one
 740    * of the write methods if you want stream output.
 741    *
 742    * @throws java.io.IOException
 743    * @throws java.io.UnsupportedEncodingException
 744    * @throws org.dom4j.DocumentException
 745    */
 746  0 public static String prettyPrintHTML(String html, boolean newlines,
 747    boolean trim, boolean isXHTML, boolean expandEmpty)
 748    throws java.io.IOException, java.io.UnsupportedEncodingException,
 749    org.dom4j.DocumentException {
 750  0 StringWriter sw = new StringWriter();
 751  0 OutputFormat format = OutputFormat.createPrettyPrint();
 752  0 format.setNewlines(newlines);
 753  0 format.setTrimText(trim);
 754  0 format.setXHTML(isXHTML);
 755  0 format.setExpandEmptyElements(expandEmpty);
 756   
 757  0 HTMLWriter writer = new HTMLWriter(sw, format);
 758  0 Document document = DocumentHelper.parseText(html);
 759  0 writer.write(document);
 760  0 writer.flush();
 761   
 762  0 return sw.toString();
 763    }
 764   
 765    // Allows us to the current state of the format in this struct on the
 766    // formatStack.
 767    private class FormatState {
 768    private boolean newlines = false;
 769   
 770    private boolean trimText = false;
 771   
 772    private String indent = "";
 773   
 774  0 public FormatState(boolean newLines, boolean trimText, String indent) {
 775  0 this.newlines = newLines;
 776  0 this.trimText = trimText;
 777  0 this.indent = indent;
 778    }
 779   
 780  0 public boolean isNewlines() {
 781  0 return newlines;
 782    }
 783   
 784  0 public boolean isTrimText() {
 785  0 return trimText;
 786    }
 787   
 788  0 public String getIndent() {
 789  0 return indent;
 790    }
 791    }
 792    }
 793   
 794    /*
 795    * <html> <head> <title>My Title </title> <style> .foo { text-align: Right; }
 796    * </style> <script> function mojo(){ return "bar"; } </script> <script
 797    * language="JavaScript"> <!-- //this is the canonical javascript hiding.
 798    * function foo(){ return "foo"; } //--> </script> </head> <!-- this is a
 799    * comment --> <body bgcolor="#A4BFDD" mojo="&amp;"> entities: &#160; &amp;
 800    * &quot; &lt; &gt; %23 <p></p> <mojo> </mojo> <foo /> <table border="1"> <tr>
 801    * <td><pre> line0 <hr /> line1 <b>line2, should line up, indent-wise </b> line
 802    * 3 line 4 </pre></td><td></td></tr> </table> <myCDATAElement> <![CDATA[My
 803    * data]]> </myCDATAElement> </body> </html>
 804    */
 805   
 806    /*
 807    * Redistribution and use of this software and associated documentation
 808    * ("Software"), with or without modification, are permitted provided that the
 809    * following conditions are met:
 810    *
 811    * 1. Redistributions of source code must retain copyright statements and
 812    * notices. Redistributions must also contain a copy of this document.
 813    *
 814    * 2. Redistributions in binary form must reproduce the above copyright notice,
 815    * this list of conditions and the following disclaimer in the documentation
 816    * and/or other materials provided with the distribution.
 817    *
 818    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 819    * from this Software without prior written permission of MetaStuff, Ltd. For
 820    * written permission, please contact dom4j-info@metastuff.com.
 821    *
 822    * 4. Products derived from this Software may not be called "DOM4J" nor may
 823    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 824    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 825    *
 826    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 827    *
 828    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 829    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 830    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 831    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 832    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 833    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 834    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 835    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 836    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 837    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 838    * POSSIBILITY OF SUCH DAMAGE.
 839    *
 840    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 841    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/XMLResult.html0000644000175000017500000010005110242117751021243 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 113   Methods: 10
NCLOC: 45   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
XMLResult.java - 42,9% 40% 41,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.io.OutputStream;
 11    import java.io.UnsupportedEncodingException;
 12    import java.io.Writer;
 13   
 14    import javax.xml.transform.sax.SAXResult;
 15   
 16    import org.xml.sax.ContentHandler;
 17    import org.xml.sax.ext.LexicalHandler;
 18   
 19    /**
 20    * <p>
 21    * <code>XMLResult</code> implements a JAXP {@link SAXResult}for an output
 22    * stream with support for pretty printing and control over how the XML is
 23    * formatted.
 24    * </p>
 25    *
 26    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 27    * @version $Revision: 1.9 $
 28    */
 29    public class XMLResult extends SAXResult {
 30    private XMLWriter xmlWriter;
 31   
 32  0 public XMLResult() {
 33  0 this(new XMLWriter());
 34    }
 35   
 36  0 public XMLResult(Writer writer) {
 37  0 this(new XMLWriter(writer));
 38    }
 39   
 40  1 public XMLResult(Writer writer, OutputFormat format) {
 41  1 this(new XMLWriter(writer, format));
 42    }
 43   
 44  0 public XMLResult(OutputStream out) throws UnsupportedEncodingException {
 45  0 this(new XMLWriter(out));
 46    }
 47   
 48  0 public XMLResult(OutputStream out, OutputFormat format)
 49    throws UnsupportedEncodingException {
 50  0 this(new XMLWriter(out, format));
 51    }
 52   
 53  1 public XMLResult(XMLWriter xmlWriter) {
 54  1 super(xmlWriter);
 55  1 this.xmlWriter = xmlWriter;
 56  1 setLexicalHandler(xmlWriter);
 57    }
 58   
 59  0 public XMLWriter getXMLWriter() {
 60  0 return xmlWriter;
 61    }
 62   
 63  0 public void setXMLWriter(XMLWriter writer) {
 64  0 this.xmlWriter = writer;
 65  0 setHandler(xmlWriter);
 66  0 setLexicalHandler(xmlWriter);
 67    }
 68   
 69  1 public ContentHandler getHandler() {
 70  1 return xmlWriter;
 71    }
 72   
 73  1 public LexicalHandler getLexicalHandler() {
 74  1 return xmlWriter;
 75    }
 76    }
 77   
 78    /*
 79    * Redistribution and use of this software and associated documentation
 80    * ("Software"), with or without modification, are permitted provided that the
 81    * following conditions are met:
 82    *
 83    * 1. Redistributions of source code must retain copyright statements and
 84    * notices. Redistributions must also contain a copy of this document.
 85    *
 86    * 2. Redistributions in binary form must reproduce the above copyright notice,
 87    * this list of conditions and the following disclaimer in the documentation
 88    * and/or other materials provided with the distribution.
 89    *
 90    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 91    * from this Software without prior written permission of MetaStuff, Ltd. For
 92    * written permission, please contact dom4j-info@metastuff.com.
 93    *
 94    * 4. Products derived from this Software may not be called "DOM4J" nor may
 95    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 96    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 97    *
 98    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 99    *
 100    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 101    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 102    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 103    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 104    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 105    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 106    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 107    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 108    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 109    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 110    * POSSIBILITY OF SUCH DAMAGE.
 111    *
 112    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 113    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/io/DOMWriter.html0000644000175000017500000034012610242117721021226 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 402   Methods: 21
NCLOC: 254   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DOMWriter.java 69,2% 65,6% 71,4% 67,2%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.io;
 9   
 10    import java.util.List;
 11   
 12    import org.dom4j.Attribute;
 13    import org.dom4j.CDATA;
 14    import org.dom4j.Comment;
 15    import org.dom4j.Document;
 16    import org.dom4j.DocumentException;
 17    import org.dom4j.Element;
 18    import org.dom4j.Entity;
 19    import org.dom4j.Namespace;
 20    import org.dom4j.ProcessingInstruction;
 21    import org.dom4j.Text;
 22    import org.dom4j.tree.NamespaceStack;
 23   
 24    import org.w3c.dom.DOMImplementation;
 25   
 26    /**
 27    * <p>
 28    * <code>DOMWriter</code> takes a DOM4J tree and outputs it as a W3C DOM
 29    * object
 30    * </p>
 31    *
 32    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 33    * @version $Revision: 1.17 $
 34    */
 35    public class DOMWriter {
 36    private static boolean loggedWarning = false;
 37   
 38    private static final String[] DEFAULT_DOM_DOCUMENT_CLASSES = {
 39    "org.apache.xerces.dom.DocumentImpl", // Xerces
 40    "gnu.xml.dom.DomDocument", // GNU JAXP
 41    "org.apache.crimson.tree.XmlDocument", // Crimson
 42    "com.sun.xml.tree.XmlDocument", // Sun's Project X
 43    "oracle.xml.parser.v2.XMLDocument", // Oracle V2
 44    "oracle.xml.parser.XMLDocument", // Oracle V1
 45    "org.dom4j.dom.DOMDocument" // Internal DOM implementation
 46    };
 47   
 48    // the Class used to create new DOM Document instances
 49    private Class domDocumentClass;
 50   
 51    /** stack of <code>Namespace</code> objects */
 52    private NamespaceStack namespaceStack = new NamespaceStack();
 53   
 54  14 public DOMWriter() {
 55    }
 56   
 57  2 public DOMWriter(Class domDocumentClass) {
 58  2 this.domDocumentClass = domDocumentClass;
 59    }
 60   
 61  0 public Class getDomDocumentClass() throws DocumentException {
 62  0 Class result = domDocumentClass;
 63   
 64  0 if (result == null) {
 65    // lets try and find one in the classpath
 66  0 int size = DEFAULT_DOM_DOCUMENT_CLASSES.length;
 67   
 68  0 for (int i = 0; i < size; i++) {
 69  0 try {
 70  0 String name = DEFAULT_DOM_DOCUMENT_CLASSES[i];
 71  0 result = Class.forName(name, true, DOMWriter.class
 72    .getClassLoader());
 73   
 74  0 if (result != null) {
 75  0 break;
 76    }
 77    } catch (Exception e) {
 78    // could not load class correctly
 79    // lets carry on to the next one
 80    }
 81    }
 82    }
 83   
 84  0 return result;
 85    }
 86   
 87    /**
 88    * Sets the DOM {@link org.w3c.dom.Document}implementation class used by
 89    * the writer when creating DOM documents.
 90    *
 91    * @param domDocumentClass
 92    * is the Class implementing the {@linkorg.w3c.dom.Document}
 93    * interface
 94    */
 95  0 public void setDomDocumentClass(Class domDocumentClass) {
 96  0 this.domDocumentClass = domDocumentClass;
 97    }
 98   
 99    /**
 100    * Sets the DOM {@link org.w3c.dom.Document}implementation class name used
 101    * by the writer when creating DOM documents.
 102    *
 103    * @param name
 104    * is the name of the Class implementing the {@link
 105    * org.w3c.dom.Document} interface
 106    *
 107    * @throws DocumentException
 108    * if the class could not be loaded
 109    */
 110  0 public void setDomDocumentClassName(String name) throws DocumentException {
 111  0 try {
 112  0 this.domDocumentClass = Class.forName(name, true, DOMWriter.class
 113    .getClassLoader());
 114    } catch (Exception e) {
 115  0 throw new DocumentException("Could not load the DOM Document "
 116    + "class: " + name, e);
 117    }
 118    }
 119   
 120  16 public org.w3c.dom.Document write(Document document)
 121    throws DocumentException {
 122  16 if (document instanceof org.w3c.dom.Document) {
 123  1 return (org.w3c.dom.Document) document;
 124    }
 125   
 126  15 resetNamespaceStack();
 127   
 128  15 org.w3c.dom.Document domDocument = createDomDocument(document);
 129  15 appendDOMTree(domDocument, domDocument, document.content());
 130  15 namespaceStack.clear();
 131   
 132  15 return domDocument;
 133    }
 134   
 135  0 public org.w3c.dom.Document write(Document document,
 136    org.w3c.dom.DOMImplementation domImpl) throws DocumentException {
 137  0 if (document instanceof org.w3c.dom.Document) {
 138  0 return (org.w3c.dom.Document) document;
 139    }
 140   
 141  0 resetNamespaceStack();
 142   
 143  0 org.w3c.dom.Document domDocument = createDomDocument(document, domImpl);
 144  0 appendDOMTree(domDocument, domDocument, document.content());
 145  0 namespaceStack.clear();
 146   
 147  0 return domDocument;
 148    }
 149   
 150  4838 protected void appendDOMTree(org.w3c.dom.Document domDocument,
 151    org.w3c.dom.Node domCurrent, List content) {
 152  4838 int size = content.size();
 153   
 154  4838 for (int i = 0; i < size; i++) {
 155  13249 Object object = content.get(i);
 156   
 157  13249 if (object instanceof Element) {
 158  4823 appendDOMTree(domDocument, domCurrent, (Element) object);
 159  8426 } else if (object instanceof String) {
 160  0 appendDOMTree(domDocument, domCurrent, (String) object);
 161  8426 } else if (object instanceof Text) {
 162  8293 Text text = (Text) object;
 163  8293 appendDOMTree(domDocument, domCurrent, text.getText());
 164  133 } else if (object instanceof CDATA) {
 165  30 appendDOMTree(domDocument, domCurrent, (CDATA) object);
 166  103 } else if (object instanceof Comment) {
 167  68 appendDOMTree(domDocument, domCurrent, (Comment) object);
 168  35 } else if (object instanceof Entity) {
 169  0 appendDOMTree(domDocument, domCurrent, (Entity) object);
 170  35 } else if (object instanceof ProcessingInstruction) {
 171  2 appendDOMTree(domDocument, domCurrent,
 172    (ProcessingInstruction) object);
 173    }
 174    }
 175    }
 176   
 177  4823 protected void appendDOMTree(org.w3c.dom.Document domDocument,
 178    org.w3c.dom.Node domCurrent, Element element) {
 179  4823 String elUri = element.getNamespaceURI();
 180  4823 String elName = element.getQualifiedName();
 181  4823 org.w3c.dom.Element domElement = domDocument.createElementNS(elUri,
 182    elName);
 183   
 184  4823 int stackSize = namespaceStack.size();
 185   
 186    // add the namespace of the element first
 187  4823 Namespace elementNamespace = element.getNamespace();
 188   
 189  4823 if (isNamespaceDeclaration(elementNamespace)) {
 190  27 namespaceStack.push(elementNamespace);
 191  27 writeNamespace(domElement, elementNamespace);
 192    }
 193   
 194    // add the additional declared namespaces
 195  4823 List declaredNamespaces = element.declaredNamespaces();
 196   
 197  4823 for (int i = 0, size = declaredNamespaces.size(); i < size; i++) {
 198  33 Namespace namespace = (Namespace) declaredNamespaces.get(i);
 199   
 200  33 if (isNamespaceDeclaration(namespace)) {
 201  6 namespaceStack.push(namespace);
 202  6 writeNamespace(domElement, namespace);
 203    }
 204    }
 205   
 206    // add the attributes
 207  4823 for (int i = 0, size = element.attributeCount(); i < size; i++) {
 208  2492 Attribute attribute = (Attribute) element.attribute(i);
 209  2492 String attUri = attribute.getNamespaceURI();
 210  2492 String attName = attribute.getQualifiedName();
 211  2492 String value = attribute.getValue();
 212  2492 domElement.setAttributeNS(attUri, attName, value);
 213    }
 214   
 215    // add content
 216  4823 appendDOMTree(domDocument, domElement, element.content());
 217   
 218  4823 domCurrent.appendChild(domElement);
 219   
 220  4823 while (namespaceStack.size() > stackSize) {
 221  33 namespaceStack.pop();
 222    }
 223    }
 224   
 225  30 protected void appendDOMTree(org.w3c.dom.Document domDocument,
 226    org.w3c.dom.Node domCurrent, CDATA cdata) {
 227  30 org.w3c.dom.CDATASection domCDATA = domDocument
 228    .createCDATASection(cdata.getText());
 229  30 domCurrent.appendChild(domCDATA);
 230    }
 231   
 232  68 protected void appendDOMTree(org.w3c.dom.Document domDocument,
 233    org.w3c.dom.Node domCurrent, Comment comment) {
 234  68 org.w3c.dom.Comment domComment = domDocument.createComment(comment
 235    .getText());
 236  68 domCurrent.appendChild(domComment);
 237    }
 238   
 239  8293 protected void appendDOMTree(org.w3c.dom.Document domDocument,
 240    org.w3c.dom.Node domCurrent, String text) {
 241  8293 org.w3c.dom.Text domText = domDocument.createTextNode(text);
 242  8293 domCurrent.appendChild(domText);
 243    }
 244   
 245  0 protected void appendDOMTree(org.w3c.dom.Document domDocument,
 246    org.w3c.dom.Node domCurrent, Entity entity) {
 247  0 org.w3c.dom.EntityReference domEntity = domDocument
 248    .createEntityReference(entity.getName());
 249  0 domCurrent.appendChild(domEntity);
 250    }
 251   
 252  2 protected void appendDOMTree(org.w3c.dom.Document domDoc,
 253    org.w3c.dom.Node domCurrent, ProcessingInstruction pi) {
 254  2 org.w3c.dom.ProcessingInstruction domPI = domDoc
 255    .createProcessingInstruction(pi.getTarget(), pi.getText());
 256  2 domCurrent.appendChild(domPI);
 257    }
 258   
 259  33 protected void writeNamespace(org.w3c.dom.Element domElement,
 260    Namespace namespace) {
 261  33 String attributeName = attributeNameForNamespace(namespace);
 262   
 263    // domElement.setAttributeNS("", attributeName, namespace.getURI());
 264  33 domElement.setAttribute(attributeName, namespace.getURI());
 265    }
 266   
 267  33 protected String attributeNameForNamespace(Namespace namespace) {
 268  33 String xmlns = "xmlns";
 269  33 String prefix = namespace.getPrefix();
 270   
 271  33 if (prefix.length() > 0) {
 272  22 return xmlns + ":" + prefix;
 273    }
 274   
 275  11 return xmlns;
 276    }
 277   
 278  15 protected org.w3c.dom.Document createDomDocument(Document document)
 279    throws DocumentException {
 280  15 org.w3c.dom.Document result = null;
 281   
 282    // use the given domDocumentClass (if not null)
 283  15 if (domDocumentClass != null) {
 284  2 try {
 285  2 result = (org.w3c.dom.Document) domDocumentClass.newInstance();
 286    } catch (Exception e) {
 287  0 throw new DocumentException(
 288    "Could not instantiate an instance "
 289    + "of DOM Document with class: "
 290    + domDocumentClass.getName(), e);
 291    }
 292    } else {
 293    // lets try JAXP first before using the hardcoded default parsers
 294  13 result = createDomDocumentViaJAXP();
 295   
 296  13 if (result == null) {
 297  0 Class theClass = getDomDocumentClass();
 298   
 299  0 try {
 300  0 result = (org.w3c.dom.Document) theClass.newInstance();
 301    } catch (Exception e) {
 302  0 throw new DocumentException("Could not instantiate an "
 303    + "instance of DOM Document " + "with class: "
 304    + theClass.getName(), e);
 305    }
 306    }
 307    }
 308   
 309  15 return result;
 310    }
 311   
 312  13 protected org.w3c.dom.Document createDomDocumentViaJAXP()
 313    throws DocumentException {
 314  13 try {
 315  13 return JAXPHelper.createDocument(false, true);
 316    } catch (Throwable e) {
 317  0 if (!loggedWarning) {
 318  0 loggedWarning = true;
 319   
 320  0 if (SAXHelper.isVerboseErrorReporting()) {
 321    // log all exceptions as warnings and carry
 322    // on as we have a default SAX parser we can use
 323  0 System.out.println("Warning: Caught exception attempting "
 324    + "to use JAXP to create a W3C DOM " + "document");
 325  0 System.out.println("Warning: Exception was: " + e);
 326  0 e.printStackTrace();
 327    } else {
 328  0 System.out.println("Warning: Error occurred using JAXP to "
 329    + "create a DOM document.");
 330    }
 331    }
 332    }
 333   
 334  0 return null;
 335    }
 336   
 337  0 protected org.w3c.dom.Document createDomDocument(Document document,
 338    DOMImplementation domImpl) throws DocumentException {
 339  0 String namespaceURI = null;
 340  0 String qualifiedName = null;
 341  0 org.w3c.dom.DocumentType docType = null;
 342   
 343  0 return domImpl.createDocument(namespaceURI, qualifiedName, docType);
 344    }
 345   
 346  4856 protected boolean isNamespaceDeclaration(Namespace ns) {
 347  4856 if ((ns != null) && (ns != Namespace.NO_NAMESPACE)
 348    && (ns != Namespace.XML_NAMESPACE)) {
 349  172 String uri = ns.getURI();
 350   
 351  172 if ((uri != null) && (uri.length() > 0)) {
 352  172 if (!namespaceStack.contains(ns)) {
 353  33 return true;
 354    }
 355    }
 356    }
 357   
 358  4823 return false;
 359    }
 360   
 361  15 protected void resetNamespaceStack() {
 362  15 namespaceStack.clear();
 363  15 namespaceStack.push(Namespace.XML_NAMESPACE);
 364    }
 365    }
 366   
 367    /*
 368    * Redistribution and use of this software and associated documentation
 369    * ("Software"), with or without modification, are permitted provided that the
 370    * following conditions are met:
 371    *
 372    * 1. Redistributions of source code must retain copyright statements and
 373    * notices. Redistributions must also contain a copy of this document.
 374    *
 375    * 2. Redistributions in binary form must reproduce the above copyright notice,
 376    * this list of conditions and the following disclaimer in the documentation
 377    * and/or other materials provided with the distribution.
 378    *
 379    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 380    * from this Software without prior written permission of MetaStuff, Ltd. For
 381    * written permission, please contact dom4j-info@metastuff.com.
 382    *
 383    * 4. Products derived from this Software may not be called "DOM4J" nor may
 384    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 385    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 386    *
 387    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 388    *
 389    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 390    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 391    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 392    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 393    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 394    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 395    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 396    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 397    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 398    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 399    * POSSIBILITY OF SUCH DAMAGE.
 400    *
 401    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 402    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/Document.html0000644000175000017500000013720210242117710020556 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 189   Methods: 0
NCLOC: 17   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
Document.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    import java.util.Map;
 11   
 12    import org.xml.sax.EntityResolver;
 13   
 14    /**
 15    * <p>
 16    * <code>Document</code> defines an XML Document.
 17    * </p>
 18    *
 19    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 20    * @version $Revision: 1.14 $
 21    */
 22    public interface Document extends Branch {
 23    /**
 24    * Returns the root {@link Element}for this document.
 25    *
 26    * @return the root element for this document
 27    */
 28    Element getRootElement();
 29   
 30    /**
 31    * Sets the root element for this document
 32    *
 33    * @param rootElement
 34    * the new root element for this document
 35    */
 36    void setRootElement(Element rootElement);
 37   
 38    /**
 39    * Adds a new <code>Comment</code> node with the given text to this
 40    * branch.
 41    *
 42    * @param comment
 43    * is the text for the <code>Comment</code> node.
 44    *
 45    * @return this <code>Document</code> instance.
 46    */
 47    Document addComment(String comment);
 48   
 49    /**
 50    * Adds a processing instruction for the given target
 51    *
 52    * @param target
 53    * is the target of the processing instruction
 54    * @param text
 55    * is the textual data (key/value pairs) of the processing
 56    * instruction
 57    *
 58    * @return this <code>Document</code> instance.
 59    */
 60    Document addProcessingInstruction(String target, String text);
 61   
 62    /**
 63    * Adds a processing instruction for the given target
 64    *
 65    * @param target
 66    * is the target of the processing instruction
 67    * @param data
 68    * is a Map of the key / value pairs of the processing
 69    * instruction
 70    *
 71    * @return this <code>Document</code> instance.
 72    */
 73    Document addProcessingInstruction(String target, Map data);
 74   
 75    /**
 76    * Adds a DOCTYPE declaration to this document
 77    *
 78    * @param name
 79    * is the name of the root element
 80    * @param publicId
 81    * is the PUBLIC URI
 82    * @param systemId
 83    * is the SYSTEM URI
 84    *
 85    * @return this <code>Document</code> instance.
 86    */
 87    Document addDocType(String name, String publicId, String systemId);
 88   
 89    /**
 90    * DOCUMENT ME!
 91    *
 92    * @return the DocumentType property
 93    */
 94    DocumentType getDocType();
 95   
 96    /**
 97    * Sets the DocumentType property
 98    *
 99    * @param docType
 100    * DOCUMENT ME!
 101    */
 102    void setDocType(DocumentType docType);
 103   
 104    /**
 105    * DOCUMENT ME!
 106    *
 107    * @return the EntityResolver used to find resolve URIs such as for DTDs, or
 108    * XML Schema documents
 109    */
 110    EntityResolver getEntityResolver();
 111   
 112    /**
 113    * Sets the EntityResolver used to find resolve URIs such as for DTDs, or
 114    * XML Schema documents
 115    *
 116    * @param entityResolver
 117    * DOCUMENT ME!
 118    */
 119    void setEntityResolver(EntityResolver entityResolver);
 120   
 121    /**
 122    * Return the encoding of this document, as part of the XML declaration This
 123    * is <code>null</code> when unspecified or when it is not known (such as
 124    * when the Document was created in memory) or when the implementation does
 125    * not support this operation.
 126    *
 127    * <p>
 128    * The way this encoding is retrieved also depends on the way the XML source
 129    * is parsed. For instance, if the SAXReader is used and if the underlying
 130    * XMLReader implementation support the
 131    * <code>org.xml.sax.ext.Locator2</code> interface, the result returned by
 132    * this method is specified by the <code>getEncoding()</code> method of
 133    * that interface.
 134    * </p>
 135    *
 136    * @return The encoding of this document, as stated in the XML declaration,
 137    * or <code>null</code> if unknown.
 138    *
 139    * @since 1.5
 140    */
 141    String getXMLEncoding();
 142   
 143    /**
 144    * Sets the encoding of this document as it will appear in the XML
 145    * declaration part of the document.
 146    *
 147    * @param encoding the encoding of the document
 148    *
 149    * @since 1.6
 150    */
 151    void setXMLEncoding(String encoding);
 152    }
 153   
 154    /*
 155    * Redistribution and use of this software and associated documentation
 156    * ("Software"), with or without modification, are permitted provided that the
 157    * following conditions are met:
 158    *
 159    * 1. Redistributions of source code must retain copyright statements and
 160    * notices. Redistributions must also contain a copy of this document.
 161    *
 162    * 2. Redistributions in binary form must reproduce the above copyright notice,
 163    * this list of conditions and the following disclaimer in the documentation
 164    * and/or other materials provided with the distribution.
 165    *
 166    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 167    * from this Software without prior written permission of MetaStuff, Ltd. For
 168    * written permission, please contact dom4j-info@metastuff.com.
 169    *
 170    * 4. Products derived from this Software may not be called "DOM4J" nor may
 171    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 172    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 173    *
 174    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 175    *
 176    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 177    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 178    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 179    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 180    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 181    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 182    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 183    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 184    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 185    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 186    * POSSIBILITY OF SUCH DAMAGE.
 187    *
 188    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 189    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/CDATA.html0000644000175000017500000004202710242117713017617 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 56   Methods: 0
NCLOC: 3   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
CDATA.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    /**
 11    * <p>
 12    * <code>CDATA</code> defines an XML CDATA section.
 13    * </p>
 14    *
 15    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 16    * @version $Revision: 1.7 $
 17    */
 18    public interface CDATA extends CharacterData {
 19    }
 20   
 21    /*
 22    * Redistribution and use of this software and associated documentation
 23    * ("Software"), with or without modification, are permitted provided that the
 24    * following conditions are met:
 25    *
 26    * 1. Redistributions of source code must retain copyright statements and
 27    * notices. Redistributions must also contain a copy of this document.
 28    *
 29    * 2. Redistributions in binary form must reproduce the above copyright notice,
 30    * this list of conditions and the following disclaimer in the documentation
 31    * and/or other materials provided with the distribution.
 32    *
 33    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 34    * from this Software without prior written permission of MetaStuff, Ltd. For
 35    * written permission, please contact dom4j-info@metastuff.com.
 36    *
 37    * 4. Products derived from this Software may not be called "DOM4J" nor may
 38    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 39    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 40    *
 41    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 42    *
 43    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 44    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 45    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 46    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 47    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 48    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 49    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 50    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 51    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 52    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 53    * POSSIBILITY OF SUCH DAMAGE.
 54    *
 55    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 56    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/Element.html0000644000175000017500000064354210242117743020410 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 885   Methods: 0
NCLOC: 75   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
Element.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    import java.util.Iterator;
 11    import java.util.List;
 12    import java.util.Map;
 13   
 14    /**
 15    * <p>
 16    * <code>Element</code> interface defines an XML element. An element can have
 17    * declared namespaces, attributes, child nodes and textual content.
 18    * </p>
 19    *
 20    * <p>
 21    * Some of this interface is optional. Some implementations may be read-only and
 22    * not support being modified. Some implementations may not support the parent
 23    * relationship and methods such as {@link #getParent}or {@link#getDocument}.
 24    * </p>
 25    *
 26    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 27    * @version $Revision: 1.47 $
 28    */
 29    public interface Element extends Branch {
 30    // Name and namespace related methods
 31    // -------------------------------------------------------------------------
 32   
 33    /**
 34    * <p>
 35    * Returns the <code>QName</code> of this element which represents the
 36    * local name, the qualified name and the <code>Namespace</code>.
 37    * </p>
 38    *
 39    * @return the <code>QName</code> associated with this element
 40    */
 41    QName getQName();
 42   
 43    /**
 44    * <p>
 45    * Sets the <code>QName</code> of this element which represents the local
 46    * name, the qualified name and the <code>Namespace</code>.
 47    * </p>
 48    *
 49    * @param qname
 50    * is the <code>QName</code> to be associated with this element
 51    */
 52    void setQName(QName qname);
 53   
 54    /**
 55    * <p>
 56    * Returns the <code>Namespace</code> of this element if one exists
 57    * otherwise <code>Namespace.NO_NAMESPACE</code> is returned.
 58    * </p>
 59    *
 60    * @return the <code>Namespace</code> associated with this element
 61    */
 62    Namespace getNamespace();
 63   
 64    /**
 65    * <p>
 66    * Returns the <code>QName</code> for the given qualified name, using the
 67    * namespace URI in scope for the given prefix of the qualified name or the
 68    * default namespace if the qualified name has no prefix.
 69    * </p>
 70    *
 71    * @param qualifiedName
 72    * DOCUMENT ME!
 73    *
 74    * @return the <code>QName</code> for the given qualified name
 75    */
 76    QName getQName(String qualifiedName);
 77   
 78    /**
 79    * <p>
 80    * Returns the <code>Namespace</code> which is mapped to the given prefix
 81    * or null if it could not be found.
 82    * </p>
 83    *
 84    * @param prefix
 85    * DOCUMENT ME!
 86    *
 87    * @return the <code>Namespace</code> associated with the given prefix
 88    */
 89    Namespace getNamespaceForPrefix(String prefix);
 90   
 91    /**
 92    * <p>
 93    * Returns the <code>Namespace</code> which is mapped to the given URI or
 94    * null if it could not be found. If there is more than one
 95    * <code>Namespace</code> mapped to the URI, which of them will be
 96    * returned is undetermined.
 97    * </p>
 98    *
 99    * @param uri
 100    * DOCUMENT ME!
 101    *
 102    * @return the <code>Namespace</code> associated with the given URI
 103    */
 104    Namespace getNamespaceForURI(String uri);
 105   
 106    /**
 107    * <p>
 108    * Returns the all namespaces which are mapped to the given URI or an empty
 109    * list if no such namespaces could be found.
 110    * </p>
 111    *
 112    * @param uri
 113    * DOCUMENT ME!
 114    *
 115    * @return the namespaces associated with the given URI
 116    *
 117    * @since 1.5
 118    */
 119    List getNamespacesForURI(String uri);
 120   
 121    /**
 122    * <p>
 123    * Returns the namespace prefix of this element if one exists otherwise an
 124    * empty <code>String</code> is returned.
 125    * </p>
 126    *
 127    * @return the prefix of the <code>Namespace</code> of this element or an
 128    * empty <code>String</code>
 129    */
 130    String getNamespacePrefix();
 131   
 132    /**
 133    * <p>
 134    * Returns the URI mapped to the namespace of this element if one exists
 135    * otherwise an empty <code>String</code> is returned.
 136    * </p>
 137    *
 138    * @return the URI for the <code>Namespace</code> of this element or an
 139    * empty <code>String</code>
 140    */
 141    String getNamespaceURI();
 142   
 143    /**
 144    * <p>
 145    * Returns the fully qualified name of this element. This will be the same
 146    * as the value returned from {@link #getName}if this element has no
 147    * namespace attached to this element or an expression of the form
 148    *
 149    * <pre>
 150    * getNamespacePrefix() + &quot;:&quot; + getName()
 151    * </pre>
 152    *
 153    * will be returned.
 154    * </p>
 155    *
 156    * @return the fully qualified name of the element.
 157    */
 158    String getQualifiedName();
 159   
 160    /**
 161    * <p>
 162    * Returns any additional namespaces declarations for this element other
 163    * than namespace returned via the {@link #getNamespace()}method. If no
 164    * additional namespace declarations are present for this element then an
 165    * empty list will be returned. The list is backed by the element such that
 166    * changes to the list will be reflected in the element though the reverse
 167    * is not the case.
 168    * </p>
 169    *
 170    * @return a list of any additional namespace declarations.
 171    */
 172    List additionalNamespaces();
 173   
 174    /**
 175    * <p>
 176    * Returns all the namespaces declared by this element. If no namespaces are
 177    * declared for this element then an empty list will be returned. The list
 178    * is backed by the element such that changes to the list will be reflected
 179    * in the element though the reverse is not the case.
 180    * </p>
 181    *
 182    * @return a list of namespaces declared for this element.
 183    */
 184    List declaredNamespaces();
 185   
 186    // Builder methods
 187    // -------------------------------------------------------------------------
 188   
 189    /**
 190    * <p>
 191    * Adds the attribute value of the given local name. If an attribute already
 192    * exists for the given name it will be replaced. Attributes with null
 193    * values are silently ignored. If the value of the attribute is null then
 194    * this method call will remove any attributes with the given name.
 195    * </p>
 196    *
 197    * @param name
 198    * is the name of the attribute whose value is to be added or
 199    * updated
 200    * @param value
 201    * is the attribute's value
 202    *
 203    * @return this <code>Element</code> instance.
 204    */
 205    Element addAttribute(String name, String value);
 206   
 207    /**
 208    * <p>
 209    * Adds the attribute value of the given fully qualified name. If an
 210    * attribute already exists for the given name it will be replaced.
 211    * Attributes with null values are silently ignored. If the value of the
 212    * attribute is null then this method call will remove any attributes with
 213    * the given name.
 214    * </p>
 215    *
 216    * @param qName
 217    * is the fully qualified name of the attribute whose value is to
 218    * be added or updated
 219    * @param value
 220    * is the attribute's value
 221    *
 222    * @return this <code>Element</code> instance.
 223    */
 224    Element addAttribute(QName qName, String value);
 225   
 226    /**
 227    * Adds a new <code>Comment</code> node with the given text to this
 228    * element.
 229    *
 230    * @param comment
 231    * is the text for the <code>Comment</code> node.
 232    *
 233    * @return this <code>Element</code> instance.
 234    */
 235    Element addComment(String comment);
 236   
 237    /**
 238    * Adds a new <code>CDATA</code> node with the given text to this element.
 239    *
 240    * @param cdata
 241    * is the text for the <code>CDATA</code> node.
 242    *
 243    * @return this <code>Element</code> instance.
 244    */
 245    Element addCDATA(String cdata);
 246   
 247    /**
 248    * Adds a new <code>Entity</code> node with the given name and text to
 249    * this element and returns a reference to the new node.
 250    *
 251    * @param name
 252    * is the name for the <code>Entity</code> node.
 253    * @param text
 254    * is the text for the <code>Entity</code> node.
 255    *
 256    * @return this <code>Element</code> instance.
 257    */
 258    Element addEntity(String name, String text);
 259   
 260    /**
 261    * Adds a namespace to this element for use by its child content
 262    *
 263    * @param prefix
 264    * is the prefix to use, which should not be null or blank
 265    * @param uri
 266    * is the namespace URI
 267    *
 268    * @return this <code>Element</code> instance.
 269    */
 270    Element addNamespace(String prefix, String uri);
 271   
 272    /**
 273    * Adds a processing instruction for the given target
 274    *
 275    * @param target
 276    * is the target of the processing instruction
 277    * @param text
 278    * is the textual data (key/value pairs) of the processing
 279    * instruction
 280    *
 281    * @return this <code>Element</code> instance.
 282    */
 283    Element addProcessingInstruction(String target, String text);
 284   
 285    /**
 286    * Adds a processing instruction for the given target
 287    *
 288    * @param target
 289    * is the target of the processing instruction
 290    * @param data
 291    * is a Map of the key / value pairs of the processing
 292    * instruction
 293    *
 294    * @return this <code>Element</code> instance.
 295    */
 296    Element addProcessingInstruction(String target, Map data);
 297   
 298    /**
 299    * Adds a new <code>Text</code> node with the given text to this element.
 300    *
 301    * @param text
 302    * is the text for the <code>Text</code> node.
 303    *
 304    * @return this <code>Element</code> instance.
 305    */
 306    Element addText(String text);
 307   
 308    // Typesafe modifying methods
 309    // -------------------------------------------------------------------------
 310   
 311    /**
 312    * Adds the given <code>Attribute</code> to this element. If the given
 313    * node already has a parent defined then an
 314    * <code>IllegalAddException</code> will be thrown. Attributes with null
 315    * values are silently ignored.
 316    *
 317    * <p>
 318    * If the value of the attribute is null then this method call will remove
 319    * any attributes with the QName of this attribute.
 320    * </p>
 321    *
 322    * @param attribute
 323    * is the attribute to be added
 324    */
 325    void add(Attribute attribute);
 326   
 327    /**
 328    * Adds the given <code>CDATA</code> to this element. If the given node
 329    * already has a parent defined then an <code>IllegalAddException</code>
 330    * will be thrown.
 331    *
 332    * @param cdata
 333    * is the CDATA to be added
 334    */
 335    void add(CDATA cdata);
 336   
 337    /**
 338    * Adds the given <code>Entity</code> to this element. If the given node
 339    * already has a parent defined then an <code>IllegalAddException</code>
 340    * will be thrown.
 341    *
 342    * @param entity
 343    * is the entity to be added
 344    */
 345    void add(Entity entity);
 346   
 347    /**
 348    * Adds the given <code>Text</code> to this element. If the given node
 349    * already has a parent defined then an <code>IllegalAddException</code>
 350    * will be thrown.
 351    *
 352    * @param text
 353    * is the text to be added
 354    */
 355    void add(Text text);
 356   
 357    /**
 358    * Adds the given <code>Namespace</code> to this element. If the given
 359    * node already has a parent defined then an
 360    * <code>IllegalAddException</code> will be thrown.
 361    *
 362    * @param namespace
 363    * is the namespace to be added
 364    */
 365    void add(Namespace namespace);
 366   
 367    /**
 368    * Removes the given <code>Attribute</code> from this element.
 369    *
 370    * @param attribute
 371    * is the attribute to be removed
 372    *
 373    * @return true if the attribute was removed
 374    */
 375    boolean remove(Attribute attribute);
 376   
 377    /**
 378    * Removes the given <code>CDATA</code> if the node is an immediate child
 379    * of this element. If the given node is not an immediate child of this
 380    * element then the {@link Node#detach()}method should be used instead.
 381    *
 382    * @param cdata
 383    * is the CDATA to be removed
 384    *
 385    * @return true if the cdata was removed
 386    */
 387    boolean remove(CDATA cdata);
 388   
 389    /**
 390    * Removes the given <code>Entity</code> if the node is an immediate child
 391    * of this element. If the given node is not an immediate child of this
 392    * element then the {@link Node#detach()}method should be used instead.
 393    *
 394    * @param entity
 395    * is the entity to be removed
 396    *
 397    * @return true if the entity was removed
 398    */
 399    boolean remove(Entity entity);
 400   
 401    /**
 402    * Removes the given <code>Namespace</code> if the node is an immediate
 403    * child of this element. If the given node is not an immediate child of
 404    * this element then the {@link Node#detach()}method should be used
 405    * instead.
 406    *
 407    * @param namespace
 408    * is the namespace to be removed
 409    *
 410    * @return true if the namespace was removed
 411    */
 412    boolean remove(Namespace namespace);
 413   
 414    /**
 415    * Removes the given <code>Text</code> if the node is an immediate child
 416    * of this element. If the given node is not an immediate child of this
 417    * element then the {@link Node#detach()}method should be used instead.
 418    *
 419    * @param text
 420    * is the text to be removed
 421    *
 422    * @return true if the text was removed
 423    */
 424    boolean remove(Text text);
 425   
 426    // Text methods
 427    // -------------------------------------------------------------------------
 428   
 429    /**
 430    * Returns the text value of this element without recursing through child
 431    * elements. This method iterates through all {@link Text},{@link CDATA}
 432    * and {@link Entity}nodes that this element contains and appends the text
 433    * values together.
 434    *
 435    * @return the textual content of this Element. Child elements are not
 436    * navigated. This method does not return null;
 437    */
 438    String getText();
 439   
 440    /**
 441    * DOCUMENT ME!
 442    *
 443    * @return the trimmed text value where whitespace is trimmed and normalised
 444    * into single spaces. This method does not return null.
 445    */
 446    String getTextTrim();
 447   
 448    /**
 449    * Returns the XPath string-value of this node. The behaviour of this method
 450    * is defined in the <a href="http://www.w3.org/TR/xpath">XPath
 451    * specification </a>. This method returns the string-value of all the
 452    * contained {@link Text},{@link CDATA},{@link Entity}and {@link
 453    * Element} nodes all appended together.
 454    *
 455    * @return the text from all the child Text and Element nodes appended
 456    * together.
 457    */
 458    String getStringValue();
 459   
 460    /**
 461    * Accesses the data of this element which may implement data typing
 462    * bindings such as XML Schema or Java Bean bindings or will return the same
 463    * value as {@link #getText}
 464    *
 465    * @return DOCUMENT ME!
 466    */
 467    Object getData();
 468   
 469    /**
 470    * Sets the data value of this element if this element supports data binding
 471    * or calls {@link #setText}if it doesn't
 472    *
 473    * @param data
 474    * DOCUMENT ME!
 475    */
 476    void setData(Object data);
 477   
 478    // Attribute methods
 479    // -------------------------------------------------------------------------
 480   
 481    /**
 482    * <p>
 483    * Returns the {@link Attribute}instances this element contains as a backed
 484    * {@link List}so that the attributes may be modified directly using the
 485    * {@link List}interface. The <code>List</code> is backed by the
 486    * <code>Element</code> so that changes to the list are reflected in the
 487    * element and vice versa.
 488    * </p>
 489    *
 490    * @return the attributes that this element contains as a <code>List</code>
 491    */
 492    List attributes();
 493   
 494    /**
 495    * Sets the attributes that this element contains
 496    *
 497    * @param attributes
 498    * DOCUMENT ME!
 499    */
 500    void setAttributes(List attributes);
 501   
 502    /**
 503    * DOCUMENT ME!
 504    *
 505    * @return the number of attributes this element contains
 506    */
 507    int attributeCount();
 508   
 509    /**
 510    * DOCUMENT ME!
 511    *
 512    * @return an iterator over the attributes of this element
 513    */
 514    Iterator attributeIterator();
 515   
 516    /**
 517    * Returns the attribute at the specified indexGets the
 518    *
 519    * @param index
 520    * DOCUMENT ME!
 521    *
 522    * @return the attribute at the specified index where index &gt;= 0 and
 523    * index &lt; number of attributes or throws an
 524    * IndexOutOfBoundsException if the index is not within the
 525    * allowable range
 526    */
 527    Attribute attribute(int index);
 528   
 529    /**
 530    * Returns the attribute with the given name
 531    *
 532    * @param name
 533    * DOCUMENT ME!
 534    *
 535    * @return the attribute for the given local name in any namespace. If there
 536    * are more than one attributes with the given local name in
 537    * different namespaces then the first one is returned.
 538    */
 539    Attribute attribute(String name);
 540   
 541    /**
 542    * DOCUMENT ME!
 543    *
 544    * @param qName
 545    * is the fully qualified name
 546    *
 547    * @return the attribute for the given fully qualified name or null if it
 548    * could not be found.
 549    */
 550    Attribute attribute(QName qName);
 551   
 552    /**
 553    * <p>
 554    * This returns the attribute value for the attribute with the given name
 555    * and any namespace or null if there is no such attribute or the empty
 556    * string if the attribute value is empty.
 557    * </p>
 558    *
 559    * @param name
 560    * is the name of the attribute value to be returnd
 561    *
 562    * @return the value of the attribute, null if the attribute does not exist
 563    * or the empty string
 564    */
 565    String attributeValue(String name);
 566   
 567    /**
 568    * <p>
 569    * This returns the attribute value for the attribute with the given name
 570    * and any namespace or the default value if there is no such attribute
 571    * value.
 572    * </p>
 573    *
 574    * @param name
 575    * is the name of the attribute value to be returnd
 576    * @param defaultValue
 577    * is the default value to be returned if the attribute has no
 578    * value defined.
 579    *
 580    * @return the value of the attribute or the defaultValue if the attribute
 581    * has no value defined.
 582    */
 583    String attributeValue(String name, String defaultValue);
 584   
 585    /**
 586    * <p>
 587    * This returns the attribute value for the attribute with the given fully
 588    * qualified name or null if there is no such attribute or the empty string
 589    * if the attribute value is empty.
 590    * </p>
 591    *
 592    * @param qName
 593    * is the fully qualified name
 594    *
 595    * @return the value of the attribute, null if the attribute does not exist
 596    * or the empty string
 597    */
 598    String attributeValue(QName qName);
 599   
 600    /**
 601    * <p>
 602    * This returns the attribute value for the attribute with the given fully
 603    * qualified name or the default value if there is no such attribute value.
 604    * </p>
 605    *
 606    * @param qName
 607    * is the fully qualified name
 608    * @param defaultValue
 609    * is the default value to be returned if the attribute has no
 610    * value defined.
 611    *
 612    * @return the value of the attribute or the defaultValue if the attribute
 613    * has no value defined.
 614    */
 615    String attributeValue(QName qName, String defaultValue);
 616   
 617    /**
 618    * <p>
 619    * Sets the attribute value of the given local name.
 620    * </p>
 621    *
 622    * @param name
 623    * is the name of the attribute whose value is to be added or
 624    * updated
 625    * @param value
 626    * is the attribute's value
 627    *
 628    * @deprecated As of version 0.5. Please use {@link
 629    * #addAttribute(String,String)} instead. WILL BE REMOVED IN
 630    * dom4j-1.6 !!
 631    */
 632    void setAttributeValue(String name, String value);
 633   
 634    /**
 635    * <p>
 636    * Sets the attribute value of the given fully qualified name.
 637    * </p>
 638    *
 639    * @param qName
 640    * is the fully qualified name of the attribute whose value is to
 641    * be added or updated
 642    * @param value
 643    * is the attribute's value
 644    *
 645    * @deprecated As of version 0.5. Please use {@link
 646    * #addAttribute(QName,String)} instead. WILL BE REMOVED IN
 647    * dom4j-1.6 !!
 648    */
 649    void setAttributeValue(QName qName, String value);
 650   
 651    // Content methods
 652    // -------------------------------------------------------------------------
 653   
 654    /**
 655    * Returns the first element for the given local name and any namespace.
 656    *
 657    * @param name
 658    * DOCUMENT ME!
 659    *
 660    * @return the first element with the given local name
 661    */
 662    Element element(String name);
 663   
 664    /**
 665    * Returns the first element for the given fully qualified name.
 666    *
 667    * @param qName
 668    * is the fully qualified name to search for
 669    *
 670    * @return the first element with the given fully qualified name
 671    */
 672    Element element(QName qName);
 673   
 674    /**
 675    * <p>
 676    * Returns the elements contained in this element. If this element does not
 677    * contain any elements then this method returns an empty list. The list is
 678    * backed by the element such that changes to the list will be reflected in
 679    * the element though the reverse is not the case.
 680    * </p>
 681    *
 682    * @return a list of all the elements in this element.
 683    */
 684    List elements();
 685   
 686    /**
 687    * <p>
 688    * Returns the elements contained in this element with the given local name
 689    * and any namespace. If no elements are found then this method returns an
 690    * empty list. The list is backed by the element such that changes to the
 691    * list will be reflected in the element though the reverse is not the case.
 692    * </p>
 693    *
 694    * @param name
 695    * DOCUMENT ME!
 696    *
 697    * @return a list of all the elements in this element for the given local
 698    * name
 699    */
 700    List elements(String name);
 701   
 702    /**
 703    * <p>
 704    * Returns the elements contained in this element with the given fully
 705    * qualified name. If no elements are found then this method returns an
 706    * empty list. The list is backed by the element such that changes to the
 707    * list will be reflected in the element though the reverse is not the case.
 708    * </p>
 709    *
 710    * @param qName
 711    * is the fully qualified name to search for
 712    *
 713    * @return a list of all the elements in this element for the given fully
 714    * qualified name.
 715    */
 716    List elements(QName qName);
 717   
 718    /**
 719    * Returns an iterator over all this elements child elements.
 720    *
 721    * @return an iterator over the contained elements
 722    */
 723    Iterator elementIterator();
 724   
 725    /**
 726    * Returns an iterator over the elements contained in this element which
 727    * match the given local name and any namespace.
 728    *
 729    * @param name
 730    * DOCUMENT ME!
 731    *
 732    * @return an iterator over the contained elements matching the given local
 733    * name
 734    */
 735    Iterator elementIterator(String name);
 736   
 737    /**
 738    * Returns an iterator over the elements contained in this element which
 739    * match the given fully qualified name.
 740    *
 741    * @param qName
 742    * is the fully qualified name to search for
 743    *
 744    * @return an iterator over the contained elements matching the given fully
 745    * qualified name
 746    */
 747    Iterator elementIterator(QName qName);
 748   
 749    // Helper methods
 750    // -------------------------------------------------------------------------
 751   
 752    /**
 753    * DOCUMENT ME!
 754    *
 755    * @return true if this element is the root element of a document and this
 756    * element supports the parent relationship else false.
 757    */
 758    boolean isRootElement();
 759   
 760    /**
 761    * <p>
 762    * Returns true if this <code>Element</code> has mixed content. Mixed
 763    * content means that an element contains both textual data and child
 764    * elements.
 765    * </p>
 766    *
 767    * @return true if this element contains mixed content.
 768    */
 769    boolean hasMixedContent();
 770   
 771    /**
 772    * <p>
 773    * Returns true if this <code>Element</code> has text only content.
 774    * </p>
 775    *
 776    * @return true if this element is empty or only contains text content.
 777    */
 778    boolean isTextOnly();
 779   
 780    /**
 781    * Appends the attributes of the given element to me. This method behaves
 782    * like the {@link java.util.Collection#addAll(java.util.Collection)}
 783    * method.
 784    *
 785    * @param element
 786    * is the element whose attributes will be added to me.
 787    */
 788    void appendAttributes(Element element);
 789   
 790    /**
 791    * <p>
 792    * Creates a deep copy of this element The new element is detached from its
 793    * parent, and getParent() on the clone will return null.
 794    * </p>
 795    *
 796    * @return a new deep copy Element
 797    */
 798    Element createCopy();
 799   
 800    /**
 801    * <p>
 802    * Creates a deep copy of this element with the given local name The new
 803    * element is detached from its parent, and getParent() on the clone will
 804    * return null.
 805    * </p>
 806    *
 807    * @param name
 808    * DOCUMENT ME!
 809    *
 810    * @return a new deep copy Element
 811    */
 812    Element createCopy(String name);
 813   
 814    /**
 815    * <p>
 816    * Creates a deep copy of this element with the given fully qualified name.
 817    * The new element is detached from its parent, and getParent() on the clone
 818    * will return null.
 819    * </p>
 820    *
 821    * @param qName
 822    * DOCUMENT ME!
 823    *
 824    * @return a new deep copy Element
 825    */
 826    Element createCopy(QName qName);
 827   
 828    String elementText(String name);
 829   
 830    String elementText(QName qname);
 831   
 832    String elementTextTrim(String name);
 833   
 834    String elementTextTrim(QName qname);
 835   
 836    /**
 837    * Returns a node at the given index suitable for an XPath result set. This
 838    * means the resulting Node will either be null or it will support the
 839    * parent relationship.
 840    *
 841    * @param index
 842    * DOCUMENT ME!
 843    *
 844    * @return the Node for the given index which will support the parent
 845    * relationship or null if there is not a node at the given index.
 846    */
 847    Node getXPathResult(int index);
 848    }
 849   
 850    /*
 851    * Redistribution and use of this software and associated documentation
 852    * ("Software"), with or without modification, are permitted provided that the
 853    * following conditions are met:
 854    *
 855    * 1. Redistributions of source code must retain copyright statements and
 856    * notices. Redistributions must also contain a copy of this document.
 857    *
 858    * 2. Redistributions in binary form must reproduce the above copyright notice,
 859    * this list of conditions and the following disclaimer in the documentation
 860    * and/or other materials provided with the distribution.
 861    *
 862    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 863    * from this Software without prior written permission of MetaStuff, Ltd. For
 864    * written permission, please contact dom4j-info@metastuff.com.
 865    *
 866    * 4. Products derived from this Software may not be called "DOM4J" nor may
 867    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 868    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 869    *
 870    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 871    *
 872    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 873    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 874    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 875    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 876    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 877    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 878    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 879    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 880    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 881    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 882    * POSSIBILITY OF SUCH DAMAGE.
 883    *
 884    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 885    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/DocumentFactory.html0000644000175000017500000035762610242117717022133 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 456   Methods: 36
NCLOC: 193   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DocumentFactory.java 75% 78,9% 86,1% 80,9%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    import java.io.IOException;
 11    import java.io.ObjectInputStream;
 12    import java.io.Serializable;
 13    import java.util.List;
 14    import java.util.Map;
 15   
 16    import org.dom4j.rule.Pattern;
 17    import org.dom4j.tree.AbstractDocument;
 18    import org.dom4j.tree.DefaultAttribute;
 19    import org.dom4j.tree.DefaultCDATA;
 20    import org.dom4j.tree.DefaultComment;
 21    import org.dom4j.tree.DefaultDocument;
 22    import org.dom4j.tree.DefaultDocumentType;
 23    import org.dom4j.tree.DefaultElement;
 24    import org.dom4j.tree.DefaultEntity;
 25    import org.dom4j.tree.DefaultProcessingInstruction;
 26    import org.dom4j.tree.DefaultText;
 27    import org.dom4j.tree.QNameCache;
 28    import org.dom4j.util.SimpleSingleton;
 29    import org.dom4j.util.SingletonStrategy;
 30    import org.dom4j.xpath.DefaultXPath;
 31    import org.dom4j.xpath.XPathPattern;
 32    import org.jaxen.VariableContext;
 33   
 34    /**
 35    * <p>
 36    * <code>DocumentFactory</code> is a collection of factory methods to allow
 37    * easy custom building of DOM4J trees. The default tree that is built uses a
 38    * doubly linked tree.
 39    * </p>
 40    *
 41    * <p>
 42    * The tree built allows full XPath expressions from anywhere on the tree.
 43    * </p>
 44    *
 45    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 46    */
 47    public class DocumentFactory implements Serializable {
 48    private static SingletonStrategy singleton = null;
 49   
 50    protected transient QNameCache cache;
 51   
 52    /** Default namespace prefix -> URI mappings for XPath expressions to use */
 53    private Map xpathNamespaceURIs;
 54   
 55  90 private static SingletonStrategy createSingleton() {
 56  90 SingletonStrategy result = null;
 57   
 58  90 String documentFactoryClassName;
 59  90 try {
 60  90 documentFactoryClassName = System.getProperty("org.dom4j.factory",
 61    "org.dom4j.DocumentFactory");
 62    } catch (Exception e) {
 63  0 documentFactoryClassName = "org.dom4j.DocumentFactory";
 64    }
 65   
 66  90 try {
 67  90 String singletonClass = System.getProperty(
 68    "org.dom4j.DocumentFactory.singleton.strategy",
 69    "org.dom4j.util.SimpleSingleton");
 70  90 Class clazz = Class.forName(singletonClass);
 71  90 result = (SingletonStrategy) clazz.newInstance();
 72    } catch (Exception e) {
 73  0 result = new SimpleSingleton();
 74    }
 75   
 76  90 result.setSingletonClassName(documentFactoryClassName);
 77   
 78  90 return result;
 79    }
 80   
 81  541 public DocumentFactory() {
 82  541 init();
 83    }
 84   
 85    /**
 86    * <p>
 87    * Access to singleton implementation of DocumentFactory which is used if no
 88    * DocumentFactory is specified when building using the standard builders.
 89    * </p>
 90    *
 91    * @return the default singleon instance
 92    */
 93  27023 public static synchronized DocumentFactory getInstance() {
 94  27023 if (singleton == null) {
 95  90 singleton = createSingleton();
 96    }
 97  27023 return (DocumentFactory) singleton.instance();
 98    }
 99   
 100    // Factory methods
 101  6270 public Document createDocument() {
 102  6270 DefaultDocument answer = new DefaultDocument();
 103  6270 answer.setDocumentFactory(this);
 104   
 105  6270 return answer;
 106    }
 107   
 108    /**
 109    * DOCUMENT ME!
 110    *
 111    * @param encoding
 112    * DOCUMENT ME!
 113    *
 114    * @return DOCUMENT ME!
 115    *
 116    * @since 1.5
 117    */
 118  5816 public Document createDocument(String encoding) {
 119    // to keep the DocumentFactory backwards compatible, we have to do this
 120    // in this not so nice way, since subclasses only need to extend the
 121    // createDocument() method.
 122  5816 Document answer = createDocument();
 123   
 124  5816 if (answer instanceof AbstractDocument) {
 125  5816 ((AbstractDocument) answer).setXMLEncoding(encoding);
 126    }
 127   
 128  5816 return answer;
 129    }
 130   
 131  2 public Document createDocument(Element rootElement) {
 132  2 Document answer = createDocument();
 133  2 answer.setRootElement(rootElement);
 134   
 135  2 return answer;
 136    }
 137   
 138  11 public DocumentType createDocType(String name, String publicId,
 139    String systemId) {
 140  11 return new DefaultDocumentType(name, publicId, systemId);
 141    }
 142   
 143  94468 public Element createElement(QName qname) {
 144  94468 return new DefaultElement(qname);
 145    }
 146   
 147  465 public Element createElement(String name) {
 148  465 return createElement(createQName(name));
 149    }
 150   
 151  4 public Element createElement(String qualifiedName, String namespaceURI) {
 152  4 return createElement(createQName(qualifiedName, namespaceURI));
 153    }
 154   
 155  14165 public Attribute createAttribute(Element owner, QName qname, String value) {
 156  14165 return new DefaultAttribute(qname, value);
 157    }
 158   
 159  1630 public Attribute createAttribute(Element owner, String name, String value) {
 160  1630 return createAttribute(owner, createQName(name), value);
 161    }
 162   
 163  103 public CDATA createCDATA(String text) {
 164  103 return new DefaultCDATA(text);
 165    }
 166   
 167  503 public Comment createComment(String text) {
 168  503 return new DefaultComment(text);
 169    }
 170   
 171  121456 public Text createText(String text) {
 172  121456 if (text == null) {
 173  0 String msg = "Adding text to an XML document must not be null";
 174  0 throw new IllegalArgumentException(msg);
 175    }
 176   
 177  121456 return new DefaultText(text);
 178    }
 179   
 180  4 public Entity createEntity(String name, String text) {
 181  4 return new DefaultEntity(name, text);
 182    }
 183   
 184  100506 public Namespace createNamespace(String prefix, String uri) {
 185  100506 return Namespace.get(prefix, uri);
 186    }
 187   
 188  16 public ProcessingInstruction createProcessingInstruction(String target,
 189    String data) {
 190  16 return new DefaultProcessingInstruction(target, data);
 191    }
 192   
 193  0 public ProcessingInstruction createProcessingInstruction(String target,
 194    Map data) {
 195  0 return new DefaultProcessingInstruction(target, data);
 196    }
 197   
 198  104391 public QName createQName(String localName, Namespace namespace) {
 199  104391 return cache.get(localName, namespace);
 200    }
 201   
 202  12760 public QName createQName(String localName) {
 203  12760 return cache.get(localName);
 204    }
 205   
 206  16 public QName createQName(String name, String prefix, String uri) {
 207  16 return cache.get(name, Namespace.get(prefix, uri));
 208    }
 209   
 210  30 public QName createQName(String qualifiedName, String uri) {
 211  30 return cache.get(qualifiedName, uri);
 212    }
 213   
 214    /**
 215    * <p>
 216    * <code>createXPath</code> parses an XPath expression and creates a new
 217    * XPath <code>XPath</code> instance.
 218    * </p>
 219    *
 220    * @param xpathExpression
 221    * is the XPath expression to create
 222    *
 223    * @return a new <code>XPath</code> instance
 224    *
 225    * @throws InvalidXPathException
 226    * if the XPath expression is invalid
 227    */
 228  589 public XPath createXPath(String xpathExpression)
 229    throws InvalidXPathException {
 230  589 DefaultXPath xpath = new DefaultXPath(xpathExpression);
 231   
 232  585 if (xpathNamespaceURIs != null) {
 233  3 xpath.setNamespaceURIs(xpathNamespaceURIs);
 234    }
 235   
 236  585 return xpath;
 237    }
 238   
 239    /**
 240    * <p>
 241    * <code>createXPath</code> parses an XPath expression and creates a new
 242    * XPath <code>XPath</code> instance.
 243    * </p>
 244    *
 245    * @param xpathExpression
 246    * is the XPath expression to create
 247    * @param variableContext
 248    * is the variable context to use when evaluating the XPath
 249    *
 250    * @return a new <code>XPath</code> instance
 251    */
 252  1 public XPath createXPath(String xpathExpression,
 253    VariableContext variableContext) {
 254  1 XPath xpath = createXPath(xpathExpression);
 255  1 xpath.setVariableContext(variableContext);
 256   
 257  1 return xpath;
 258    }
 259   
 260    /**
 261    * <p>
 262    * <code>createXPathFilter</code> parses a NodeFilter from the given XPath
 263    * filter expression. XPath filter expressions occur within XPath
 264    * expressions such as <code>self::node()[ filterExpression ]</code>
 265    * </p>
 266    *
 267    * @param xpathFilterExpression
 268    * is the XPath filter expression to create
 269    * @param variableContext
 270    * is the variable context to use when evaluating the XPath
 271    *
 272    * @return a new <code>NodeFilter</code> instance
 273    */
 274  0 public NodeFilter createXPathFilter(String xpathFilterExpression,
 275    VariableContext variableContext) {
 276  0 XPath answer = createXPath(xpathFilterExpression);
 277   
 278    // DefaultXPath answer = new DefaultXPath( xpathFilterExpression );
 279  0 answer.setVariableContext(variableContext);
 280   
 281  0 return answer;
 282    }
 283   
 284    /**
 285    * <p>
 286    * <code>createXPathFilter</code> parses a NodeFilter from the given XPath
 287    * filter expression. XPath filter expressions occur within XPath
 288    * expressions such as <code>self::node()[ filterExpression ]</code>
 289    * </p>
 290    *
 291    * @param xpathFilterExpression
 292    * is the XPath filter expression to create
 293    *
 294    * @return a new <code>NodeFilter</code> instance
 295    */
 296  4 public NodeFilter createXPathFilter(String xpathFilterExpression) {
 297  4 return createXPath(xpathFilterExpression);
 298   
 299    // return new DefaultXPath( xpathFilterExpression );
 300    }
 301   
 302    /**
 303    * <p>
 304    * <code>createPattern</code> parses the given XPath expression to create
 305    * an XSLT style {@link Pattern}instance which can then be used in an XSLT
 306    * processing model.
 307    * </p>
 308    *
 309    * @param xpathPattern
 310    * is the XPath pattern expression to create
 311    *
 312    * @return a new <code>Pattern</code> instance
 313    */
 314  37 public Pattern createPattern(String xpathPattern) {
 315  37 return new XPathPattern(xpathPattern);
 316    }
 317   
 318    // Properties
 319    // -------------------------------------------------------------------------
 320   
 321    /**
 322    * Returns a list of all the QName instances currently used by this document
 323    * factory
 324    *
 325    * @return DOCUMENT ME!
 326    */
 327  1 public List getQNames() {
 328  1 return cache.getQNames();
 329    }
 330   
 331    /**
 332    * DOCUMENT ME!
 333    *
 334    * @return the Map of namespace URIs that will be used by by XPath
 335    * expressions to resolve namespace prefixes into namespace URIs.
 336    * The map is keyed by namespace prefix and the value is the
 337    * namespace URI. This value could well be null to indicate no
 338    * namespace URIs are being mapped.
 339    */
 340  0 public Map getXPathNamespaceURIs() {
 341  0 return xpathNamespaceURIs;
 342    }
 343   
 344    /**
 345    * Sets the namespace URIs to be used by XPath expressions created by this
 346    * factory or by nodes associated with this factory. The keys are namespace
 347    * prefixes and the values are namespace URIs.
 348    *
 349    * @param namespaceURIs
 350    * DOCUMENT ME!
 351    */
 352  2 public void setXPathNamespaceURIs(Map namespaceURIs) {
 353  2 this.xpathNamespaceURIs = namespaceURIs;
 354    }
 355   
 356    // Implementation methods
 357    // -------------------------------------------------------------------------
 358   
 359    /**
 360    * <p>
 361    * <code>createSingleton</code> creates the singleton instance from the
 362    * given class name.
 363    * </p>
 364    *
 365    * @param className
 366    * is the name of the DocumentFactory class to use
 367    *
 368    * @return a new singleton instance.
 369    */
 370  0 protected static DocumentFactory createSingleton(String className) {
 371    // let's try and class load an implementation?
 372  0 try {
 373    // I'll use the current class loader
 374    // that loaded me to avoid problems in J2EE and web apps
 375  0 Class theClass = Class.forName(className, true,
 376    DocumentFactory.class.getClassLoader());
 377   
 378  0 return (DocumentFactory) theClass.newInstance();
 379    } catch (Throwable e) {
 380  0 System.out.println("WARNING: Cannot load DocumentFactory: "
 381    + className);
 382   
 383  0 return new DocumentFactory();
 384    }
 385    }
 386   
 387    /**
 388    * DOCUMENT ME!
 389    *
 390    * @param qname
 391    * DOCUMENT ME!
 392    *
 393    * @return the cached QName instance if there is one or adds the given qname
 394    * to the cache if not
 395    */
 396  0 protected QName intern(QName qname) {
 397  0 return cache.intern(qname);
 398    }
 399   
 400    /**
 401    * Factory method to create the QNameCache. This method should be overloaded
 402    * if you wish to use your own derivation of QName.
 403    *
 404    * @return DOCUMENT ME!
 405    */
 406  544 protected QNameCache createQNameCache() {
 407  544 return new QNameCache(this);
 408    }
 409   
 410  3 private void readObject(ObjectInputStream in) throws IOException,
 411    ClassNotFoundException {
 412  3 in.defaultReadObject();
 413  3 init();
 414    }
 415   
 416  544 protected void init() {
 417  544 cache = createQNameCache();
 418    }
 419    }
 420   
 421    /*
 422    * Redistribution and use of this software and associated documentation
 423    * ("Software"), with or without modification, are permitted provided that the
 424    * following conditions are met:
 425    *
 426    * 1. Redistributions of source code must retain copyright statements and
 427    * notices. Redistributions must also contain a copy of this document.
 428    *
 429    * 2. Redistributions in binary form must reproduce the above copyright notice,
 430    * this list of conditions and the following disclaimer in the documentation
 431    * and/or other materials provided with the distribution.
 432    *
 433    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 434    * from this Software without prior written permission of MetaStuff, Ltd. For
 435    * written permission, please contact dom4j-info@metastuff.com.
 436    *
 437    * 4. Products derived from this Software may not be called "DOM4J" nor may
 438    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 439    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 440    *
 441    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 442    *
 443    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 444    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 445    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 446    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 447    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 448    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 449    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 450    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 451    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 452    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 453    * POSSIBILITY OF SUCH DAMAGE.
 454    *
 455    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 456    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/Comment.html0000644000175000017500000004205510242117765020415 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 56   Methods: 0
NCLOC: 3   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
Comment.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    /**
 11    * <p>
 12    * <code>Comment</code> defines the behavior of an XML comment.
 13    * </p>
 14    *
 15    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 16    * @version $Revision: 1.7 $
 17    */
 18    public interface Comment extends CharacterData {
 19    }
 20   
 21    /*
 22    * Redistribution and use of this software and associated documentation
 23    * ("Software"), with or without modification, are permitted provided that the
 24    * following conditions are met:
 25    *
 26    * 1. Redistributions of source code must retain copyright statements and
 27    * notices. Redistributions must also contain a copy of this document.
 28    *
 29    * 2. Redistributions in binary form must reproduce the above copyright notice,
 30    * this list of conditions and the following disclaimer in the documentation
 31    * and/or other materials provided with the distribution.
 32    *
 33    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 34    * from this Software without prior written permission of MetaStuff, Ltd. For
 35    * written permission, please contact dom4j-info@metastuff.com.
 36    *
 37    * 4. Products derived from this Software may not be called "DOM4J" nor may
 38    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 39    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 40    *
 41    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 42    *
 43    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 44    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 45    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 46    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 47    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 48    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 49    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 50    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 51    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 52    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 53    * POSSIBILITY OF SUCH DAMAGE.
 54    *
 55    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 56    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/util/0000755000175000017500000000000012133227266017073 5ustar ebourgebourgdom4j-1.6.1/docs/clover/org/dom4j/util/pkg-classes.html0000644000175000017500000000515210242117745022177 0ustar ebourgebourg dom4j - 1.6.1 org.dom4j.util
Classes
AttributeHelper (28,6%)
IndexedDocumentFactory (0%)
IndexedElement (0%)
NodeComparator (64%)
NonLazyDocumentFactory (0%)
NonLazyElement (0%)
PerThreadSingleton (76,2%)
ProxyDocumentFactory (0%)
SimpleSingleton (76,5%)
UserDataAttribute (25%)
UserDataDocumentFactory (100%)
UserDataElement (74,1%)
XMLErrorHandler (0%)
dom4j-1.6.1/docs/clover/org/dom4j/util/UserDataDocumentFactory.html0000644000175000017500000006337010242117711024521 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 90   Methods: 3
NCLOC: 18   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
UserDataDocumentFactory.java - 100% 100% 100%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.util;
 9   
 10    import org.dom4j.Attribute;
 11    import org.dom4j.DocumentFactory;
 12    import org.dom4j.Element;
 13    import org.dom4j.QName;
 14   
 15    /**
 16    * <p>
 17    * <code>UserDataDocumentFactory</code> is a factory of XML objects which
 18    * support the adornment of a user data object on an Element or Attribute
 19    * instance such that the methods <code>getData()</code> and
 20    * <code>setData()</code> will get and set the values of a user data object.
 21    * This can be useful for developers wishing to create XML trees and adorn the
 22    * trees with user defined objects.
 23    * </p>
 24    *
 25    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 26    * @version $Revision: 1.11 $
 27    */
 28    public class UserDataDocumentFactory extends DocumentFactory {
 29    /** The Singleton instance */
 30    protected static transient UserDataDocumentFactory singleton
 31    = new UserDataDocumentFactory();
 32   
 33    /**
 34    * <p>
 35    * Access to the singleton instance of this factory.
 36    * </p>
 37    *
 38    * @return the default singleon instance
 39    */
 40  5 public static DocumentFactory getInstance() {
 41  5 return singleton;
 42    }
 43   
 44    // DocumentFactory methods
 45    // -------------------------------------------------------------------------
 46  80 public Element createElement(QName qname) {
 47  80 return new UserDataElement(qname);
 48    }
 49   
 50  4 public Attribute createAttribute(Element owner, QName qname, String value) {
 51  4 return new UserDataAttribute(qname, value);
 52    }
 53    }
 54   
 55    /*
 56    * Redistribution and use of this software and associated documentation
 57    * ("Software"), with or without modification, are permitted provided that the
 58    * following conditions are met:
 59    *
 60    * 1. Redistributions of source code must retain copyright statements and
 61    * notices. Redistributions must also contain a copy of this document.
 62    *
 63    * 2. Redistributions in binary form must reproduce the above copyright notice,
 64    * this list of conditions and the following disclaimer in the documentation
 65    * and/or other materials provided with the distribution.
 66    *
 67    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 68    * from this Software without prior written permission of MetaStuff, Ltd. For
 69    * written permission, please contact dom4j-info@metastuff.com.
 70    *
 71    * 4. Products derived from this Software may not be called "DOM4J" nor may
 72    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 73    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 74    *
 75    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 76    *
 77    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 78    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 79    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 80    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 81    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 82    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 83    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 84    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 85    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 86    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 87    * POSSIBILITY OF SUCH DAMAGE.
 88    *
 89    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 90    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/util/IndexedDocumentFactory.html0000644000175000017500000006173110242117763024377 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 87   Methods: 3
NCLOC: 17   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
IndexedDocumentFactory.java - 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.util;
 9   
 10    import org.dom4j.DocumentFactory;
 11    import org.dom4j.Element;
 12    import org.dom4j.QName;
 13   
 14    /**
 15    * <p>
 16    * <code>IndexedDocumentFactory</code> is a factory of XML objects which
 17    * create indexed Element implementations to allow quicker lookup via name of
 18    * Element and Attributes though at the expense of more memory used to create
 19    * the name indexes.
 20    * </p>
 21    *
 22    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 23    * @version $Revision: 1.9 $
 24    */
 25    public class IndexedDocumentFactory extends DocumentFactory {
 26    /** The Singleton instance */
 27    protected static transient IndexedDocumentFactory singleton
 28    = new IndexedDocumentFactory();
 29   
 30    /**
 31    * <p>
 32    * Access to the singleton instance of this factory.
 33    * </p>
 34    *
 35    * @return the default singleon instance
 36    */
 37  0 public static DocumentFactory getInstance() {
 38  0 return singleton;
 39    }
 40   
 41    // DocumentFactory methods
 42    // -------------------------------------------------------------------------
 43  0 public Element createElement(QName qname) {
 44  0 return new IndexedElement(qname);
 45    }
 46   
 47  0 public Element createElement(QName qname, int attributeCount) {
 48  0 return new IndexedElement(qname, attributeCount);
 49    }
 50    }
 51   
 52    /*
 53    * Redistribution and use of this software and associated documentation
 54    * ("Software"), with or without modification, are permitted provided that the
 55    * following conditions are met:
 56    *
 57    * 1. Redistributions of source code must retain copyright statements and
 58    * notices. Redistributions must also contain a copy of this document.
 59    *
 60    * 2. Redistributions in binary form must reproduce the above copyright notice,
 61    * this list of conditions and the following disclaimer in the documentation
 62    * and/or other materials provided with the distribution.
 63    *
 64    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 65    * from this Software without prior written permission of MetaStuff, Ltd. For
 66    * written permission, please contact dom4j-info@metastuff.com.
 67    *
 68    * 4. Products derived from this Software may not be called "DOM4J" nor may
 69    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 70    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 71    *
 72    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 73    *
 74    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 75    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 76    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 77    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 78    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 79    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 80    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 81    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 82    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 83    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 84    * POSSIBILITY OF SUCH DAMAGE.
 85    *
 86    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 87    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/util/UserDataElement.html0000644000175000017500000010712110242117677023010 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 128   Methods: 9
NCLOC: 42   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
UserDataElement.java 50% 75% 77,8% 74,1%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.util;
 9   
 10    import org.dom4j.Element;
 11    import org.dom4j.QName;
 12    import org.dom4j.tree.DefaultElement;
 13   
 14    /**
 15    * <p>
 16    * <code>UserDataElement</code> support the adornment of a user data object on
 17    * an Element or Attribute instance such that the methods {@link#getData}
 18    * {@link #setData(Object)}will get and set the values of a user data object.
 19    * This can be useful for developers wishing to create XML trees and adorn the
 20    * trees with user defined objects.
 21    * </p>
 22    *
 23    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 24    * @version $Revision: 1.12 $
 25    */
 26    public class UserDataElement extends DefaultElement {
 27    /** The user data object */
 28    private Object data;
 29   
 30  0 public UserDataElement(String name) {
 31  0 super(name);
 32    }
 33   
 34  80 public UserDataElement(QName qname) {
 35  80 super(qname);
 36    }
 37   
 38  4 public Object getData() {
 39  4 return data;
 40    }
 41   
 42  2 public void setData(Object data) {
 43  2 this.data = data;
 44    }
 45   
 46  1 public String toString() {
 47  1 return super.toString() + " userData: " + data;
 48    }
 49   
 50  56 public Object clone() {
 51  56 UserDataElement answer = (UserDataElement) super.clone();
 52   
 53  56 if (answer != this) {
 54  56 answer.data = getCopyOfUserData();
 55    }
 56   
 57  56 return answer;
 58    }
 59   
 60    // Implementation methods
 61    // -------------------------------------------------------------------------
 62   
 63    /**
 64    * If a deep copy of user data is required whenever the clone() or
 65    * createCopy() methods are called on this element then this method should
 66    * return a clone of the user data
 67    *
 68    * @return DOCUMENT ME!
 69    */
 70  57 protected Object getCopyOfUserData() {
 71  57 return data;
 72    }
 73   
 74  0 protected Element createElement(String name) {
 75  0 Element answer = getDocumentFactory().createElement(name);
 76  0 answer.setData(getCopyOfUserData());
 77   
 78  0 return answer;
 79    }
 80   
 81  1 protected Element createElement(QName qName) {
 82  1 Element answer = getDocumentFactory().createElement(qName);
 83  1 answer.setData(getCopyOfUserData());
 84   
 85  1 return answer;
 86    }
 87   
 88    // protected DocumentFactory getDocumentFactory() {
 89    // return DOCUMENT_FACTORY;
 90    // }
 91    }
 92   
 93    /*
 94    * Redistribution and use of this software and associated documentation
 95    * ("Software"), with or without modification, are permitted provided that the
 96    * following conditions are met:
 97    *
 98    * 1. Redistributions of source code must retain copyright statements and
 99    * notices. Redistributions must also contain a copy of this document.
 100    *
 101    * 2. Redistributions in binary form must reproduce the above copyright notice,
 102    * this list of conditions and the following disclaimer in the documentation
 103    * and/or other materials provided with the distribution.
 104    *
 105    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 106    * from this Software without prior written permission of MetaStuff, Ltd. For
 107    * written permission, please contact dom4j-info@metastuff.com.
 108    *
 109    * 4. Products derived from this Software may not be called "DOM4J" nor may
 110    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 111    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 112    *
 113    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 114    *
 115    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 116    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 117    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 118    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 119    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 120    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 121    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 122    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 123    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 124    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 125    * POSSIBILITY OF SUCH DAMAGE.
 126    *
 127    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 128    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/util/NonLazyDocumentFactory.html0000644000175000017500000005755710242117740024417 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 83   Methods: 2
NCLOC: 14   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
NonLazyDocumentFactory.java - 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.util;
 9   
 10    import org.dom4j.DocumentFactory;
 11    import org.dom4j.Element;
 12    import org.dom4j.QName;
 13   
 14    /**
 15    * <p>
 16    * <code>NonLazyDocumentFactory</code> is a factory of XML objects which avoid
 17    * using the lazy creation pattern. This results in a slower creation of a
 18    * Document and uses more memory but it means that the same Document instance
 19    * can be shared across threads provided it is not modified.
 20    * </p>
 21    *
 22    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 23    * @version $Revision: 1.9 $
 24    */
 25    public class NonLazyDocumentFactory extends DocumentFactory {
 26    /** The Singleton instance */
 27    protected static transient NonLazyDocumentFactory singleton
 28    = new NonLazyDocumentFactory();
 29   
 30    /**
 31    * <p>
 32    * Access to the singleton instance of this factory.
 33    * </p>
 34    *
 35    * @return the default singleon instance
 36    */
 37  0 public static DocumentFactory getInstance() {
 38  0 return singleton;
 39    }
 40   
 41    // DocumentFactory methods
 42    // -------------------------------------------------------------------------
 43  0 public Element createElement(QName qname) {
 44  0 return new NonLazyElement(qname);
 45    }
 46    }
 47   
 48    /*
 49    * Redistribution and use of this software and associated documentation
 50    * ("Software"), with or without modification, are permitted provided that the
 51    * following conditions are met:
 52    *
 53    * 1. Redistributions of source code must retain copyright statements and
 54    * notices. Redistributions must also contain a copy of this document.
 55    *
 56    * 2. Redistributions in binary form must reproduce the above copyright notice,
 57    * this list of conditions and the following disclaimer in the documentation
 58    * and/or other materials provided with the distribution.
 59    *
 60    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 61    * from this Software without prior written permission of MetaStuff, Ltd. For
 62    * written permission, please contact dom4j-info@metastuff.com.
 63    *
 64    * 4. Products derived from this Software may not be called "DOM4J" nor may
 65    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 66    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 67    *
 68    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 69    *
 70    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 71    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 72    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 73    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 74    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 75    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 76    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 77    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 78    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 79    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 80    * POSSIBILITY OF SUCH DAMAGE.
 81    *
 82    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 83    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/util/pkg-summary.html0000644000175000017500000003312710242117730022234 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
package stats: LOC: 1.952   Methods: 119
NCLOC: 787   Classes: 14
Files: 14  
 
 Package Conditionals Statements Methods TOTAL
org.dom4j.util 29,3% 34,4% 26,9% 31,8%
coverage coverage
 
 Classes Conditionals Statements Methods TOTAL
IndexedDocumentFactory - 0% 0% 0%
coverage
IndexedElement 0% 0% 0% 0%
coverage
NonLazyDocumentFactory - 0% 0% 0%
coverage
NonLazyElement - 0% 0% 0%
coverage
ProxyDocumentFactory 0% 0% 0% 0%
coverage
XMLErrorHandler 0% 0% 0% 0%
coverage
UserDataAttribute - 25% 25% 25%
coverage coverage
AttributeHelper 16,7% 27,3% 50% 28,6%
coverage coverage
NodeComparator 50% 67,8% 92,3% 64%
coverage coverage
UserDataElement 50% 75% 77,8% 74,1%
coverage coverage
PerThreadSingleton 100% 73,3% 75% 76,2%
coverage coverage
SimpleSingleton 50% 72,7% 100% 76,5%
coverage coverage
UserDataDocumentFactory - 100% 100% 100%
coverage
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/util/ProxyDocumentFactory.html0000644000175000017500000015702210242117726024136 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 204   Methods: 27
NCLOC: 110   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
ProxyDocumentFactory.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.util;
 9   
 10    import java.util.Map;
 11   
 12    import org.dom4j.Attribute;
 13    import org.dom4j.CDATA;
 14    import org.dom4j.Comment;
 15    import org.dom4j.Document;
 16    import org.dom4j.DocumentFactory;
 17    import org.dom4j.DocumentType;
 18    import org.dom4j.Element;
 19    import org.dom4j.Entity;
 20    import org.dom4j.Namespace;
 21    import org.dom4j.NodeFilter;
 22    import org.dom4j.ProcessingInstruction;
 23    import org.dom4j.QName;
 24    import org.dom4j.Text;
 25    import org.dom4j.XPath;
 26    import org.dom4j.rule.Pattern;
 27   
 28    import org.jaxen.VariableContext;
 29   
 30    /**
 31    * <p>
 32    * <code>ProxyDocumentFactory</code> implements a proxy to a DocumentFactory
 33    * which is useful for implementation inheritence, allowing the pipelining of
 34    * various factory implementations. For example an EncodingDocumentFactory which
 35    * takes care of encoding strings outside of allowable XML ranges could be used
 36    * with a DatatypeDocumentFactory which is XML Schema Data Type aware.
 37    * </p>
 38    *
 39    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 40    * @version $Revision: 1.13 $
 41    */
 42    public abstract class ProxyDocumentFactory {
 43    private DocumentFactory proxy;
 44   
 45  0 public ProxyDocumentFactory() {
 46    // use default factory
 47  0 this.proxy = DocumentFactory.getInstance();
 48    }
 49   
 50  0 public ProxyDocumentFactory(DocumentFactory proxy) {
 51  0 this.proxy = proxy;
 52    }
 53   
 54    // Factory methods
 55    // -------------------------------------------------------------------------
 56  0 public Document createDocument() {
 57  0 return proxy.createDocument();
 58    }
 59   
 60  0 public Document createDocument(Element rootElement) {
 61  0 return proxy.createDocument(rootElement);
 62    }
 63   
 64  0 public DocumentType createDocType(String name, String publicId,
 65    String systemId) {
 66  0 return proxy.createDocType(name, publicId, systemId);
 67    }
 68   
 69  0 public Element createElement(QName qname) {
 70  0 return proxy.createElement(qname);
 71    }
 72   
 73  0 public Element createElement(String name) {
 74  0 return proxy.createElement(name);
 75    }
 76   
 77  0 public Attribute createAttribute(Element owner, QName qname, String value) {
 78  0 return proxy.createAttribute(owner, qname, value);
 79    }
 80   
 81  0 public Attribute createAttribute(Element owner, String name, String value) {
 82  0 return proxy.createAttribute(owner, name, value);
 83    }
 84   
 85  0 public CDATA createCDATA(String text) {
 86  0 return proxy.createCDATA(text);
 87    }
 88   
 89  0 public Comment createComment(String text) {
 90  0 return proxy.createComment(text);
 91    }
 92   
 93  0 public Text createText(String text) {
 94  0 return proxy.createText(text);
 95    }
 96   
 97  0 public Entity createEntity(String name, String text) {
 98  0 return proxy.createEntity(name, text);
 99    }
 100   
 101  0 public Namespace createNamespace(String prefix, String uri) {
 102  0 return proxy.createNamespace(prefix, uri);
 103    }
 104   
 105  0 public ProcessingInstruction createProcessingInstruction(String target,
 106    String data) {
 107  0 return proxy.createProcessingInstruction(target, data);
 108    }
 109   
 110  0 public ProcessingInstruction createProcessingInstruction(String target,
 111    Map data) {
 112  0 return proxy.createProcessingInstruction(target, data);
 113    }
 114   
 115  0 public QName createQName(String localName, Namespace namespace) {
 116  0 return proxy.createQName(localName, namespace);
 117    }
 118   
 119  0 public QName createQName(String localName) {
 120  0 return proxy.createQName(localName);
 121    }
 122   
 123  0 public QName createQName(String name, String prefix, String uri) {
 124  0 return proxy.createQName(name, prefix, uri);
 125    }
 126   
 127  0 public QName createQName(String qualifiedName, String uri) {
 128  0 return proxy.createQName(qualifiedName, uri);
 129    }
 130   
 131  0 public XPath createXPath(String xpathExpression) {
 132  0 return proxy.createXPath(xpathExpression);
 133    }
 134   
 135  0 public XPath createXPath(String xpathExpression,
 136    VariableContext variableContext) {
 137  0 return proxy.createXPath(xpathExpression, variableContext);
 138    }
 139   
 140  0 public NodeFilter createXPathFilter(String xpathFilterExpression,
 141    VariableContext variableContext) {
 142  0 return proxy.createXPathFilter(xpathFilterExpression, variableContext);
 143    }
 144   
 145  0 public NodeFilter createXPathFilter(String xpathFilterExpression) {
 146  0 return proxy.createXPathFilter(xpathFilterExpression);
 147    }
 148   
 149  0 public Pattern createPattern(String xpathPattern) {
 150  0 return proxy.createPattern(xpathPattern);
 151    }
 152   
 153    // Implementation methods
 154    // -------------------------------------------------------------------------
 155  0 protected DocumentFactory getProxy() {
 156  0 return proxy;
 157    }
 158   
 159  0 protected void setProxy(DocumentFactory proxy) {
 160  0 if (proxy == null) {
 161    // use default factory
 162  0 proxy = DocumentFactory.getInstance();
 163    }
 164   
 165  0 this.proxy = proxy;
 166    }
 167    }
 168   
 169    /*
 170    * Redistribution and use of this software and associated documentation
 171    * ("Software"), with or without modification, are permitted provided that the
 172    * following conditions are met:
 173    *
 174    * 1. Redistributions of source code must retain copyright statements and
 175    * notices. Redistributions must also contain a copy of this document.
 176    *
 177    * 2. Redistributions in binary form must reproduce the above copyright notice,
 178    * this list of conditions and the following disclaimer in the documentation
 179    * and/or other materials provided with the distribution.
 180    *
 181    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 182    * from this Software without prior written permission of MetaStuff, Ltd. For
 183    * written permission, please contact dom4j-info@metastuff.com.
 184    *
 185    * 4. Products derived from this Software may not be called "DOM4J" nor may
 186    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 187    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 188    *
 189    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 190    *
 191    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 192    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 193    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 194    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 195    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 196    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 197    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 198    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 199    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 200    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 201    * POSSIBILITY OF SUCH DAMAGE.
 202    *
 203    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 204    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/util/SimpleSingleton.html0000644000175000017500000006646610242117723023112 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 94   Methods: 4
NCLOC: 30   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
SimpleSingleton.java 50% 72,7% 100% 76,5%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.util;
 9   
 10    /**
 11    * <p>
 12    * <code>SimpleSingleton</code> is an implementation of the SingletonStrategy
 13    * interface used to provide common factory access for the same object instance.
 14    * This implementation will create a new instance from the class specified and
 15    * will not create a new one unless it is reset.
 16    * </p>
 17    *
 18    * @author <a href="mailto:ddlucas@users.sourceforge.net">David Lucas </a>
 19    * @version $Revision: 1.3 $
 20    */
 21   
 22    public class SimpleSingleton implements SingletonStrategy {
 23    private String singletonClassName = null;
 24   
 25    private Object singletonInstance = null;
 26   
 27  183 public SimpleSingleton() {
 28    }
 29   
 30  41671 public Object instance() {
 31  41671 return singletonInstance;
 32    }
 33   
 34  183 public void reset() {
 35  183 if (singletonClassName != null) {
 36  183 Class clazz = null;
 37  183 try {
 38  183 clazz = Thread.currentThread().getContextClassLoader().loadClass(
 39    singletonClassName);
 40  183 singletonInstance = clazz.newInstance();
 41    } catch (Exception ignore) {
 42  0 try {
 43  0 clazz = Class.forName(singletonClassName);
 44  0 singletonInstance = clazz.newInstance();
 45    } catch (Exception ignore2) {
 46    }
 47    }
 48   
 49    }
 50    }
 51   
 52  183 public void setSingletonClassName(String singletonClassName) {
 53  183 this.singletonClassName = singletonClassName;
 54  183 reset();
 55    }
 56   
 57    }
 58   
 59    /*
 60    * Redistribution and use of this software and associated documentation
 61    * ("Software"), with or without modification, are permitted provided that the
 62    * following conditions are met:
 63    *
 64    * 1. Redistributions of source code must retain copyright statements and
 65    * notices. Redistributions must also contain a copy of this document.
 66    *
 67    * 2. Redistributions in binary form must reproduce the above copyright notice,
 68    * this list of conditions and the following disclaimer in the documentation
 69    * and/or other materials provided with the distribution.
 70    *
 71    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 72    * from this Software without prior written permission of MetaStuff, Ltd. For
 73    * written permission, please contact dom4j-info@metastuff.com.
 74    *
 75    * 4. Products derived from this Software may not be called "DOM4J" nor may
 76    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 77    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 78    *
 79    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 80    *
 81    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 82    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 83    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 84    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 85    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 86    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 87    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 88    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 89    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 90    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 91    * POSSIBILITY OF SUCH DAMAGE.
 92    *
 93    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 94    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/util/NonLazyElement.html0000644000175000017500000006210410242117732022663 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 84   Methods: 4
NCLOC: 26   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
NonLazyElement.java - 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.util;
 9   
 10    import org.dom4j.Namespace;
 11    import org.dom4j.QName;
 12    import org.dom4j.tree.BaseElement;
 13   
 14    /**
 15    * <p>
 16    * <code>NonLazyElement</code> is the default DOM4J default implementation of
 17    * an XML element.
 18    * </p>
 19    *
 20    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 21    * @version $Revision: 1.8 $
 22    */
 23    public class NonLazyElement extends BaseElement {
 24  0 public NonLazyElement(String name) {
 25  0 super(name);
 26  0 this.attributes = createAttributeList();
 27  0 this.content = createContentList();
 28    }
 29   
 30  0 public NonLazyElement(QName qname) {
 31  0 super(qname);
 32  0 this.attributes = createAttributeList();
 33  0 this.content = createContentList();
 34    }
 35   
 36  0 public NonLazyElement(String name, Namespace namespace) {
 37  0 super(name, namespace);
 38  0 this.attributes = createAttributeList();
 39  0 this.content = createContentList();
 40    }
 41   
 42  0 public NonLazyElement(QName qname, int attributeCount) {
 43  0 super(qname);
 44  0 this.attributes = createAttributeList(attributeCount);
 45  0 this.content = createContentList();
 46    }
 47    }
 48   
 49    /*
 50    * Redistribution and use of this software and associated documentation
 51    * ("Software"), with or without modification, are permitted provided that the
 52    * following conditions are met:
 53    *
 54    * 1. Redistributions of source code must retain copyright statements and
 55    * notices. Redistributions must also contain a copy of this document.
 56    *
 57    * 2. Redistributions in binary form must reproduce the above copyright notice,
 58    * this list of conditions and the following disclaimer in the documentation
 59    * and/or other materials provided with the distribution.
 60    *
 61    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 62    * from this Software without prior written permission of MetaStuff, Ltd. For
 63    * written permission, please contact dom4j-info@metastuff.com.
 64    *
 65    * 4. Products derived from this Software may not be called "DOM4J" nor may
 66    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 67    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 68    *
 69    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 70    *
 71    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 72    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 73    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 74    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 75    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 76    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 77    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 78    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 79    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 80    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 81    * POSSIBILITY OF SUCH DAMAGE.
 82    *
 83    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 84    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/util/PerThreadSingleton.html0000644000175000017500000007401110242117700023513 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 103   Methods: 4
NCLOC: 36   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
PerThreadSingleton.java 100% 73,3% 75% 76,2%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.util;
 9   
 10    import java.lang.ref.WeakReference;
 11   
 12    /**
 13    * <p>
 14    * <code>PerThreadSingleton</code> is an implementation of the
 15    * SingletonStrategy used to provide common factory access to a single object
 16    * instance based on an implementation strategy for one object instance per
 17    * thread. This is useful in replace of the ThreadLocal usage.
 18    * </p>
 19    *
 20    * @author <a href="mailto:ddlucas@users.sourceforge.net">David Lucas </a>
 21    * @version $Revision: 1.3 $
 22    */
 23   
 24    public class PerThreadSingleton implements SingletonStrategy {
 25    private String singletonClassName = null;
 26   
 27    private ThreadLocal perThreadCache = new ThreadLocal();
 28   
 29  2 public PerThreadSingleton() {
 30    }
 31   
 32  0 public void reset() {
 33  0 perThreadCache = new ThreadLocal();
 34    }
 35   
 36  1003 public Object instance() {
 37  1003 Object singletonInstancePerThread = null;
 38    // use weak reference to prevent cyclic reference during GC
 39  1003 WeakReference ref = (WeakReference) perThreadCache.get();
 40    // singletonInstancePerThread=perThreadCache.get();
 41    // if (singletonInstancePerThread==null) {
 42  1003 if (ref == null || ref.get() == null) {
 43  6 Class clazz = null;
 44  6 try {
 45  6 clazz = Thread.currentThread().getContextClassLoader().loadClass(
 46    singletonClassName);
 47  6 singletonInstancePerThread = clazz.newInstance();
 48    } catch (Exception ignore) {
 49  0 try {
 50  0 clazz = Class.forName(singletonClassName);
 51  0 singletonInstancePerThread = clazz.newInstance();
 52    } catch (Exception ignore2) {
 53    }
 54    }
 55  6 perThreadCache.set(new WeakReference(singletonInstancePerThread));
 56    } else {
 57  997 singletonInstancePerThread = ref.get();
 58    }
 59  1003 return singletonInstancePerThread;
 60    }
 61   
 62  2 public void setSingletonClassName(String singletonClassName) {
 63  2 this.singletonClassName = singletonClassName;
 64    }
 65   
 66    }
 67   
 68    /*
 69    * Redistribution and use of this software and associated documentation
 70    * ("Software"), with or without modification, are permitted provided that the
 71    * following conditions are met:
 72    *
 73    * 1. Redistributions of source code must retain copyright statements and
 74    * notices. Redistributions must also contain a copy of this document.
 75    *
 76    * 2. Redistributions in binary form must reproduce the above copyright notice,
 77    * this list of conditions and the following disclaimer in the documentation
 78    * and/or other materials provided with the distribution.
 79    *
 80    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 81    * from this Software without prior written permission of MetaStuff, Ltd. For
 82    * written permission, please contact dom4j-info@metastuff.com.
 83    *
 84    * 4. Products derived from this Software may not be called "DOM4J" nor may
 85    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 86    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 87    *
 88    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 89    *
 90    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 91    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 92    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 93    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 94    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 95    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 96    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 97    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 98    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 99    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 100    * POSSIBILITY OF SUCH DAMAGE.
 101    *
 102    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 103    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/util/IndexedElement.html0000644000175000017500000026016310242117700022651 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 321   Methods: 28
NCLOC: 182   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
IndexedElement.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.util;
 9   
 10    import java.util.ArrayList;
 11    import java.util.HashMap;
 12    import java.util.Iterator;
 13    import java.util.List;
 14    import java.util.Map;
 15   
 16    import org.dom4j.Attribute;
 17    import org.dom4j.Element;
 18    import org.dom4j.Node;
 19    import org.dom4j.QName;
 20    import org.dom4j.tree.BackedList;
 21    import org.dom4j.tree.DefaultElement;
 22   
 23    /**
 24    * <p>
 25    * <code>IndexedElement</code> is an implementation of {@link Element}which
 26    * maintains an index of the attributes and elements it contains to optimise
 27    * lookups via name.
 28    * </p>
 29    *
 30    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 31    * @version $Revision: 1.10 $
 32    */
 33    public class IndexedElement extends DefaultElement {
 34    /** Lazily constructed index for elements */
 35    private Map elementIndex;
 36   
 37    /** Lazily constructed index for attributes */
 38    private Map attributeIndex;
 39   
 40  0 public IndexedElement(String name) {
 41  0 super(name);
 42    }
 43   
 44  0 public IndexedElement(QName qname) {
 45  0 super(qname);
 46    }
 47   
 48  0 public IndexedElement(QName qname, int attributeCount) {
 49  0 super(qname, attributeCount);
 50    }
 51   
 52  0 public Attribute attribute(String name) {
 53  0 return (Attribute) attributeIndex().get(name);
 54    }
 55   
 56  0 public Attribute attribute(QName qName) {
 57  0 return (Attribute) attributeIndex().get(qName);
 58    }
 59   
 60  0 public Element element(String name) {
 61  0 return asElement(elementIndex().get(name));
 62    }
 63   
 64  0 public Element element(QName qName) {
 65  0 return asElement(elementIndex().get(qName));
 66    }
 67   
 68  0 public List elements(String name) {
 69  0 return asElementList(elementIndex().get(name));
 70    }
 71   
 72  0 public List elements(QName qName) {
 73  0 return asElementList(elementIndex().get(qName));
 74    }
 75   
 76    // Implementation methods
 77    // -------------------------------------------------------------------------
 78  0 protected Element asElement(Object object) {
 79  0 if (object instanceof Element) {
 80  0 return (Element) object;
 81  0 } else if (object != null) {
 82  0 List list = (List) object;
 83   
 84  0 if (list.size() >= 1) {
 85  0 return (Element) list.get(0);
 86    }
 87    }
 88   
 89  0 return null;
 90    }
 91   
 92  0 protected List asElementList(Object object) {
 93  0 if (object instanceof Element) {
 94  0 return createSingleResultList(object);
 95  0 } else if (object != null) {
 96  0 List list = (List) object;
 97  0 BackedList answer = createResultList();
 98   
 99  0 for (int i = 0, size = list.size(); i < size; i++) {
 100  0 answer.addLocal(list.get(i));
 101    }
 102   
 103  0 return answer;
 104    }
 105   
 106  0 return createEmptyList();
 107    }
 108   
 109    /**
 110    * DOCUMENT ME!
 111    *
 112    * @param object
 113    * DOCUMENT ME!
 114    *
 115    * @return DOCUMENT ME!
 116    *
 117    * @deprecated WILL BE REMOVED IN dom4j-1.6 !!
 118    */
 119  0 protected Iterator asElementIterator(Object object) {
 120  0 return asElementList(object).iterator();
 121    }
 122   
 123    // #### could we override the add(Element) remove(Element methods?
 124  0 protected void addNode(Node node) {
 125  0 super.addNode(node);
 126   
 127  0 if ((elementIndex != null) && node instanceof Element) {
 128  0 addToElementIndex((Element) node);
 129  0 } else if ((attributeIndex != null) && node instanceof Attribute) {
 130  0 addToAttributeIndex((Attribute) node);
 131    }
 132    }
 133   
 134  0 protected boolean removeNode(Node node) {
 135  0 if (super.removeNode(node)) {
 136  0 if ((elementIndex != null) && node instanceof Element) {
 137  0 removeFromElementIndex((Element) node);
 138  0 } else if ((attributeIndex != null) && node instanceof Attribute) {
 139  0 removeFromAttributeIndex((Attribute) node);
 140    }
 141   
 142  0 return true;
 143    }
 144   
 145  0 return false;
 146    }
 147   
 148  0 protected Map attributeIndex() {
 149  0 if (attributeIndex == null) {
 150  0 attributeIndex = createAttributeIndex();
 151   
 152  0 for (Iterator iter = attributeIterator(); iter.hasNext();) {
 153  0 addToAttributeIndex((Attribute) iter.next());
 154    }
 155    }
 156   
 157  0 return attributeIndex;
 158    }
 159   
 160  0 protected Map elementIndex() {
 161  0 if (elementIndex == null) {
 162  0 elementIndex = createElementIndex();
 163   
 164  0 for (Iterator iter = elementIterator(); iter.hasNext();) {
 165  0 addToElementIndex((Element) iter.next());
 166    }
 167    }
 168   
 169  0 return elementIndex;
 170    }
 171   
 172    /**
 173    * A Factory Method to create the index for attributes
 174    *
 175    * @return DOCUMENT ME!
 176    */
 177  0 protected Map createAttributeIndex() {
 178  0 Map answer = createIndex();
 179   
 180  0 return answer;
 181    }
 182   
 183    /**
 184    * A Factory Method to create the index for elements
 185    *
 186    * @return DOCUMENT ME!
 187    */
 188  0 protected Map createElementIndex() {
 189  0 Map answer = createIndex();
 190   
 191  0 return answer;
 192    }
 193   
 194  0 protected void addToElementIndex(Element element) {
 195  0 QName qName = element.getQName();
 196  0 String name = qName.getName();
 197  0 addToElementIndex(qName, element);
 198  0 addToElementIndex(name, element);
 199    }
 200   
 201  0 protected void addToElementIndex(Object key, Element value) {
 202  0 Object oldValue = elementIndex.get(key);
 203   
 204  0 if (oldValue == null) {
 205  0 elementIndex.put(key, value);
 206    } else {
 207  0 if (oldValue instanceof List) {
 208  0 List list = (List) oldValue;
 209  0 list.add(value);
 210    } else {
 211  0 List list = createList();
 212  0 list.add(oldValue);
 213  0 list.add(value);
 214  0 elementIndex.put(key, list);
 215    }
 216    }
 217    }
 218   
 219  0 protected void removeFromElementIndex(Element element) {
 220  0 QName qName = element.getQName();
 221  0 String name = qName.getName();
 222  0 removeFromElementIndex(qName, element);
 223  0 removeFromElementIndex(name, element);
 224    }
 225   
 226  0 protected void removeFromElementIndex(Object key, Element value) {
 227  0 Object oldValue = elementIndex.get(key);
 228   
 229  0 if (oldValue instanceof List) {
 230  0 List list = (List) oldValue;
 231  0 list.remove(value);
 232    } else {
 233  0 elementIndex.remove(key);
 234    }
 235    }
 236   
 237  0 protected void addToAttributeIndex(Attribute attribute) {
 238  0 QName qName = attribute.getQName();
 239  0 String name = qName.getName();
 240  0 addToAttributeIndex(qName, attribute);
 241  0 addToAttributeIndex(name, attribute);
 242    }
 243   
 244  0 protected void addToAttributeIndex(Object key, Attribute value) {
 245  0 Object oldValue = attributeIndex.get(key);
 246   
 247  0 if (oldValue != null) {
 248  0 attributeIndex.put(key, value);
 249    }
 250    }
 251   
 252  0 protected void removeFromAttributeIndex(Attribute attribute) {
 253  0 QName qName = attribute.getQName();
 254  0 String name = qName.getName();
 255  0 removeFromAttributeIndex(qName, attribute);
 256  0 removeFromAttributeIndex(name, attribute);
 257    }
 258   
 259  0 protected void removeFromAttributeIndex(Object key, Attribute value) {
 260  0 Object oldValue = attributeIndex.get(key);
 261   
 262  0 if ((oldValue != null) && oldValue.equals(value)) {
 263  0 attributeIndex.remove(key);
 264    }
 265    }
 266   
 267    /**
 268    * Factory method to return a new map implementation for indices
 269    *
 270    * @return DOCUMENT ME!
 271    */
 272  0 protected Map createIndex() {
 273  0 return new HashMap();
 274    }
 275   
 276    /**
 277    * Factory method to return a list implementation for indices
 278    *
 279    * @return DOCUMENT ME!
 280    */
 281  0 protected List createList() {
 282  0 return new ArrayList();
 283    }
 284    }
 285   
 286    /*
 287    * Redistribution and use of this software and associated documentation
 288    * ("Software"), with or without modification, are permitted provided that the
 289    * following conditions are met:
 290    *
 291    * 1. Redistributions of source code must retain copyright statements and
 292    * notices. Redistributions must also contain a copy of this document.
 293    *
 294    * 2. Redistributions in binary form must reproduce the above copyright notice,
 295    * this list of conditions and the following disclaimer in the documentation
 296    * and/or other materials provided with the distribution.
 297    *
 298    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 299    * from this Software without prior written permission of MetaStuff, Ltd. For
 300    * written permission, please contact dom4j-info@metastuff.com.
 301    *
 302    * 4. Products derived from this Software may not be called "DOM4J" nor may
 303    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 304    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 305    *
 306    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 307    *
 308    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 309    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 310    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 311    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 312    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 313    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 314    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 315    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 316    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 317    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 318    * POSSIBILITY OF SUCH DAMAGE.
 319    *
 320    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 321    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/util/SingletonStrategy.html0000644000175000017500000005342410242117760023452 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 76   Methods: 0
NCLOC: 6   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
SingletonStrategy.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.util;
 9   
 10    /**
 11    * <p>
 12    * <code>SingletonStrategy</code> is an interface used to provide common
 13    * factory access for the same object based on an implementation strategy for
 14    * singleton. Right now there are two that accompany this interface:
 15    * SimpleSingleton and PerThreadSingleton. This will replace previous usage of
 16    * ThreadLocal to allow for alternate strategies.
 17    * </p>
 18    *
 19    * @author <a href="mailto:ddlucas@users.sourceforge.net">David Lucas </a>
 20    * @version $Revision: 1.2 $
 21    */
 22    public interface SingletonStrategy {
 23    /**
 24    * return a singleton instance of the class specified in setSingletonClass
 25    */
 26    Object instance();
 27   
 28    /**
 29    * reset the instance to a new instance for the implemented strategy
 30    */
 31    void reset();
 32   
 33    /**
 34    * set a singleton class name that will be used to create the singleton
 35    * based on the strategy implementation of this interface. The default
 36    * constructor of the class will be used and must be public.
 37    */
 38    void setSingletonClassName(String singletonClassName);
 39    }
 40   
 41    /*
 42    * Redistribution and use of this software and associated documentation
 43    * ("Software"), with or without modification, are permitted provided that the
 44    * following conditions are met:
 45    *
 46    * 1. Redistributions of source code must retain copyright statements and
 47    * notices. Redistributions must also contain a copy of this document.
 48    *
 49    * 2. Redistributions in binary form must reproduce the above copyright notice,
 50    * this list of conditions and the following disclaimer in the documentation
 51    * and/or other materials provided with the distribution.
 52    *
 53    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 54    * from this Software without prior written permission of MetaStuff, Ltd. For
 55    * written permission, please contact dom4j-info@metastuff.com.
 56    *
 57    * 4. Products derived from this Software may not be called "DOM4J" nor may
 58    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 59    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 60    *
 61    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 62    *
 63    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 64    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 65    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 66    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 67    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 68    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 69    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 70    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 71    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 72    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 73    * POSSIBILITY OF SUCH DAMAGE.
 74    *
 75    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 76    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/util/AttributeHelper.html0000644000175000017500000006456310242117704023074 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 89   Methods: 4
NCLOC: 28   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
AttributeHelper.java 16,7% 27,3% 50% 28,6%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.util;
 9   
 10    import org.dom4j.Attribute;
 11    import org.dom4j.Element;
 12    import org.dom4j.QName;
 13   
 14    /**
 15    * <p>
 16    * <code>AttributeHelper</code> a number of helper methods for working with
 17    * attribute values.
 18    * </p>
 19    *
 20    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 21    * @version $Revision: 1.7 $
 22    */
 23    public class AttributeHelper {
 24  0 protected AttributeHelper() {
 25    }
 26   
 27  103 public static boolean booleanValue(Element element, String attributeName) {
 28  103 return booleanValue(element.attribute(attributeName));
 29    }
 30   
 31  0 public static boolean booleanValue(Element element, QName attributeQName) {
 32  0 return booleanValue(element.attribute(attributeQName));
 33    }
 34   
 35  103 protected static boolean booleanValue(Attribute attribute) {
 36  103 if (attribute == null) {
 37  103 return false;
 38    }
 39   
 40  0 Object value = attribute.getData();
 41   
 42  0 if (value == null) {
 43  0 return false;
 44  0 } else if (value instanceof Boolean) {
 45  0 Boolean b = (Boolean) value;
 46   
 47  0 return b.booleanValue();
 48    } else {
 49  0 return "true".equalsIgnoreCase(value.toString());
 50    }
 51    }
 52    }
 53   
 54    /*
 55    * Redistribution and use of this software and associated documentation
 56    * ("Software"), with or without modification, are permitted provided that the
 57    * following conditions are met:
 58    *
 59    * 1. Redistributions of source code must retain copyright statements and
 60    * notices. Redistributions must also contain a copy of this document.
 61    *
 62    * 2. Redistributions in binary form must reproduce the above copyright notice,
 63    * this list of conditions and the following disclaimer in the documentation
 64    * and/or other materials provided with the distribution.
 65    *
 66    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 67    * from this Software without prior written permission of MetaStuff, Ltd. For
 68    * written permission, please contact dom4j-info@metastuff.com.
 69    *
 70    * 4. Products derived from this Software may not be called "DOM4J" nor may
 71    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 72    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 73    *
 74    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 75    *
 76    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 77    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 78    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 79    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 80    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 81    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 82    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 83    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 84    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 85    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 86    * POSSIBILITY OF SUCH DAMAGE.
 87    *
 88    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 89    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/util/UserDataAttribute.html0000644000175000017500000005712710242117732023364 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 81   Methods: 4
NCLOC: 18   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
UserDataAttribute.java - 25% 25% 25%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.util;
 9   
 10    import org.dom4j.QName;
 11    import org.dom4j.tree.DefaultAttribute;
 12   
 13    /**
 14    * <p>
 15    * <code>UserDataAttribute</code> support the adornment of a user data object
 16    * on an Element or Attribute instance such that the methods {@link#getData}
 17    * {@link #setData(Object)}will get and set the values of a user data object.
 18    * This can be useful for developers wishing to create XML trees and adorn the
 19    * trees with user defined objects.
 20    * </p>
 21    *
 22    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 23    * @version $Revision: 1.8 $
 24    */
 25    public class UserDataAttribute extends DefaultAttribute {
 26    /** The user data object */
 27    private Object data;
 28   
 29  0 public UserDataAttribute(QName qname) {
 30  0 super(qname);
 31    }
 32   
 33  4 public UserDataAttribute(QName qname, String text) {
 34  4 super(qname, text);
 35    }
 36   
 37  0 public Object getData() {
 38  0 return data;
 39    }
 40   
 41  0 public void setData(Object data) {
 42  0 this.data = data;
 43    }
 44    }
 45   
 46    /*
 47    * Redistribution and use of this software and associated documentation
 48    * ("Software"), with or without modification, are permitted provided that the
 49    * following conditions are met:
 50    *
 51    * 1. Redistributions of source code must retain copyright statements and
 52    * notices. Redistributions must also contain a copy of this document.
 53    *
 54    * 2. Redistributions in binary form must reproduce the above copyright notice,
 55    * this list of conditions and the following disclaimer in the documentation
 56    * and/or other materials provided with the distribution.
 57    *
 58    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 59    * from this Software without prior written permission of MetaStuff, Ltd. For
 60    * written permission, please contact dom4j-info@metastuff.com.
 61    *
 62    * 4. Products derived from this Software may not be called "DOM4J" nor may
 63    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 64    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 65    *
 66    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 67    *
 68    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 69    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 70    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 71    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 72    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 73    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 74    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 75    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 76    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 77    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 78    * POSSIBILITY OF SUCH DAMAGE.
 79    *
 80    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 81    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/util/XMLErrorHandler.html0000644000175000017500000013411610242117715022733 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 168   Methods: 14
NCLOC: 70   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
XMLErrorHandler.java 0% 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.util;
 9   
 10    import org.dom4j.DocumentHelper;
 11    import org.dom4j.Element;
 12    import org.dom4j.QName;
 13   
 14    import org.xml.sax.ErrorHandler;
 15    import org.xml.sax.SAXParseException;
 16   
 17    /**
 18    * <code>XMLErrorHandler</code> is a SAX {@link ErrorHandler}which turns the
 19    * SAX parsing errors into XML so that the output can be formatted using XSLT or
 20    * the errors can be included in a SOAP message.
 21    *
 22    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 23    * @version $Revision: 1.7 $
 24    */
 25    public class XMLErrorHandler implements ErrorHandler {
 26    protected static final QName ERROR_QNAME = QName.get("error");
 27   
 28    protected static final QName FATALERROR_QNAME = QName.get("fatalError");
 29   
 30    protected static final QName WARNING_QNAME = QName.get("warning");
 31   
 32    /** Stores the errors that occur during a SAX parse */
 33    private Element errors;
 34   
 35    /** QName used for error elements */
 36    private QName errorQName = ERROR_QNAME;
 37   
 38    /** QName used for fatalerror elements */
 39    private QName fatalErrorQName = FATALERROR_QNAME;
 40   
 41    /** QName used for warning elements */
 42    private QName warningQName = WARNING_QNAME;
 43   
 44  0 public XMLErrorHandler() {
 45  0 this.errors = DocumentHelper.createElement("errors");
 46    }
 47   
 48  0 public XMLErrorHandler(Element errors) {
 49  0 this.errors = errors;
 50    }
 51   
 52  0 public void error(SAXParseException e) {
 53  0 Element element = errors.addElement(errorQName);
 54  0 addException(element, e);
 55    }
 56   
 57  0 public void fatalError(SAXParseException e) {
 58  0 Element element = errors.addElement(fatalErrorQName);
 59  0 addException(element, e);
 60    }
 61   
 62  0 public void warning(SAXParseException e) {
 63  0 Element element = errors.addElement(warningQName);
 64  0 addException(element, e);
 65    }
 66   
 67    // Properties
 68    // -------------------------------------------------------------------------
 69  0 public Element getErrors() {
 70  0 return errors;
 71    }
 72   
 73  0 public void setErrors(Element errors) {
 74  0 this.errors = errors;
 75    }
 76   
 77    // Allow the QNames used to create subelements to be changed
 78  0 public QName getErrorQName() {
 79  0 return errorQName;
 80    }
 81   
 82  0 public void setErrorQName(QName errorQName) {
 83  0 this.errorQName = errorQName;
 84    }
 85   
 86  0 public QName getFatalErrorQName() {
 87  0 return fatalErrorQName;
 88    }
 89   
 90  0 public void setFatalErrorQName(QName fatalErrorQName) {
 91  0 this.fatalErrorQName = fatalErrorQName;
 92    }
 93   
 94  0 public QName getWarningQName() {
 95  0 return warningQName;
 96    }
 97   
 98  0 public void setWarningQName(QName warningQName) {
 99  0 this.warningQName = warningQName;
 100    }
 101   
 102    // Implementation methods
 103    // -------------------------------------------------------------------------
 104   
 105    /**
 106    * Adds the given parse exception information to the given element instance
 107    *
 108    * @param element
 109    * DOCUMENT ME!
 110    * @param e
 111    * DOCUMENT ME!
 112    */
 113  0 protected void addException(Element element, SAXParseException e) {
 114  0 element.addAttribute("column", Integer.toString(e.getColumnNumber()));
 115  0 element.addAttribute("line", Integer.toString(e.getLineNumber()));
 116   
 117  0 String publicID = e.getPublicId();
 118   
 119  0 if ((publicID != null) && (publicID.length() > 0)) {
 120  0 element.addAttribute("publicID", publicID);
 121    }
 122   
 123  0 String systemID = e.getSystemId();
 124   
 125  0 if ((systemID != null) && (systemID.length() > 0)) {
 126  0 element.addAttribute("systemID", systemID);
 127    }
 128   
 129  0 element.addText(e.getMessage());
 130    }
 131    }
 132   
 133    /*
 134    * Redistribution and use of this software and associated documentation
 135    * ("Software"), with or without modification, are permitted provided that the
 136    * following conditions are met:
 137    *
 138    * 1. Redistributions of source code must retain copyright statements and
 139    * notices. Redistributions must also contain a copy of this document.
 140    *
 141    * 2. Redistributions in binary form must reproduce the above copyright notice,
 142    * this list of conditions and the following disclaimer in the documentation
 143    * and/or other materials provided with the distribution.
 144    *
 145    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 146    * from this Software without prior written permission of MetaStuff, Ltd. For
 147    * written permission, please contact dom4j-info@metastuff.com.
 148    *
 149    * 4. Products derived from this Software may not be called "DOM4J" nor may
 150    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 151    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 152    *
 153    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 154    *
 155    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 156    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 157    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 158    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 159    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 160    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 161    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 162    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 163    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 164    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 165    * POSSIBILITY OF SUCH DAMAGE.
 166    *
 167    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 168    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/util/NodeComparator.html0000644000175000017500000030230310242117727022676 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 344   Methods: 13
NCLOC: 190   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
NodeComparator.java 50% 67,8% 92,3% 64%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.util;
 9   
 10    import java.util.Comparator;
 11   
 12    import org.dom4j.Attribute;
 13    import org.dom4j.Branch;
 14    import org.dom4j.CDATA;
 15    import org.dom4j.CharacterData;
 16    import org.dom4j.Comment;
 17    import org.dom4j.Document;
 18    import org.dom4j.DocumentType;
 19    import org.dom4j.Element;
 20    import org.dom4j.Entity;
 21    import org.dom4j.Namespace;
 22    import org.dom4j.Node;
 23    import org.dom4j.ProcessingInstruction;
 24    import org.dom4j.QName;
 25    import org.dom4j.Text;
 26   
 27    /**
 28    * <p>
 29    * <code>NodeComparator</code> is a {@link Comparator}of Node instances which
 30    * is capable of comparing Nodes for equality based on their values.
 31    * </p>
 32    *
 33    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 34    * @version $Revision: 1.10 $
 35    */
 36    public class NodeComparator implements Comparator {
 37    /**
 38    * Compares its two arguments for order. Returns a negative integer, zero,
 39    * or a positive integer as the first argument is less than, equal to, or
 40    * greater than the second.
 41    *
 42    * <p>
 43    * The implementor must ensure that <tt>sgn(compare(x, y)) ==
 44    * -sgn(compare(y, x))</tt>
 45    * for all <tt>x</tt> and <tt>y</tt>. (This implies that
 46    * <tt>compare(x, y)</tt> must throw an exception if and only if
 47    * <tt>compare(y, x)</tt> throws an exception.)
 48    * </p>
 49    *
 50    * <p>
 51    * The implementor must also ensure that the relation is transitive:
 52    * <tt>((compare(x, y)&gt;0) &amp;&amp; (compare(y, z)&gt;0))</tt> implies
 53    * <tt>compare(x, z)&gt;0</tt>.
 54    * </p>
 55    *
 56    * <p>
 57    * Finally, the implementer must ensure that <tt>compare(x, y)==0</tt>
 58    * implies that <tt>sgn(compare(x, z))==sgn(compare(y, z))</tt> for all
 59    * <tt>z</tt>.
 60    * </p>
 61    *
 62    * <p>
 63    * It is generally the case, but <i>not </i> strictly required that
 64    * <tt>(compare(x, y)==0) == (x.equals(y))</tt>. Generally speaking, any
 65    * comparator that violates this condition should clearly indicate this
 66    * fact. The recommended language is "Note: this comparator imposes
 67    * orderings that are inconsistent with equals."
 68    * </p>
 69    *
 70    * @param o1
 71    * the first object to be compared.
 72    * @param o2
 73    * the second object to be compared.
 74    *
 75    * @return a negative integer, zero, or a positive integer as the first
 76    * argument is less than, equal to, or greater than the second.
 77    */
 78  6 public int compare(Object o1, Object o2) {
 79  6 if (o1 == o2) {
 80  0 return 0;
 81  6 } else if (o1 == null) {
 82    // null is less
 83  0 return -1;
 84  6 } else if (o2 == null) {
 85  0 return 1;
 86    }
 87   
 88  6 if (o1 instanceof Node) {
 89  6 if (o2 instanceof Node) {
 90  6 return compare((Node) o1, (Node) o2);
 91    } else {
 92    // Node implementations are greater
 93  0 return 1;
 94    }
 95    } else {
 96  0 if (o2 instanceof Node) {
 97    // Node implementations are greater
 98  0 return -1;
 99    } else {
 100  0 if (o1 instanceof Comparable) {
 101  0 Comparable c1 = (Comparable) o1;
 102   
 103  0 return c1.compareTo(o2);
 104    } else {
 105  0 String name1 = o1.getClass().getName();
 106  0 String name2 = o2.getClass().getName();
 107   
 108  0 return name1.compareTo(name2);
 109    }
 110    }
 111    }
 112    }
 113   
 114  60643 public int compare(Node n1, Node n2) {
 115  60643 int nodeType1 = n1.getNodeType();
 116  60643 int nodeType2 = n2.getNodeType();
 117  60643 int answer = nodeType1 - nodeType2;
 118   
 119  60643 if (answer != 0) {
 120  0 return answer;
 121    } else {
 122  60643 switch (nodeType1) {
 123  21394 case Node.ELEMENT_NODE:
 124  21394 return compare((Element) n1, (Element) n2);
 125   
 126  4 case Node.DOCUMENT_NODE:
 127  4 return compare((Document) n1, (Document) n2);
 128   
 129  0 case Node.ATTRIBUTE_NODE:
 130  0 return compare((Attribute) n1, (Attribute) n2);
 131   
 132  38623 case Node.TEXT_NODE:
 133  38623 return compare((Text) n1, (Text) n2);
 134   
 135  90 case Node.CDATA_SECTION_NODE:
 136  90 return compare((CDATA) n1, (CDATA) n2);
 137   
 138  0 case Node.ENTITY_REFERENCE_NODE:
 139  0 return compare((Entity) n1, (Entity) n2);
 140   
 141  6 case Node.PROCESSING_INSTRUCTION_NODE:
 142  6 return compare((ProcessingInstruction) n1,
 143    (ProcessingInstruction) n2);
 144   
 145  408 case Node.COMMENT_NODE:
 146  408 return compare((Comment) n1, (Comment) n2);
 147   
 148  0 case Node.DOCUMENT_TYPE_NODE:
 149  0 return compare((DocumentType) n1, (DocumentType) n2);
 150   
 151  118 case Node.NAMESPACE_NODE:
 152  118 return compare((Namespace) n1, (Namespace) n2);
 153   
 154  0 default:
 155  0 throw new RuntimeException("Invalid node types. node1: "
 156    + n1 + " and node2: " + n2);
 157    }
 158    }
 159    }
 160   
 161  58 public int compare(Document n1, Document n2) {
 162  58 int answer = compare(n1.getDocType(), n2.getDocType());
 163   
 164  58 if (answer == 0) {
 165  58 answer = compareContent(n1, n2);
 166    }
 167   
 168  58 return answer;
 169    }
 170   
 171  21394 public int compare(Element n1, Element n2) {
 172  21394 int answer = compare(n1.getQName(), n2.getQName());
 173   
 174  21394 if (answer == 0) {
 175    // lets compare attributes
 176  21394 int c1 = n1.attributeCount();
 177  21394 int c2 = n2.attributeCount();
 178  21394 answer = c1 - c2;
 179   
 180  21394 if (answer == 0) {
 181  21393 for (int i = 0; i < c1; i++) {
 182  8747 Attribute a1 = n1.attribute(i);
 183  8747 Attribute a2 = n2.attribute(a1.getQName());
 184  8747 answer = compare(a1, a2);
 185   
 186  8747 if (answer != 0) {
 187  1 return answer;
 188    }
 189    }
 190   
 191  21392 answer = compareContent(n1, n2);
 192    }
 193    }
 194   
 195  21393 return answer;
 196    }
 197   
 198  8747 public int compare(Attribute n1, Attribute n2) {
 199  8747 int answer = compare(n1.getQName(), n2.getQName());
 200   
 201  8747 if (answer == 0) {
 202  8747 answer = compare(n1.getValue(), n2.getValue());
 203    }
 204   
 205  8747 return answer;
 206    }
 207   
 208  30141 public int compare(QName n1, QName n2) {
 209  30141 int answer = compare(n1.getNamespaceURI(), n2.getNamespaceURI());
 210   
 211  30141 if (answer == 0) {
 212  30141 answer = compare(n1.getQualifiedName(), n2.getQualifiedName());
 213    }
 214   
 215  30141 return answer;
 216    }
 217   
 218  118 public int compare(Namespace n1, Namespace n2) {
 219  118 int answer = compare(n1.getURI(), n2.getURI());
 220   
 221  118 if (answer == 0) {
 222  118 answer = compare(n1.getPrefix(), n2.getPrefix());
 223    }
 224   
 225  118 return answer;
 226    }
 227   
 228  39121 public int compare(CharacterData t1, CharacterData t2) {
 229  39121 return compare(t1.getText(), t2.getText());
 230    }
 231   
 232  58 public int compare(DocumentType o1, DocumentType o2) {
 233  58 if (o1 == o2) {
 234  58 return 0;
 235  0 } else if (o1 == null) {
 236    // null is less
 237  0 return -1;
 238  0 } else if (o2 == null) {
 239  0 return 1;
 240    }
 241   
 242  0 int answer = compare(o1.getPublicID(), o2.getPublicID());
 243   
 244  0 if (answer == 0) {
 245  0 answer = compare(o1.getSystemID(), o2.getSystemID());
 246   
 247  0 if (answer == 0) {
 248  0 answer = compare(o1.getName(), o2.getName());
 249    }
 250    }
 251   
 252  0 return answer;
 253    }
 254   
 255  0 public int compare(Entity n1, Entity n2) {
 256  0 int answer = compare(n1.getName(), n2.getName());
 257   
 258  0 if (answer == 0) {
 259  0 answer = compare(n1.getText(), n2.getText());
 260    }
 261   
 262  0 return answer;
 263    }
 264   
 265  6 public int compare(ProcessingInstruction n1, ProcessingInstruction n2) {
 266  6 int answer = compare(n1.getTarget(), n2.getTarget());
 267   
 268  6 if (answer == 0) {
 269  6 answer = compare(n1.getText(), n2.getText());
 270    }
 271   
 272  6 return answer;
 273    }
 274   
 275  21450 public int compareContent(Branch b1, Branch b2) {
 276  21450 int c1 = b1.nodeCount();
 277  21450 int c2 = b2.nodeCount();
 278  21450 int answer = c1 - c2;
 279   
 280  21450 if (answer == 0) {
 281  21448 for (int i = 0; i < c1; i++) {
 282  60637 Node n1 = b1.node(i);
 283  60637 Node n2 = b2.node(i);
 284  60637 answer = compare(n1, n2);
 285   
 286  60637 if (answer != 0) {
 287  6 break;
 288    }
 289    }
 290    }
 291   
 292  21450 return answer;
 293    }
 294   
 295  108398 public int compare(String o1, String o2) {
 296  108398 if (o1 == o2) {
 297  66175 return 0;
 298  42223 } else if (o1 == null) {
 299    // null is less
 300  0 return -1;
 301  42223 } else if (o2 == null) {
 302  0 return 1;
 303    }
 304   
 305  42223 return o1.compareTo(o2);
 306    }
 307    }
 308   
 309    /*
 310    * Redistribution and use of this software and associated documentation
 311    * ("Software"), with or without modification, are permitted provided that the
 312    * following conditions are met:
 313    *
 314    * 1. Redistributions of source code must retain copyright statements and
 315    * notices. Redistributions must also contain a copy of this document.
 316    *
 317    * 2. Redistributions in binary form must reproduce the above copyright notice,
 318    * this list of conditions and the following disclaimer in the documentation
 319    * and/or other materials provided with the distribution.
 320    *
 321    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 322    * from this Software without prior written permission of MetaStuff, Ltd. For
 323    * written permission, please contact dom4j-info@metastuff.com.
 324    *
 325    * 4. Products derived from this Software may not be called "DOM4J" nor may
 326    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 327    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 328    *
 329    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 330    *
 331    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 332    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 333    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 334    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 335    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 336    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 337    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 338    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 339    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 340    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 341    * POSSIBILITY OF SUCH DAMAGE.
 342    *
 343    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 344    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/XPath.html0000644000175000017500000025146410242117737020044 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 345   Methods: 0
NCLOC: 28   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
XPath.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    import java.util.List;
 11    import java.util.Map;
 12   
 13    import org.jaxen.FunctionContext;
 14    import org.jaxen.NamespaceContext;
 15    import org.jaxen.VariableContext;
 16   
 17    /**
 18    * <p>
 19    * <code>XPath</code> represents an XPath expression after it has been parsed
 20    * from a String.
 21    * </p>
 22    *
 23    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 24    * @version $Revision: 1.20 $
 25    */
 26    public interface XPath extends NodeFilter {
 27    /**
 28    * <p>
 29    * <code>getText</code> will return the textual version of the XPath
 30    * expression.
 31    * </p>
 32    *
 33    * @return the textual format of the XPath expression.
 34    */
 35    String getText();
 36   
 37    /**
 38    * <p>
 39    * <code>matches</code> returns true if the given node matches the XPath
 40    * expression. To be more precise when evaluating this XPath expression on
 41    * the given node the result set must include the node.
 42    * </p>
 43    *
 44    * @param node
 45    * DOCUMENT ME!
 46    *
 47    * @return true if the given node matches this XPath expression
 48    */
 49    boolean matches(Node node);
 50   
 51    /**
 52    * <p>
 53    * <code>evaluate</code> evaluates an XPath expression and returns the
 54    * result as an {@link Object}. The object returned can either be a {@link
 55    * List} of {@link Node}instances, a {@link Node}instance, a {@link
 56    * String} or a {@link Number}instance depending on the XPath expression.
 57    * </p>
 58    *
 59    * @param context
 60    * is either a node or a list of nodes on which to evalute the
 61    * XPath
 62    *
 63    * @return the value of the XPath expression as a {@link List}of {@link
 64    * Node} instances, a {@link Node}instance, a {@link String}or a
 65    * {@link Number}instance depending on the XPath expression.
 66    */
 67    Object evaluate(Object context);
 68   
 69    /**
 70    * <p>
 71    * <code>selectObject</code> evaluates an XPath expression and returns the
 72    * result as an {@link Object}. The object returned can either be a {@link
 73    * List} of {@link Node}instances, a {@link Node}instance, a {@link
 74    * String} or a {@link Number}instance depending on the XPath expression.
 75    * </p>
 76    *
 77    * @param context
 78    * is either a node or a list of nodes on which to evalute the
 79    * XPath
 80    *
 81    * @return the value of the XPath expression as a {@link List}of {@link
 82    * Node} instances, a {@link Node}instance, a {@link String}or a
 83    * {@link Number}instance depending on the XPath expression.
 84    *
 85    * @deprecated please use evaluate(Object) instead. WILL BE REMOVED IN
 86    * dom4j-1.6 !!
 87    */
 88    Object selectObject(Object context);
 89   
 90    /**
 91    * <p>
 92    * <code>selectNodes</code> performs this XPath expression on the given
 93    * {@link Node}or {@link List}of {@link Node}s instances appending all
 94    * the results together into a single list.
 95    * </p>
 96    *
 97    * @param context
 98    * is either a node or a list of nodes on which to evalute the
 99    * XPath
 100    *
 101    * @return the results of all the XPath evaluations as a single list
 102    */
 103    List selectNodes(Object context);
 104   
 105    /**
 106    * <p>
 107    * <code>selectNodes</code> evaluates the XPath expression on the given
 108    * {@link Node}or {@link List}of {@link Node}s and returns the result as
 109    * a <code>List</code> of <code>Node</code> s sorted by the sort XPath
 110    * expression.
 111    * </p>
 112    *
 113    * @param context
 114    * is either a node or a list of nodes on which to evalute the
 115    * XPath
 116    * @param sortXPath
 117    * is the XPath expression to sort by
 118    *
 119    * @return a list of <code>Node</code> instances
 120    */
 121    List selectNodes(Object context, XPath sortXPath);
 122   
 123    /**
 124    * <p>
 125    * <code>selectNodes</code> evaluates the XPath expression on the given
 126    * {@link Node}or {@link List}of {@link Node}s and returns the result as
 127    * a <code>List</code> of <code>Node</code> s sorted by the sort XPath
 128    * expression.
 129    * </p>
 130    *
 131    * @param context
 132    * is either a node or a list of nodes on which to evalute the
 133    * XPath
 134    * @param sortXPath
 135    * is the XPath expression to sort by
 136    * @param distinct
 137    * specifies whether or not duplicate values of the sort
 138    * expression are allowed. If this parameter is true then only
 139    * distinct sort expressions values are included in the result
 140    *
 141    * @return a list of <code>Node</code> instances
 142    */
 143    List selectNodes(Object context, XPath sortXPath, boolean distinct);
 144   
 145    /**
 146    * <p>
 147    * <code>selectSingleNode</code> evaluates this XPath expression on the
 148    * given {@link Node}or {@link List}of {@link Node}s and returns the
 149    * result as a single <code>Node</code> instance.
 150    * </p>
 151    *
 152    * @param context
 153    * is either a node or a list of nodes on which to evalute the
 154    * XPath
 155    *
 156    * @return a single matching <code>Node</code> instance
 157    */
 158    Node selectSingleNode(Object context);
 159   
 160    /**
 161    * <p>
 162    * <code>valueOf</code> evaluates this XPath expression and returns the
 163    * textual representation of the results using the XPath string() function.
 164    * </p>
 165    *
 166    * @param context
 167    * is either a node or a list of nodes on which to evalute the
 168    * XPath
 169    *
 170    * @return the string representation of the results of the XPath expression
 171    */
 172    String valueOf(Object context);
 173   
 174    /**
 175    * <p>
 176    * <code>numberValueOf</code> evaluates an XPath expression and returns
 177    * the numeric value of the XPath expression if the XPath expression results
 178    * is a number, or null if the result is not a number.
 179    * </p>
 180    *
 181    * @param context
 182    * is either a node or a list of nodes on which to evalute the
 183    * XPath
 184    *
 185    * @return the numeric result of the XPath expression or null if the result
 186    * is not a number.
 187    */
 188    Number numberValueOf(Object context);
 189   
 190    /**
 191    * Retrieve a boolean-value interpretation of this XPath expression when
 192    * evaluated against a given context.
 193    *
 194    * <p>
 195    * The boolean-value of the expression is determined per the
 196    * <code>boolean(..)</code> core function as defined in the XPath
 197    * specification. This means that an expression that selects zero nodes will
 198    * return <code>false</code>, while an expression that selects
 199    * one-or-more nodes will return <code>true</code>.
 200    * </p>
 201    *
 202    * @param context
 203    * The node, nodeset or Context object for evaluation. This value
 204    * can be null
 205    *
 206    * @return The boolean-value interpretation of this expression.
 207    *
 208    * @since 1.5
 209    */
 210    boolean booleanValueOf(Object context);
 211   
 212    /**
 213    * <p>
 214    * <code>sort</code> sorts the given List of Nodes using this XPath
 215    * expression as a {@link java.util.Comparator}.
 216    * </p>
 217    *
 218    * @param list
 219    * is the list of Nodes to sort
 220    */
 221    void sort(List list);
 222   
 223    /**
 224    * <p>
 225    * <code>sort</code> sorts the given List of Nodes using this XPath
 226    * expression as a {@link java.util.Comparator}and optionally removing
 227    * duplicates.
 228    * </p>
 229    *
 230    * @param list
 231    * is the list of Nodes to sort
 232    * @param distinct
 233    * if true then duplicate values (using the sortXPath for
 234    * comparisions) will be removed from the List
 235    */
 236    void sort(List list, boolean distinct);
 237   
 238    /**
 239    * DOCUMENT ME!
 240    *
 241    * @return the current function context
 242    */
 243    FunctionContext getFunctionContext();
 244   
 245    /**
 246    * Sets the function context to be used when evaluating XPath expressions
 247    *
 248    * @param functionContext
 249    * DOCUMENT ME!
 250    */
 251    void setFunctionContext(FunctionContext functionContext);
 252   
 253    /**
 254    * DOCUMENT ME!
 255    *
 256    * @return the current namespace context
 257    */
 258    NamespaceContext getNamespaceContext();
 259   
 260    /**
 261    * Sets the namespace context to be used when evaluating XPath expressions
 262    *
 263    * @param namespaceContext
 264    * DOCUMENT ME!
 265    */
 266    void setNamespaceContext(NamespaceContext namespaceContext);
 267   
 268    /**
 269    * <p>
 270    * Sets the current NamespaceContext from a Map where the keys are the
 271    * String namespace prefixes and the values are the namespace URIs.
 272    * </p>
 273    *
 274    * <p>
 275    * For example:
 276    *
 277    * <pre>
 278    * Map uris = new HashMap();
 279    * uris.put("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/");
 280    * uris.put("m", "urn:xmethodsBabelFish");
 281    * XPath xpath = document
 282    * .createXPath("SOAP-ENV:Envelope/SOAP-ENV:Body/m:BabelFish");
 283    * xpath.setNamespaceURIs(uris);
 284    * Node babelfish = xpath.selectSingleNode(document);
 285    * </pre>
 286    *
 287    * </p>
 288    *
 289    * @param map
 290    * the map containing the namespace mappings
 291    */
 292    void setNamespaceURIs(Map map);
 293   
 294    /**
 295    * DOCUMENT ME!
 296    *
 297    * @return the current variable context
 298    */
 299    VariableContext getVariableContext();
 300   
 301    /**
 302    * Sets the variable context to be used when evaluating XPath expressions
 303    *
 304    * @param variableContext
 305    * DOCUMENT ME!
 306    */
 307    void setVariableContext(VariableContext variableContext);
 308    }
 309   
 310    /*
 311    * Redistribution and use of this software and associated documentation
 312    * ("Software"), with or without modification, are permitted provided that the
 313    * following conditions are met:
 314    *
 315    * 1. Redistributions of source code must retain copyright statements and
 316    * notices. Redistributions must also contain a copy of this document.
 317    *
 318    * 2. Redistributions in binary form must reproduce the above copyright notice,
 319    * this list of conditions and the following disclaimer in the documentation
 320    * and/or other materials provided with the distribution.
 321    *
 322    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 323    * from this Software without prior written permission of MetaStuff, Ltd. For
 324    * written permission, please contact dom4j-info@metastuff.com.
 325    *
 326    * 4. Products derived from this Software may not be called "DOM4J" nor may
 327    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 328    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 329    *
 330    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 331    *
 332    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 333    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 334    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 335    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 336    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 337    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 338    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 339    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 340    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 341    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 342    * POSSIBILITY OF SUCH DAMAGE.
 343    *
 344    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 345    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/ElementHandler.html0000644000175000017500000005347110242117613021676 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 76   Methods: 0
NCLOC: 5   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
ElementHandler.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    /**
 11    * <p>
 12    * <code>ElementHandler</code> interface defines a handler of
 13    * <code>Element</code> objects. It is used primarily in event based
 14    * processing models such as for processing large XML documents as they are
 15    * being parsed rather than waiting until the whole document is parsed.
 16    * </p>
 17    *
 18    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 19    * @version $Revision: 1.8 $
 20    */
 21    public interface ElementHandler {
 22    /**
 23    * Called by an event based processor when an elements openning tag is
 24    * encountered.
 25    *
 26    * @param elementPath
 27    * is the current <code>ElementPath</code> to process
 28    */
 29    void onStart(ElementPath elementPath);
 30   
 31    /**
 32    * Called by an event based processor when an elements closing tag is
 33    * encountered.
 34    *
 35    * @param elementPath
 36    * is the current <code>ElementPath</code> to process
 37    */
 38    void onEnd(ElementPath elementPath);
 39    }
 40   
 41    /*
 42    * Redistribution and use of this software and associated documentation
 43    * ("Software"), with or without modification, are permitted provided that the
 44    * following conditions are met:
 45    *
 46    * 1. Redistributions of source code must retain copyright statements and
 47    * notices. Redistributions must also contain a copy of this document.
 48    *
 49    * 2. Redistributions in binary form must reproduce the above copyright notice,
 50    * this list of conditions and the following disclaimer in the documentation
 51    * and/or other materials provided with the distribution.
 52    *
 53    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 54    * from this Software without prior written permission of MetaStuff, Ltd. For
 55    * written permission, please contact dom4j-info@metastuff.com.
 56    *
 57    * 4. Products derived from this Software may not be called "DOM4J" nor may
 58    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 59    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 60    *
 61    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 62    *
 63    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 64    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 65    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 66    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 67    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 68    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 69    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 70    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 71    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 72    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 73    * POSSIBILITY OF SUCH DAMAGE.
 74    *
 75    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 76    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/Attribute.html0000644000175000017500000012764410242117631020756 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 173   Methods: 0
NCLOC: 13   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
Attribute.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    /**
 11    * <p>
 12    * <code>Attribute</code> defines an XML attribute. An attribute may have a
 13    * name, an optional namespace and a value.
 14    * </p>
 15    *
 16    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 17    * @version $Revision: 1.9 $
 18    */
 19    public interface Attribute extends Node {
 20    /**
 21    * <p>
 22    * Returns the <code>QName</code> of this attribute which represents the
 23    * local name, the qualified name and the <code>Namespace</code>.
 24    * </p>
 25    *
 26    * @return the <code>QName</code> associated with this attribute
 27    */
 28    QName getQName();
 29   
 30    /**
 31    * <p>
 32    * Returns the <code>Namespace</code> of this element if one exists
 33    * otherwise null is returned returned.
 34    * </p>
 35    *
 36    * @return the <code>Namespace</code> associated with this node
 37    */
 38    Namespace getNamespace();
 39   
 40    /**
 41    * <p>
 42    * Sets the <code>Namespace</code> of this element or if this element is
 43    * read only then an <code>UnsupportedOperationException</code> is thrown.
 44    * </p>
 45    *
 46    * @param namespace
 47    * is the <code>Namespace</code> to associate with this element
 48    */
 49    void setNamespace(Namespace namespace);
 50   
 51    /**
 52    * <p>
 53    * Returns the namespace prefix of this element if one exists otherwise an
 54    * empty <code>String</code> is returned.
 55    * </p>
 56    *
 57    * @return the prefix of the <code>Namespace</code> of this element or an
 58    * empty <code>String</code>
 59    */
 60    String getNamespacePrefix();
 61   
 62    /**
 63    * <p>
 64    * Returns the URI mapped to the namespace of this element if one exists
 65    * otherwise an empty <code>String</code> is returned.
 66    * </p>
 67    *
 68    * @return the URI for the <code>Namespace</code> of this element or an
 69    * empty <code>String</code>
 70    */
 71    String getNamespaceURI();
 72   
 73    /**
 74    * <p>
 75    * Returns the fully qualified name of this element.
 76    * </p>
 77    *
 78    * <p>
 79    * This will be the same as the value returned from {@link Node#getName()}
 80    * if this element has no namespace attached to this element or an
 81    * expression of the form
 82    *
 83    * <pre>
 84    * getNamespacePrefix() + &quot;:&quot; + getName()
 85    * </pre>
 86    *
 87    * will be returned.
 88    * </p>
 89    *
 90    * @return the fully qualified name of the element
 91    */
 92    String getQualifiedName();
 93   
 94    /**
 95    * <p>
 96    * Returns the value of the attribute. This method returns the same value as
 97    * the {@link Node#getText()}method.
 98    * </p>
 99    *
 100    * @return the value of the attribute
 101    */
 102    String getValue();
 103   
 104    /**
 105    * <p>
 106    * Sets the value of this attribute or this method will throw an
 107    * <code>UnsupportedOperationException</code> if it is read-only.
 108    * </p>
 109    *
 110    * @param value
 111    * is the new value of this attribute
 112    */
 113    void setValue(String value);
 114   
 115    /**
 116    * <p>
 117    * Accesses the data of this attribute which may implement data typing
 118    * bindings such as <code>XML Schema</code> or <code>Java Bean</code>
 119    * bindings or will return the same value as {@link Node#getText()}.
 120    * </p>
 121    *
 122    * @return the attribute data
 123    */
 124    Object getData();
 125   
 126    /**
 127    * <p>
 128    * Sets the data value of this attribute if this element supports data
 129    * binding or calls {@link Node#setText(String)}if it doesn't.
 130    * </p>
 131    *
 132    * @param data
 133    * the attribute data
 134    */
 135    void setData(Object data);
 136    }
 137   
 138    /*
 139    * Redistribution and use of this software and associated documentation
 140    * ("Software"), with or without modification, are permitted provided that the
 141    * following conditions are met:
 142    *
 143    * 1. Redistributions of source code must retain copyright statements and
 144    * notices. Redistributions must also contain a copy of this document.
 145    *
 146    * 2. Redistributions in binary form must reproduce the above copyright notice,
 147    * this list of conditions and the following disclaimer in the documentation
 148    * and/or other materials provided with the distribution.
 149    *
 150    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 151    * from this Software without prior written permission of MetaStuff, Ltd. For
 152    * written permission, please contact dom4j-info@metastuff.com.
 153    *
 154    * 4. Products derived from this Software may not be called "DOM4J" nor may
 155    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 156    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 157    *
 158    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 159    *
 160    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 161    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 162    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 163    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 164    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 165    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 166    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 167    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 168    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 169    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 170    * POSSIBILITY OF SUCH DAMAGE.
 171    *
 172    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 173    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/Branch.html0000644000175000017500000025531710242117626020213 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 351   Methods: 0
NCLOC: 31   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
Branch.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    import java.util.Iterator;
 11    import java.util.List;
 12   
 13    /**
 14    * <p>
 15    * <code>Branch</code> interface defines the common behaviour for Nodes which
 16    * can contain child nodes (content) such as XML elements and documents. This
 17    * interface allows both elements and documents to be treated in a polymorphic
 18    * manner when changing or navigating child nodes (content).
 19    * </p>
 20    *
 21    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 22    * @version $Revision: 1.32 $
 23    */
 24    public interface Branch extends Node {
 25    /**
 26    * Returns the <code>Node</code> at the specified index position.
 27    *
 28    * @param index
 29    * the index of the node to return.
 30    *
 31    * @return the <code>Node</code> at the specified position.
 32    *
 33    * @throws IndexOutOfBoundsException
 34    * if the index is out of range (index &lt; 0 || index &gt;=
 35    * {@link Branch#nodeCount()}).
 36    */
 37    Node node(int index) throws IndexOutOfBoundsException;
 38   
 39    /**
 40    * Returns the index of the given node if it is a child node of this branch
 41    * or -1 if the given node is not a child node.
 42    *
 43    * @param node
 44    * the content child node to find.
 45    *
 46    * @return the index of the given node starting at 0 or -1 if the node is
 47    * not a child node of this branch
 48    */
 49    int indexOf(Node node);
 50   
 51    /**
 52    * Returns the number of <code>Node</code> instances that this branch
 53    * contains.
 54    *
 55    * @return the number of nodes this branch contains
 56    */
 57    int nodeCount();
 58   
 59    /**
 60    * Returns the element of the given ID attribute value. If this tree is
 61    * capable of understanding which attribute value should be used for the ID
 62    * then it should be used, otherwise this method should return null.
 63    *
 64    * @param elementID
 65    * DOCUMENT ME!
 66    *
 67    * @return DOCUMENT ME!
 68    */
 69    Element elementByID(String elementID);
 70   
 71    /**
 72    * <p>
 73    * Returns the content nodes of this branch as a backed {@link List}so that
 74    * the content of this branch may be modified directly using the
 75    * {@link List}interface. The <code>List</code> is backed by the
 76    * <code>Branch</code> so that changes to the list are reflected in the
 77    * branch and vice versa.
 78    * </p>
 79    *
 80    * @return the nodes that this branch contains as a <code>List</code>
 81    */
 82    List content();
 83   
 84    /**
 85    * Returns an iterator through the content nodes of this branch
 86    *
 87    * @return an iterator through the content nodes of this branch
 88    */
 89    Iterator nodeIterator();
 90   
 91    /**
 92    * Sets the contents of this branch as a <code>List</code> of
 93    * <code>Node</code> instances.
 94    *
 95    * @param content
 96    * is the list of nodes to use as the content for this branch.
 97    */
 98    void setContent(List content);
 99   
 100    /**
 101    * Appends the content of the given branch to this branch instance. This
 102    * method behaves like the {@link
 103    * java.util.Collection#addAll(java.util.Collection)} method.
 104    *
 105    * @param branch
 106    * is the branch whose content will be added to me.
 107    */
 108    void appendContent(Branch branch);
 109   
 110    /**
 111    * Clears the content for this branch, removing any <code>Node</code>
 112    * instances this branch may contain.
 113    */
 114    void clearContent();
 115   
 116    /**
 117    * <p>
 118    * Returns a list of all the processing instructions in this branch. The
 119    * list is backed by this branch so that changes to the list will be
 120    * reflected in the branch but the reverse is not the case.
 121    * </p>
 122    *
 123    * @return a backed list of the processing instructions
 124    */
 125    List processingInstructions();
 126   
 127    /**
 128    * <p>
 129    * Returns a list of the processing instructions for the given target. The
 130    * list is backed by this branch so that changes to the list will be
 131    * reflected in the branch but the reverse is not the case.
 132    * </p>
 133    *
 134    * @param target
 135    * DOCUMENT ME!
 136    *
 137    * @return a backed list of the processing instructions
 138    */
 139    List processingInstructions(String target);
 140   
 141    /**
 142    * DOCUMENT ME!
 143    *
 144    * @param target
 145    * DOCUMENT ME!
 146    *
 147    * @return the processing instruction for the given target
 148    */
 149    ProcessingInstruction processingInstruction(String target);
 150   
 151    /**
 152    * Sets all the processing instructions for this branch
 153    *
 154    * @param listOfPIs
 155    * DOCUMENT ME!
 156    */
 157    void setProcessingInstructions(List listOfPIs);
 158   
 159    /**
 160    * Adds a new <code>Element</code> node with the given name to this branch
 161    * and returns a reference to the new node.
 162    *
 163    * @param name
 164    * is the name for the <code>Element</code> node.
 165    *
 166    * @return the newly added <code>Element</code> node.
 167    */
 168    Element addElement(String name);
 169   
 170    /**
 171    * Adds a new <code>Element</code> node with the given {@link QName}to
 172    * this branch and returns a reference to the new node.
 173    *
 174    * @param qname
 175    * is the qualified name for the <code>Element</code> node.
 176    *
 177    * @return the newly added <code>Element</code> node.
 178    */
 179    Element addElement(QName qname);
 180   
 181    /**
 182    * Adds a new <code>Element</code> node with the given qualified name and
 183    * namespace URI to this branch and returns a reference to the new node.
 184    *
 185    * @param qualifiedName
 186    * is the fully qualified name of the Element
 187    * @param namespaceURI
 188    * is the URI of the namespace to use
 189    *
 190    * @return the newly added <code>Element</code> node.
 191    */
 192    Element addElement(String qualifiedName, String namespaceURI);
 193   
 194    /**
 195    * Removes the processing instruction for the given target if it exists
 196    *
 197    * @param target
 198    * DOCUMENT ME!
 199    *
 200    * @return true if a processing instruction was removed else false
 201    */
 202    boolean removeProcessingInstruction(String target);
 203   
 204    /**
 205    * Adds the given <code>Node</code> or throws {@link IllegalAddException}
 206    * if the given node is not of a valid type. This is a polymorphic method
 207    * which will call the typesafe method for the node type such as
 208    * add(Element) or add(Comment).
 209    *
 210    * @param node
 211    * is the given node to add
 212    */
 213    void add(Node node);
 214   
 215    /**
 216    * Adds the given <code>Comment</code> to this branch. If the given node
 217    * already has a parent defined then an <code>IllegalAddException</code>
 218    * will be thrown.
 219    *
 220    * @param comment
 221    * is the comment to be added
 222    */
 223    void add(Comment comment);
 224   
 225    /**
 226    * Adds the given <code>Element</code> to this branch. If the given node
 227    * already has a parent defined then an <code>IllegalAddException</code>
 228    * will be thrown.
 229    *
 230    * @param element
 231    * is the element to be added
 232    */
 233    void add(Element element);
 234   
 235    /**
 236    * Adds the given <code>ProcessingInstruction</code> to this branch. If
 237    * the given node already has a parent defined then an
 238    * <code>IllegalAddException</code> will be thrown.
 239    *
 240    * @param pi
 241    * is the processing instruction to be added
 242    */
 243    void add(ProcessingInstruction pi);
 244   
 245    /**
 246    * Removes the given <code>Node</code> if the node is an immediate child
 247    * of this branch. If the given node is not an immediate child of this
 248    * branch then the {@link Node#detach()}method should be used instead. This
 249    * is a polymorphic method which will call the typesafe method for the node
 250    * type such as remove(Element) or remove(Comment).
 251    *
 252    * @param node
 253    * is the given node to be removed
 254    *
 255    * @return true if the node was removed
 256    */
 257    boolean remove(Node node);
 258   
 259    /**
 260    * Removes the given <code>Comment</code> if the node is an immediate
 261    * child of this branch. If the given node is not an immediate child of this
 262    * branch then the {@link Node#detach()}method should be used instead.
 263    *
 264    * @param comment
 265    * is the comment to be removed
 266    *
 267    * @return true if the comment was removed
 268    */
 269    boolean remove(Comment comment);
 270   
 271    /**
 272    * Removes the given <code>Element</code> if the node is an immediate
 273    * child of this branch. If the given node is not an immediate child of this
 274    * branch then the {@link Node#detach()}method should be used instead.
 275    *
 276    * @param element
 277    * is the element to be removed
 278    *
 279    * @return true if the element was removed
 280    */
 281    boolean remove(Element element);
 282   
 283    /**
 284    * Removes the given <code>ProcessingInstruction</code> if the node is an
 285    * immediate child of this branch. If the given node is not an immediate
 286    * child of this branch then the {@link Node#detach()}method should be used
 287    * instead.
 288    *
 289    * @param pi
 290    * is the processing instruction to be removed
 291    *
 292    * @return true if the processing instruction was removed
 293    */
 294    boolean remove(ProcessingInstruction pi);
 295   
 296    /**
 297    * Puts all <code>Text</code> nodes in the full depth of the sub-tree
 298    * underneath this <code>Node</code>, including attribute nodes, into a
 299    * "normal" form where only structure (e.g., elements, comments, processing
 300    * instructions, CDATA sections, and entity references) separates
 301    * <code>Text</code> nodes, i.e., there are neither adjacent
 302    * <code>Text</code> nodes nor empty <code>Text</code> nodes. This can
 303    * be used to ensure that the DOM view of a document is the same as if it
 304    * were saved and re-loaded, and is useful when operations (such as XPointer
 305    * lookups) that depend on a particular document tree structure are to be
 306    * used.In cases where the document contains <code>CDATASections</code>,
 307    * the normalize operation alone may not be sufficient, since XPointers do
 308    * not differentiate between <code>Text</code> nodes and
 309    * <code>CDATASection</code> nodes.
 310    *
 311    * @since DOM Level 2
 312    */
 313    void normalize();
 314    }
 315   
 316    /*
 317    * Redistribution and use of this software and associated documentation
 318    * ("Software"), with or without modification, are permitted provided that the
 319    * following conditions are met:
 320    *
 321    * 1. Redistributions of source code must retain copyright statements and
 322    * notices. Redistributions must also contain a copy of this document.
 323    *
 324    * 2. Redistributions in binary form must reproduce the above copyright notice,
 325    * this list of conditions and the following disclaimer in the documentation
 326    * and/or other materials provided with the distribution.
 327    *
 328    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 329    * from this Software without prior written permission of MetaStuff, Ltd. For
 330    * written permission, please contact dom4j-info@metastuff.com.
 331    *
 332    * 4. Products derived from this Software may not be called "DOM4J" nor may
 333    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 334    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 335    *
 336    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 337    *
 338    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 339    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 340    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 341    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 342    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 343    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 344    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 345    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 346    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 347    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 348    * POSSIBILITY OF SUCH DAMAGE.
 349    *
 350    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 351    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/Entity.html0000644000175000017500000004201510242117701020251 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 56   Methods: 0
NCLOC: 3   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
Entity.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    /**
 11    * <p>
 12    * <code>Entity</code> defines an XML entity.
 13    * </p>
 14    *
 15    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 16    * @version $Revision: 1.7 $
 17    */
 18    public interface Entity extends Node {
 19    }
 20   
 21    /*
 22    * Redistribution and use of this software and associated documentation
 23    * ("Software"), with or without modification, are permitted provided that the
 24    * following conditions are met:
 25    *
 26    * 1. Redistributions of source code must retain copyright statements and
 27    * notices. Redistributions must also contain a copy of this document.
 28    *
 29    * 2. Redistributions in binary form must reproduce the above copyright notice,
 30    * this list of conditions and the following disclaimer in the documentation
 31    * and/or other materials provided with the distribution.
 32    *
 33    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 34    * from this Software without prior written permission of MetaStuff, Ltd. For
 35    * written permission, please contact dom4j-info@metastuff.com.
 36    *
 37    * 4. Products derived from this Software may not be called "DOM4J" nor may
 38    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 39    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 40    *
 41    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 42    *
 43    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 44    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 45    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 46    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 47    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 48    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 49    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 50    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 51    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 52    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 53    * POSSIBILITY OF SUCH DAMAGE.
 54    *
 55    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 56    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/DocumentHelper.html0000644000175000017500000033306310242117750021725 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 412   Methods: 28
NCLOC: 154   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DocumentHelper.java 95% 75,4% 50% 72,6%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    import java.io.StringReader;
 11    import java.util.List;
 12    import java.util.Map;
 13    import java.util.StringTokenizer;
 14   
 15    import org.dom4j.io.SAXReader;
 16    import org.dom4j.rule.Pattern;
 17   
 18    import org.jaxen.VariableContext;
 19   
 20    import org.xml.sax.InputSource;
 21   
 22    /**
 23    * <p>
 24    * <code>DocumentHelper</code> is a collection of helper methods for using
 25    * DOM4J.
 26    * </p>
 27    *
 28    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 29    * @version $Revision: 1.26 $
 30    */
 31    public final class DocumentHelper {
 32  0 private DocumentHelper() {
 33    }
 34   
 35  12496 private static DocumentFactory getDocumentFactory() {
 36  12496 return DocumentFactory.getInstance();
 37    }
 38   
 39    // Static helper methods
 40  412 public static Document createDocument() {
 41  412 return getDocumentFactory().createDocument();
 42    }
 43   
 44  2 public static Document createDocument(Element rootElement) {
 45  2 return getDocumentFactory().createDocument(rootElement);
 46    }
 47   
 48  2000 public static Element createElement(QName qname) {
 49  2000 return getDocumentFactory().createElement(qname);
 50    }
 51   
 52  4 public static Element createElement(String name) {
 53  4 return getDocumentFactory().createElement(name);
 54    }
 55   
 56  0 public static Attribute createAttribute(Element owner, QName qname,
 57    String value) {
 58  0 return getDocumentFactory().createAttribute(owner, qname, value);
 59    }
 60   
 61  0 public static Attribute createAttribute(Element owner, String name,
 62    String value) {
 63  0 return getDocumentFactory().createAttribute(owner, name, value);
 64    }
 65   
 66  0 public static CDATA createCDATA(String text) {
 67  0 return DocumentFactory.getInstance().createCDATA(text);
 68    }
 69   
 70  0 public static Comment createComment(String text) {
 71  0 return DocumentFactory.getInstance().createComment(text);
 72    }
 73   
 74  0 public static Text createText(String text) {
 75  0 return DocumentFactory.getInstance().createText(text);
 76    }
 77   
 78  0 public static Entity createEntity(String name, String text) {
 79  0 return DocumentFactory.getInstance().createEntity(name, text);
 80    }
 81   
 82  0 public static Namespace createNamespace(String prefix, String uri) {
 83  0 return DocumentFactory.getInstance().createNamespace(prefix, uri);
 84    }
 85   
 86  2 public static ProcessingInstruction createProcessingInstruction(String pi,
 87    String d) {
 88  2 return getDocumentFactory().createProcessingInstruction(pi, d);
 89    }
 90   
 91  0 public static ProcessingInstruction createProcessingInstruction(String pi,
 92    Map data) {
 93  0 return getDocumentFactory().createProcessingInstruction(pi, data);
 94    }
 95   
 96  0 public static QName createQName(String localName, Namespace namespace) {
 97  0 return getDocumentFactory().createQName(localName, namespace);
 98    }
 99   
 100  10000 public static QName createQName(String localName) {
 101  10000 return getDocumentFactory().createQName(localName);
 102    }
 103   
 104    /**
 105    * <p>
 106    * <code>createXPath</code> parses an XPath expression and creates a new
 107    * XPath <code>XPath</code> instance using the singleton {@link
 108    * DocumentFactory}.
 109    * </p>
 110    *
 111    * @param xpathExpression
 112    * is the XPath expression to create
 113    *
 114    * @return a new <code>XPath</code> instance
 115    *
 116    * @throws InvalidXPathException
 117    * if the XPath expression is invalid
 118    */
 119  57 public static XPath createXPath(String xpathExpression)
 120    throws InvalidXPathException {
 121  57 return getDocumentFactory().createXPath(xpathExpression);
 122    }
 123   
 124    /**
 125    * <p>
 126    * <code>createXPath</code> parses an XPath expression and creates a new
 127    * XPath <code>XPath</code> instance using the singleton {@link
 128    * DocumentFactory}.
 129    * </p>
 130    *
 131    * @param xpathExpression
 132    * is the XPath expression to create
 133    * @param context
 134    * is the variable context to use when evaluating the XPath
 135    *
 136    * @return a new <code>XPath</code> instance
 137    *
 138    * @throws InvalidXPathException
 139    * if the XPath expression is invalid
 140    */
 141  1 public static XPath createXPath(String xpathExpression,
 142    VariableContext context) throws InvalidXPathException {
 143  1 return getDocumentFactory().createXPath(xpathExpression, context);
 144    }
 145   
 146    /**
 147    * <p>
 148    * <code>createXPathFilter</code> parses a NodeFilter from the given XPath
 149    * filter expression using the singleton {@link DocumentFactory}. XPath
 150    * filter expressions occur within XPath expressions such as
 151    * <code>self::node()[ filterExpression ]</code>
 152    * </p>
 153    *
 154    * @param xpathFilterExpression
 155    * is the XPath filter expression to create
 156    *
 157    * @return a new <code>NodeFilter</code> instance
 158    */
 159  4 public static NodeFilter createXPathFilter(String xpathFilterExpression) {
 160  4 return getDocumentFactory().createXPathFilter(xpathFilterExpression);
 161    }
 162   
 163    /**
 164    * <p>
 165    * <code>createPattern</code> parses the given XPath expression to create
 166    * an XSLT style {@link Pattern}instance which can then be used in an XSLT
 167    * processing model.
 168    * </p>
 169    *
 170    * @param xpathPattern
 171    * is the XPath pattern expression to create
 172    *
 173    * @return a new <code>Pattern</code> instance
 174    */
 175  14 public static Pattern createPattern(String xpathPattern) {
 176  14 return getDocumentFactory().createPattern(xpathPattern);
 177    }
 178   
 179    /**
 180    * <p>
 181    * <code>selectNodes</code> performs the given XPath expression on the
 182    * {@link List}of {@link Node}instances appending all the results together
 183    * into a single list.
 184    * </p>
 185    *
 186    * @param xpathFilterExpression
 187    * is the XPath filter expression to evaluate
 188    * @param nodes
 189    * is the list of nodes on which to evalute the XPath
 190    *
 191    * @return the results of all the XPath evaluations as a single list
 192    */
 193  0 public static List selectNodes(String xpathFilterExpression, List nodes) {
 194  0 XPath xpath = createXPath(xpathFilterExpression);
 195   
 196  0 return xpath.selectNodes(nodes);
 197    }
 198   
 199    /**
 200    * <p>
 201    * <code>selectNodes</code> performs the given XPath expression on the
 202    * {@link List}of {@link Node}instances appending all the results together
 203    * into a single list.
 204    * </p>
 205    *
 206    * @param xpathFilterExpression
 207    * is the XPath filter expression to evaluate
 208    * @param node
 209    * is the Node on which to evalute the XPath
 210    *
 211    * @return the results of all the XPath evaluations as a single list
 212    */
 213  0 public static List selectNodes(String xpathFilterExpression, Node node) {
 214  0 XPath xpath = createXPath(xpathFilterExpression);
 215   
 216  0 return xpath.selectNodes(node);
 217    }
 218   
 219    /**
 220    * <p>
 221    * <code>sort</code> sorts the given List of Nodes using an XPath
 222    * expression as a {@link java.util.Comparator}.
 223    * </p>
 224    *
 225    * @param list
 226    * is the list of Nodes to sort
 227    * @param xpathExpression
 228    * is the XPath expression used for comparison
 229    */
 230  0 public static void sort(List list, String xpathExpression) {
 231  0 XPath xpath = createXPath(xpathExpression);
 232  0 xpath.sort(list);
 233    }
 234   
 235    /**
 236    * <p>
 237    * <code>sort</code> sorts the given List of Nodes using an XPath
 238    * expression as a {@link java.util.Comparator}and optionally removing
 239    * duplicates.
 240    * </p>
 241    *
 242    * @param list
 243    * is the list of Nodes to sort
 244    * @param expression
 245    * is the XPath expression used for comparison
 246    * @param distinct
 247    * if true then duplicate values (using the sortXPath for
 248    * comparisions) will be removed from the List
 249    */
 250  0 public static void sort(List list, String expression, boolean distinct) {
 251  0 XPath xpath = createXPath(expression);
 252  0 xpath.sort(list, distinct);
 253    }
 254   
 255    /**
 256    * <p>
 257    * <code>parseText</code> parses the given text as an XML document and
 258    * returns the newly created Document.
 259    * </p>
 260    *
 261    * @param text
 262    * the XML text to be parsed
 263    *
 264    * @return a newly parsed Document
 265    *
 266    * @throws DocumentException
 267    * if the document could not be parsed
 268    */
 269  5552 public static Document parseText(String text) throws DocumentException {
 270  5552 Document result = null;
 271   
 272  5552 SAXReader reader = new SAXReader();
 273  5552 String encoding = getEncoding(text);
 274   
 275  5552 InputSource source = new InputSource(new StringReader(text));
 276  5552 source.setEncoding(encoding);
 277   
 278  5552 result = reader.read(source);
 279   
 280    // if the XML parser doesn't provide a way to retrieve the encoding,
 281    // specify it manually
 282  5552 if (result.getXMLEncoding() == null) {
 283  5528 result.setXMLEncoding(encoding);
 284    }
 285   
 286  5552 return result;
 287    }
 288   
 289  5552 private static String getEncoding(String text) {
 290  5552 String result = null;
 291   
 292  5552 String xml = text.trim();
 293   
 294  5552 if (xml.startsWith("<?xml")) {
 295  25 int end = xml.indexOf("?>");
 296  25 String sub = xml.substring(0, end);
 297  25 StringTokenizer tokens = new StringTokenizer(sub, " =\"\'");
 298   
 299  25 while (tokens.hasMoreTokens()) {
 300  99 String token = tokens.nextToken();
 301   
 302  99 if ("encoding".equals(token)) {
 303  24 if (tokens.hasMoreTokens()) {
 304  24 result = tokens.nextToken();
 305    }
 306   
 307  24 break;
 308    }
 309    }
 310    }
 311   
 312  5552 return result;
 313    }
 314   
 315    /**
 316    * <p>
 317    * makeElement
 318    * </p>
 319    * a helper method which navigates from the given Document or Element node
 320    * to some Element using the path expression, creating any necessary
 321    * elements along the way. For example the path <code>a/b/c</code> would
 322    * get the first child &lt;a&gt; element, which would be created if it did
 323    * not exist, then the next child &lt;b&gt; and so on until finally a
 324    * &lt;c&gt; element is returned.
 325    *
 326    * @param source
 327    * is the Element or Document to start navigating from
 328    * @param path
 329    * is a simple path expression, seperated by '/' which denotes
 330    * the path from the source to the resulting element such as
 331    * a/b/c
 332    *
 333    * @return the first Element on the given path which either already existed
 334    * on the path or were created by this method.
 335    */
 336  6 public static Element makeElement(Branch source, String path) {
 337  6 StringTokenizer tokens = new StringTokenizer(path, "/");
 338  6 Element parent;
 339   
 340  6 if (source instanceof Document) {
 341  4 Document document = (Document) source;
 342  4 parent = document.getRootElement();
 343   
 344    // lets throw a NoSuchElementException
 345    // if we are given an empty path
 346  4 String name = tokens.nextToken();
 347   
 348  4 if (parent == null) {
 349  1 parent = document.addElement(name);
 350    }
 351    } else {
 352  2 parent = (Element) source;
 353    }
 354   
 355  6 Element element = null;
 356   
 357  6 while (tokens.hasMoreTokens()) {
 358  14 String name = tokens.nextToken();
 359   
 360  14 if (name.indexOf(':') > 0) {
 361  4 element = parent.element(parent.getQName(name));
 362    } else {
 363  10 element = parent.element(name);
 364    }
 365   
 366  14 if (element == null) {
 367  6 element = parent.addElement(name);
 368    }
 369   
 370  14 parent = element;
 371    }
 372   
 373  6 return element;
 374    }
 375    }
 376   
 377    /*
 378    * Redistribution and use of this software and associated documentation
 379    * ("Software"), with or without modification, are permitted provided that the
 380    * following conditions are met:
 381    *
 382    * 1. Redistributions of source code must retain copyright statements and
 383    * notices. Redistributions must also contain a copy of this document.
 384    *
 385    * 2. Redistributions in binary form must reproduce the above copyright notice,
 386    * this list of conditions and the following disclaimer in the documentation
 387    * and/or other materials provided with the distribution.
 388    *
 389    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 390    * from this Software without prior written permission of MetaStuff, Ltd. For
 391    * written permission, please contact dom4j-info@metastuff.com.
 392    *
 393    * 4. Products derived from this Software may not be called "DOM4J" nor may
 394    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 395    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 396    *
 397    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 398    *
 399    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 400    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 401    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 402    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 403    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 404    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 405    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 406    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 407    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 408    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 409    * POSSIBILITY OF SUCH DAMAGE.
 410    *
 411    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 412    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/ProcessingInstruction.html0000644000175000017500000007202210242117603023355 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 110   Methods: 0
NCLOC: 12   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
ProcessingInstruction.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    import java.util.Map;
 11   
 12    /**
 13    * <p>
 14    * <code>ProcessingInstruction</code> defines an XML processing instruction.
 15    * The {@link Node#getName}method will return the target of the PI and the
 16    * {@link Node#getText}method will return the data from all of the
 17    * instructions.
 18    * </p>
 19    *
 20    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 21    * @version $Revision: 1.10 $
 22    */
 23    public interface ProcessingInstruction extends Node {
 24    /**
 25    * This method is the equivalent to the {@link #getName}method. It is added
 26    * for clarity.
 27    *
 28    * @return the target of this PI
 29    */
 30    String getTarget();
 31   
 32    /**
 33    * This method is the equivalent to the {@link #setName}method. It is added
 34    * for clarity.
 35    *
 36    * @param target
 37    * DOCUMENT ME!
 38    */
 39    void setTarget(String target);
 40   
 41    /**
 42    * DOCUMENT ME!
 43    *
 44    * @return the text for all the data associated with the processing
 45    * instruction
 46    */
 47    String getText();
 48   
 49    /**
 50    * <p>
 51    * Returns the value of a specific name in the PI.
 52    * </p>
 53    *
 54    * @param name
 55    * is the name of the attribute to lookup.
 56    *
 57    * @return the value of the named attribute
 58    */
 59    String getValue(String name);
 60   
 61    /**
 62    * DOCUMENT ME!
 63    *
 64    * @return the values for this processing instruction as a Map
 65    */
 66    Map getValues();
 67   
 68    void setValue(String name, String value);
 69   
 70    void setValues(Map data);
 71   
 72    boolean removeValue(String name);
 73    }
 74   
 75    /*
 76    * Redistribution and use of this software and associated documentation
 77    * ("Software"), with or without modification, are permitted provided that the
 78    * following conditions are met:
 79    *
 80    * 1. Redistributions of source code must retain copyright statements and
 81    * notices. Redistributions must also contain a copy of this document.
 82    *
 83    * 2. Redistributions in binary form must reproduce the above copyright notice,
 84    * this list of conditions and the following disclaimer in the documentation
 85    * and/or other materials provided with the distribution.
 86    *
 87    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 88    * from this Software without prior written permission of MetaStuff, Ltd. For
 89    * written permission, please contact dom4j-info@metastuff.com.
 90    *
 91    * 4. Products derived from this Software may not be called "DOM4J" nor may
 92    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 93    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 94    *
 95    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 96    *
 97    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 98    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 99    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 100    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 101    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 102    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 103    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 104    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 105    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 106    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 107    * POSSIBILITY OF SUCH DAMAGE.
 108    *
 109    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 110    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dtd/0000755000175000017500000000000012133227266016671 5ustar ebourgebourgdom4j-1.6.1/docs/clover/org/dom4j/dtd/pkg-classes.html0000644000175000017500000000240010242117764021767 0ustar ebourgebourg dom4j - 1.6.1 org.dom4j.dtd
Classes
AttributeDecl (78%)
ElementDecl (64,3%)
ExternalEntityDecl (80%)
InternalEntityDecl (70,4%)
dom4j-1.6.1/docs/clover/org/dom4j/dtd/ExternalEntityDecl.html0000644000175000017500000013070710242117725023333 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 162   Methods: 9
NCLOC: 56   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
ExternalEntityDecl.java 75% 89,3% 55,6% 80%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dtd;
 9   
 10    /**
 11    * <p>
 12    * <code>ExternalEntityDecl</code> represents an external entity declaration
 13    * in a DTD.
 14    * </p>
 15    *
 16    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 17    * @version $Revision: 1.9 $
 18    */
 19    public class ExternalEntityDecl {
 20    /** Holds value of property name. */
 21    private String name;
 22   
 23    /** Holds value of property publicID. */
 24    private String publicID;
 25   
 26    /** Holds value of property systemID. */
 27    private String systemID;
 28   
 29  0 public ExternalEntityDecl() {
 30    }
 31   
 32  4 public ExternalEntityDecl(String name, String publicID, String systemID) {
 33  4 this.name = name;
 34  4 this.publicID = publicID;
 35  4 this.systemID = systemID;
 36    }
 37   
 38    /**
 39    * Getter for property name.
 40    *
 41    * @return Value of property name.
 42    */
 43  2 public String getName() {
 44  2 return name;
 45    }
 46   
 47    /**
 48    * Setter for property name.
 49    *
 50    * @param name
 51    * New value of property name.
 52    */
 53  0 public void setName(String name) {
 54  0 this.name = name;
 55    }
 56   
 57    /**
 58    * Getter for property publicID.
 59    *
 60    * @return Value of property publicID.
 61    */
 62  2 public String getPublicID() {
 63  2 return publicID;
 64    }
 65   
 66    /**
 67    * Setter for property publicID.
 68    *
 69    * @param publicID
 70    * New value of property publicID.
 71    */
 72  0 public void setPublicID(String publicID) {
 73  0 this.publicID = publicID;
 74    }
 75   
 76    /**
 77    * Getter for property systemID.
 78    *
 79    * @return Value of property systemID.
 80    */
 81  2 public String getSystemID() {
 82  2 return systemID;
 83    }
 84   
 85    /**
 86    * Setter for property systemID.
 87    *
 88    * @param systemID
 89    * New value of property systemID.
 90    */
 91  0 public void setSystemID(String systemID) {
 92  0 this.systemID = systemID;
 93    }
 94   
 95  4 public String toString() {
 96  4 StringBuffer buffer = new StringBuffer("<!ENTITY ");
 97   
 98  4 if (name.startsWith("%")) {
 99  1 buffer.append("% ");
 100  1 buffer.append(name.substring(1));
 101    } else {
 102  3 buffer.append(name);
 103    }
 104   
 105  4 if (publicID != null) {
 106  1 buffer.append(" PUBLIC \"");
 107  1 buffer.append(publicID);
 108  1 buffer.append("\" ");
 109   
 110  1 if (systemID != null) {
 111  1 buffer.append("\"");
 112  1 buffer.append(systemID);
 113  1 buffer.append("\" ");
 114    }
 115  3 } else if (systemID != null) {
 116  3 buffer.append(" SYSTEM \"");
 117  3 buffer.append(systemID);
 118  3 buffer.append("\" ");
 119    }
 120   
 121  4 buffer.append(">");
 122   
 123  4 return buffer.toString();
 124    }
 125    }
 126   
 127    /*
 128    * Redistribution and use of this software and associated documentation
 129    * ("Software"), with or without modification, are permitted provided that the
 130    * following conditions are met:
 131    *
 132    * 1. Redistributions of source code must retain copyright statements and
 133    * notices. Redistributions must also contain a copy of this document.
 134    *
 135    * 2. Redistributions in binary form must reproduce the above copyright notice,
 136    * this list of conditions and the following disclaimer in the documentation
 137    * and/or other materials provided with the distribution.
 138    *
 139    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 140    * from this Software without prior written permission of MetaStuff, Ltd. For
 141    * written permission, please contact dom4j-info@metastuff.com.
 142    *
 143    * 4. Products derived from this Software may not be called "DOM4J" nor may
 144    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 145    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 146    *
 147    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 148    *
 149    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 150    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 151    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 152    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 153    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 154    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 155    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 156    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 157    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 158    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 159    * POSSIBILITY OF SUCH DAMAGE.
 160    *
 161    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 162    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dtd/pkg-summary.html0000644000175000017500000001653110242117727022040 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
package stats: LOC: 650   Methods: 37
NCLOC: 220   Classes: 4
Files: 4  
 
 Package Conditionals Statements Methods TOTAL
org.dom4j.dtd 83,3% 79,6% 56,8% 74,8%
coverage coverage
 
 Classes Conditionals Statements Methods TOTAL
ElementDecl - 71,4% 57,1% 64,3%
coverage coverage
InternalEntityDecl 83,3% 70% 62,5% 70,4%
coverage coverage
AttributeDecl 100% 84,8% 53,8% 78%
coverage coverage
ExternalEntityDecl 75% 89,3% 55,6% 80%
coverage coverage
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dtd/AttributeDecl.html0000644000175000017500000015553610242117565022330 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 205   Methods: 13
NCLOC: 71   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
AttributeDecl.java 100% 84,8% 53,8% 78%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dtd;
 9   
 10    /**
 11    * <p>
 12    * <code>AttributeDecl</code> represents an attribute declaration in a DTD.
 13    * </p>
 14    *
 15    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 16    * @version $Revision: 1.7 $
 17    */
 18    public class AttributeDecl {
 19    /** Holds value of property elementName. */
 20    private String elementName;
 21   
 22    /** Holds value of property attributeName. */
 23    private String attributeName;
 24   
 25    /** Holds value of property type. */
 26    private String type;
 27   
 28    /** Holds value of property value. */
 29    private String value;
 30   
 31    /** Holds value of property valueDefault. */
 32    private String valueDefault;
 33   
 34  0 public AttributeDecl() {
 35    }
 36   
 37  8 public AttributeDecl(String elementName, String attributeName, String type,
 38    String valueDefault, String value) {
 39  8 this.elementName = elementName;
 40  8 this.attributeName = attributeName;
 41  8 this.type = type;
 42  8 this.value = value;
 43  8 this.valueDefault = valueDefault;
 44    }
 45   
 46    /**
 47    * Getter for property elementName.
 48    *
 49    * @return Value of property elementName.
 50    */
 51  7 public String getElementName() {
 52  7 return elementName;
 53    }
 54   
 55    /**
 56    * Setter for property elementName.
 57    *
 58    * @param elementName
 59    * New value of property elementName.
 60    */
 61  0 public void setElementName(String elementName) {
 62  0 this.elementName = elementName;
 63    }
 64   
 65    /**
 66    * Getter for property attributeName.
 67    *
 68    * @return Value of property attributeName.
 69    */
 70  7 public String getAttributeName() {
 71  7 return attributeName;
 72    }
 73   
 74    /**
 75    * Setter for property attributeName.
 76    *
 77    * @param attributeName
 78    * New value of property attributeName.
 79    */
 80  0 public void setAttributeName(String attributeName) {
 81  0 this.attributeName = attributeName;
 82    }
 83   
 84    /**
 85    * Getter for property type.
 86    *
 87    * @return Value of property type.
 88    */
 89  7 public String getType() {
 90  7 return type;
 91    }
 92   
 93    /**
 94    * Setter for property type.
 95    *
 96    * @param type
 97    * New value of property type.
 98    */
 99  0 public void setType(String type) {
 100  0 this.type = type;
 101    }
 102   
 103    /**
 104    * Getter for property value.
 105    *
 106    * @return Value of property value.
 107    */
 108  4 public String getValue() {
 109  4 return value;
 110    }
 111   
 112    /**
 113    * Setter for property value.
 114    *
 115    * @param value
 116    * New value of property value.
 117    */
 118  0 public void setValue(String value) {
 119  0 this.value = value;
 120    }
 121   
 122    /**
 123    * Getter for property valueDefault.
 124    *
 125    * @return Value of property valueDefault.
 126    */
 127  7 public String getValueDefault() {
 128  7 return valueDefault;
 129    }
 130   
 131    /**
 132    * Setter for property valueDefault.
 133    *
 134    * @param valueDefault
 135    * New value of property valueDefault.
 136    */
 137  0 public void setValueDefault(String valueDefault) {
 138  0 this.valueDefault = valueDefault;
 139    }
 140   
 141  11 public String toString() {
 142  11 StringBuffer buffer = new StringBuffer("<!ATTLIST ");
 143  11 buffer.append(elementName);
 144  11 buffer.append(" ");
 145  11 buffer.append(attributeName);
 146  11 buffer.append(" ");
 147  11 buffer.append(type);
 148  11 buffer.append(" ");
 149   
 150  11 if (valueDefault != null) {
 151  10 buffer.append(valueDefault);
 152   
 153  10 if (valueDefault.equals("#FIXED")) {
 154  1 buffer.append(" \"");
 155  1 buffer.append(value);
 156  1 buffer.append("\"");
 157    }
 158    } else {
 159  1 buffer.append("\"");
 160  1 buffer.append(value);
 161  1 buffer.append("\"");
 162    }
 163   
 164  11 buffer.append(">");
 165   
 166  11 return buffer.toString();
 167    }
 168    }
 169   
 170    /*
 171    * Redistribution and use of this software and associated documentation
 172    * ("Software"), with or without modification, are permitted provided that the
 173    * following conditions are met:
 174    *
 175    * 1. Redistributions of source code must retain copyright statements and
 176    * notices. Redistributions must also contain a copy of this document.
 177    *
 178    * 2. Redistributions in binary form must reproduce the above copyright notice,
 179    * this list of conditions and the following disclaimer in the documentation
 180    * and/or other materials provided with the distribution.
 181    *
 182    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 183    * from this Software without prior written permission of MetaStuff, Ltd. For
 184    * written permission, please contact dom4j-info@metastuff.com.
 185    *
 186    * 4. Products derived from this Software may not be called "DOM4J" nor may
 187    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 188    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 189    *
 190    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 191    *
 192    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 193    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 194    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 195    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 196    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 197    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 198    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 199    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 200    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 201    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 202    * POSSIBILITY OF SUCH DAMAGE.
 203    *
 204    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 205    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dtd/InternalEntityDecl.html0000644000175000017500000013666510242117742023335 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 172   Methods: 8
NCLOC: 67   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
InternalEntityDecl.java 83,3% 70% 62,5% 70,4%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dtd;
 9   
 10    /**
 11    * <p>
 12    * <code>InternalEntityDecl</code> represents an internal entity declaration
 13    * in a DTD.
 14    * </p>
 15    *
 16    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 17    * @version $Revision: 1.9 $
 18    */
 19    public class InternalEntityDecl {
 20    /** Holds value of property name. */
 21    private String name;
 22   
 23    /** Holds value of property value. */
 24    private String value;
 25   
 26  0 public InternalEntityDecl() {
 27    }
 28   
 29  19 public InternalEntityDecl(String name, String value) {
 30  19 this.name = name;
 31  19 this.value = value;
 32    }
 33   
 34    /**
 35    * Getter for property name.
 36    *
 37    * @return Value of property name.
 38    */
 39  6 public String getName() {
 40  6 return name;
 41    }
 42   
 43    /**
 44    * Setter for property name.
 45    *
 46    * @param name
 47    * New value of property name.
 48    */
 49  0 public void setName(String name) {
 50  0 this.name = name;
 51    }
 52   
 53    /**
 54    * Getter for property value.
 55    *
 56    * @return Value of property value.
 57    */
 58  6 public String getValue() {
 59  6 return value;
 60    }
 61   
 62    /**
 63    * Setter for property value.
 64    *
 65    * @param value
 66    * New value of property value.
 67    */
 68  0 public void setValue(String value) {
 69  0 this.value = value;
 70    }
 71   
 72  22 public String toString() {
 73  22 StringBuffer buffer = new StringBuffer("<!ENTITY ");
 74   
 75  22 if (name.startsWith("%")) {
 76  10 buffer.append("% ");
 77  10 buffer.append(name.substring(1));
 78    } else {
 79  12 buffer.append(name);
 80    }
 81   
 82  22 buffer.append(" \"");
 83  22 buffer.append(escapeEntityValue(value));
 84  22 buffer.append("\">");
 85   
 86  22 return buffer.toString();
 87    }
 88   
 89  22 private String escapeEntityValue(String text) {
 90  22 StringBuffer result = new StringBuffer();
 91   
 92  22 for (int i = 0; i < text.length(); i++) {
 93  167 char c = text.charAt(i);
 94   
 95  167 switch (c) {
 96  0 case '<':
 97  0 result.append("&#38;#60;");
 98   
 99  0 break;
 100   
 101  1 case '>':
 102  1 result.append("&#62;");
 103   
 104  1 break;
 105   
 106  0 case '&':
 107  0 result.append("&#38;#38;");
 108   
 109  0 break;
 110   
 111  0 case '\'':
 112  0 result.append("&#39;");
 113   
 114  0 break;
 115   
 116  1 case '\"':
 117  1 result.append("&#34;");
 118   
 119  1 break;
 120   
 121  165 default:
 122   
 123  165 if (c < 32) {
 124  0 result.append("&#" + (int) c + ";");
 125    } else {
 126  165 result.append(c);
 127    }
 128   
 129  165 break;
 130    }
 131    }
 132   
 133  22 return result.toString();
 134    }
 135    }
 136   
 137    /*
 138    * Redistribution and use of this software and associated documentation
 139    * ("Software"), with or without modification, are permitted provided that the
 140    * following conditions are met:
 141    *
 142    * 1. Redistributions of source code must retain copyright statements and
 143    * notices. Redistributions must also contain a copy of this document.
 144    *
 145    * 2. Redistributions in binary form must reproduce the above copyright notice,
 146    * this list of conditions and the following disclaimer in the documentation
 147    * and/or other materials provided with the distribution.
 148    *
 149    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 150    * from this Software without prior written permission of MetaStuff, Ltd. For
 151    * written permission, please contact dom4j-info@metastuff.com.
 152    *
 153    * 4. Products derived from this Software may not be called "DOM4J" nor may
 154    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 155    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 156    *
 157    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 158    *
 159    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 160    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 161    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 162    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 163    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 164    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 165    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 166    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 167    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 168    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 169    * POSSIBILITY OF SUCH DAMAGE.
 170    *
 171    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 172    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/dtd/ElementDecl.html0000644000175000017500000007520110242117545021742 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 111   Methods: 7
NCLOC: 26   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
ElementDecl.java - 71,4% 57,1% 64,3%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.dtd;
 9   
 10    /**
 11    * <p>
 12    * <code>AttributeDecl</code> represents an element declaration in a DTD.
 13    * </p>
 14    *
 15    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 16    * @version $Revision: 1.6 $
 17    */
 18    public class ElementDecl {
 19    /** Holds value of property name. */
 20    private String name;
 21   
 22    /** Holds value of property model. */
 23    private String model;
 24   
 25  0 public ElementDecl() {
 26    }
 27   
 28  11 public ElementDecl(String name, String model) {
 29  11 this.name = name;
 30  11 this.model = model;
 31    }
 32   
 33    /**
 34    * Getter for property name.
 35    *
 36    * @return Value of property name.
 37    */
 38  11 public String getName() {
 39  11 return name;
 40    }
 41   
 42    /**
 43    * Setter for property name.
 44    *
 45    * @param name
 46    * New value of property name.
 47    */
 48  0 public void setName(String name) {
 49  0 this.name = name;
 50    }
 51   
 52    /**
 53    * Getter for property model.
 54    *
 55    * @return Value of property model.
 56    */
 57  11 public String getModel() {
 58  11 return model;
 59    }
 60   
 61    /**
 62    * Setter for property model.
 63    *
 64    * @param model
 65    * New value of property model.
 66    */
 67  0 public void setModel(String model) {
 68  0 this.model = model;
 69    }
 70   
 71  18 public String toString() {
 72  18 return "<!ELEMENT " + name + " " + model + ">";
 73    }
 74    }
 75   
 76    /*
 77    * Redistribution and use of this software and associated documentation
 78    * ("Software"), with or without modification, are permitted provided that the
 79    * following conditions are met:
 80    *
 81    * 1. Redistributions of source code must retain copyright statements and
 82    * notices. Redistributions must also contain a copy of this document.
 83    *
 84    * 2. Redistributions in binary form must reproduce the above copyright notice,
 85    * this list of conditions and the following disclaimer in the documentation
 86    * and/or other materials provided with the distribution.
 87    *
 88    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 89    * from this Software without prior written permission of MetaStuff, Ltd. For
 90    * written permission, please contact dom4j-info@metastuff.com.
 91    *
 92    * 4. Products derived from this Software may not be called "DOM4J" nor may
 93    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 94    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 95    *
 96    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 97    *
 98    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 99    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 100    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 101    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 102    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 103    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 104    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 105    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 106    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 107    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 108    * POSSIBILITY OF SUCH DAMAGE.
 109    *
 110    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 111    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/VisitorSupport.html0000644000175000017500000006260010242117672022042 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 90   Methods: 11
NCLOC: 25   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
VisitorSupport.java - - 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    /**
 11    * <p>
 12    * <code>VisitorSupport</code> is an abstract base class which is useful for
 13    * implementation inheritence or when using anonymous inner classes to create
 14    * simple <code>Visitor</code> implementations.
 15    * </p>
 16    *
 17    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 18    * @version $Revision: 1.6 $
 19    */
 20    public abstract class VisitorSupport implements Visitor {
 21  0 public VisitorSupport() {
 22    }
 23   
 24  0 public void visit(Document document) {
 25    }
 26   
 27  0 public void visit(DocumentType documentType) {
 28    }
 29   
 30  0 public void visit(Element node) {
 31    }
 32   
 33  0 public void visit(Attribute node) {
 34    }
 35   
 36  0 public void visit(CDATA node) {
 37    }
 38   
 39  0 public void visit(Comment node) {
 40    }
 41   
 42  0 public void visit(Entity node) {
 43    }
 44   
 45  0 public void visit(Namespace namespace) {
 46    }
 47   
 48  0 public void visit(ProcessingInstruction node) {
 49    }
 50   
 51  0 public void visit(Text node) {
 52    }
 53    }
 54   
 55    /*
 56    * Redistribution and use of this software and associated documentation
 57    * ("Software"), with or without modification, are permitted provided that the
 58    * following conditions are met:
 59    *
 60    * 1. Redistributions of source code must retain copyright statements and
 61    * notices. Redistributions must also contain a copy of this document.
 62    *
 63    * 2. Redistributions in binary form must reproduce the above copyright notice,
 64    * this list of conditions and the following disclaimer in the documentation
 65    * and/or other materials provided with the distribution.
 66    *
 67    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 68    * from this Software without prior written permission of MetaStuff, Ltd. For
 69    * written permission, please contact dom4j-info@metastuff.com.
 70    *
 71    * 4. Products derived from this Software may not be called "DOM4J" nor may
 72    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 73    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 74    *
 75    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 76    *
 77    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 78    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 79    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 80    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 81    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 82    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 83    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 84    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 85    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 86    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 87    * POSSIBILITY OF SUCH DAMAGE.
 88    *
 89    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 90    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/Visitor.html0000644000175000017500000012423210242117544020443 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 166   Methods: 0
NCLOC: 13   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
Visitor.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    /**
 11    * <p>
 12    * <code>Visitor</code> is used to implement the <code>Visitor</code>
 13    * pattern in DOM4J. An object of this interface can be passed to a
 14    * <code>Node</code> which will then call its typesafe methods. Please refer
 15    * to the <i>Gang of Four </i> book of Design Patterns for more details on the
 16    * <code>Visitor</code> pattern.
 17    * </p>
 18    *
 19    * <p>
 20    * This <a href="http://www.patterndepot.com/put/8/JavaPatterns.htm">site </a>
 21    * has further discussion on design patterns and links to the GOF book. This <a
 22    * href="http://www.patterndepot.com/put/8/visitor.pdf">link </a> describes the
 23    * Visitor pattern in detail.
 24    * </p>
 25    *
 26    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 27    * @version $Revision: 1.8 $
 28    */
 29    public interface Visitor {
 30    /**
 31    * <p>
 32    * Visits the given <code>Document</code>
 33    * </p>
 34    *
 35    * @param document
 36    * is the <code>Document</code> node to visit.
 37    */
 38    void visit(Document document);
 39   
 40    /**
 41    * <p>
 42    * Visits the given <code>DocumentType</code>
 43    * </p>
 44    *
 45    * @param documentType
 46    * is the <code>DocumentType</code> node to visit.
 47    */
 48    void visit(DocumentType documentType);
 49   
 50    /**
 51    * <p>
 52    * Visits the given <code>Element</code>
 53    * </p>
 54    *
 55    * @param node
 56    * is the <code>Element</code> node to visit.
 57    */
 58    void visit(Element node);
 59   
 60    /**
 61    * <p>
 62    * Visits the given <code>Attribute</code>
 63    * </p>
 64    *
 65    * @param node
 66    * is the <code>Attribute</code> node to visit.
 67    */
 68    void visit(Attribute node);
 69   
 70    /**
 71    * <p>
 72    * Visits the given <code>CDATA</code>
 73    * </p>
 74    *
 75    * @param node
 76    * is the <code>CDATA</code> node to visit.
 77    */
 78    void visit(CDATA node);
 79   
 80    /**
 81    * <p>
 82    * Visits the given <code>Comment</code>
 83    * </p>
 84    *
 85    * @param node
 86    * is the <code>Comment</code> node to visit.
 87    */
 88    void visit(Comment node);
 89   
 90    /**
 91    * <p>
 92    * Visits the given <code>Entity</code>
 93    * </p>
 94    *
 95    * @param node
 96    * is the <code>Entity</code> node to visit.
 97    */
 98    void visit(Entity node);
 99   
 100    /**
 101    * <p>
 102    * Visits the given <code>Namespace</code>
 103    * </p>
 104    *
 105    * @param namespace
 106    * is the <code>Namespace</code> node to visit.
 107    */
 108    void visit(Namespace namespace);
 109   
 110    /**
 111    * <p>
 112    * Visits the given <code>ProcessingInstruction</code>
 113    * </p>
 114    *
 115    * @param node
 116    * is the <code>ProcessingInstruction</code> node to visit.
 117    */
 118    void visit(ProcessingInstruction node);
 119   
 120    /**
 121    * <p>
 122    * Visits the given <code>Text</code>
 123    * </p>
 124    *
 125    * @param node
 126    * is the <code>Text</code> node to visit.
 127    */
 128    void visit(Text node);
 129    }
 130   
 131    /*
 132    * Redistribution and use of this software and associated documentation
 133    * ("Software"), with or without modification, are permitted provided that the
 134    * following conditions are met:
 135    *
 136    * 1. Redistributions of source code must retain copyright statements and
 137    * notices. Redistributions must also contain a copy of this document.
 138    *
 139    * 2. Redistributions in binary form must reproduce the above copyright notice,
 140    * this list of conditions and the following disclaimer in the documentation
 141    * and/or other materials provided with the distribution.
 142    *
 143    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 144    * from this Software without prior written permission of MetaStuff, Ltd. For
 145    * written permission, please contact dom4j-info@metastuff.com.
 146    *
 147    * 4. Products derived from this Software may not be called "DOM4J" nor may
 148    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 149    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 150    *
 151    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 152    *
 153    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 154    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 155    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 156    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 157    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 158    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 159    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 160    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 161    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 162    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 163    * POSSIBILITY OF SUCH DAMAGE.
 164    *
 165    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 166    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/CharacterData.html0000644000175000017500000005003010242117572021465 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 68   Methods: 0
NCLOC: 4   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
CharacterData.java - - - -
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    /**
 11    * <p>
 12    * <code>CharacterData</code> is a marker interface for character based nodes
 13    * such as the <code>CDATA</code>,<code>Comment</code> and
 14    * <code>Text</code> nodes.
 15    * </p>
 16    *
 17    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 18    * @version $Revision: 1.9 $
 19    */
 20    public interface CharacterData extends Node {
 21    /**
 22    * Appends the given text to this nodes text value. Calling this method is
 23    * equivalent of the code <code>node.setText(node.getText() + text)</code>
 24    * but allows for possible implementation optimisations (such as a text
 25    * based node storing a StringBuffer internally
 26    *
 27    * @param text
 28    * the text to append
 29    */
 30    void appendText(String text);
 31    }
 32   
 33    /*
 34    * Redistribution and use of this software and associated documentation
 35    * ("Software"), with or without modification, are permitted provided that the
 36    * following conditions are met:
 37    *
 38    * 1. Redistributions of source code must retain copyright statements and
 39    * notices. Redistributions must also contain a copy of this document.
 40    *
 41    * 2. Redistributions in binary form must reproduce the above copyright notice,
 42    * this list of conditions and the following disclaimer in the documentation
 43    * and/or other materials provided with the distribution.
 44    *
 45    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 46    * from this Software without prior written permission of MetaStuff, Ltd. For
 47    * written permission, please contact dom4j-info@metastuff.com.
 48    *
 49    * 4. Products derived from this Software may not be called "DOM4J" nor may
 50    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 51    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 52    *
 53    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 54    *
 55    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 56    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 57    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 58    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 59    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 60    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 61    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 62    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 63    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 64    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 65    * POSSIBILITY OF SUCH DAMAGE.
 66    *
 67    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 68    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/XPathException.html0000644000175000017500000006125010242117625021707 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 84   Methods: 4
NCLOC: 20   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
XPathException.java - 28,6% 25% 27,3%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j;
 9   
 10    /**
 11    * <p>
 12    * <code>XPathException</code> is thrown when an exception occurs while
 13    * evaluating an XPath expression, usually due to some function throwing an
 14    * exception.
 15    * </p>
 16    *
 17    * @version $Revision: 1.6 $
 18    */
 19    public class XPathException extends RuntimeException {
 20    /** The XPath expression that caused the exception */
 21    private String xpath;
 22   
 23  0 public XPathException(String xpath) {
 24  0 super("Exception occurred evaluting XPath: " + xpath);
 25  0 this.xpath = xpath;
 26    }
 27   
 28  0 public XPathException(String xpath, String reason) {
 29  0 super("Exception occurred evaluting XPath: " + xpath + " " + reason);
 30  0 this.xpath = xpath;
 31    }
 32   
 33  1 public XPathException(String xpath, Exception e) {
 34  1 super("Exception occurred evaluting XPath: " + xpath + ". Exception: "
 35    + e.getMessage());
 36  1 this.xpath = xpath;
 37    }
 38   
 39    /**
 40    * Returns the XPath expression that caused the problem
 41    *
 42    * @return DOCUMENT ME!
 43    */
 44  0 public String getXPath() {
 45  0 return xpath;
 46    }
 47    }
 48   
 49    /*
 50    * Redistribution and use of this software and associated documentation
 51    * ("Software"), with or without modification, are permitted provided that the
 52    * following conditions are met:
 53    *
 54    * 1. Redistributions of source code must retain copyright statements and
 55    * notices. Redistributions must also contain a copy of this document.
 56    *
 57    * 2. Redistributions in binary form must reproduce the above copyright notice,
 58    * this list of conditions and the following disclaimer in the documentation
 59    * and/or other materials provided with the distribution.
 60    *
 61    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 62    * from this Software without prior written permission of MetaStuff, Ltd. For
 63    * written permission, please contact dom4j-info@metastuff.com.
 64    *
 65    * 4. Products derived from this Software may not be called "DOM4J" nor may
 66    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 67    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 68    *
 69    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 70    *
 71    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 72    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 73    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 74    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 75    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 76    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 77    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 78    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 79    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 80    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 81    * POSSIBILITY OF SUCH DAMAGE.
 82    *
 83    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 84    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/datatype/0000755000175000017500000000000012133227266017731 5ustar ebourgebourgdom4j-1.6.1/docs/clover/org/dom4j/datatype/pkg-classes.html0000644000175000017500000000340410242117754023033 0ustar ebourgebourg dom4j - 1.6.1 org.dom4j.datatype
Classes
DatatypeAttribute (38,5%)
DatatypeDocumentFactory (50%)
DatatypeElement (54,7%)
DatatypeElementFactory (91,7%)
InvalidSchemaException (0%)
NamedTypeResolver (94,7%)
SchemaParser (71,3%)
dom4j-1.6.1/docs/clover/org/dom4j/datatype/SchemaParser.html0000644000175000017500000050633510242117711023200 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 607   Methods: 18
NCLOC: 324   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
SchemaParser.java 67,6% 71,6% 83,3% 71,3%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.datatype;
 9   
 10    import com.sun.msv.datatype.xsd.DatatypeFactory;
 11    import com.sun.msv.datatype.xsd.TypeIncubator;
 12    import com.sun.msv.datatype.xsd.XSDatatype;
 13   
 14    import java.util.HashMap;
 15    import java.util.Iterator;
 16    import java.util.Map;
 17   
 18    import org.dom4j.Attribute;
 19    import org.dom4j.Document;
 20    import org.dom4j.DocumentFactory;
 21    import org.dom4j.Element;
 22    import org.dom4j.Namespace;
 23    import org.dom4j.QName;
 24    import org.dom4j.io.SAXReader;
 25    import org.dom4j.util.AttributeHelper;
 26   
 27    import org.relaxng.datatype.DatatypeException;
 28    import org.relaxng.datatype.ValidationContext;
 29   
 30    import org.xml.sax.EntityResolver;
 31    import org.xml.sax.InputSource;
 32   
 33    /**
 34    * <p>
 35    * <code>SchemaParser</code> reads an XML Schema Document.
 36    * </p>
 37    *
 38    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 39    * @author Yuxin Ruan
 40    * @version $Revision: 1.19 $
 41    */
 42    public class SchemaParser {
 43    private static final Namespace XSD_NAMESPACE = Namespace.get("xsd",
 44    "http://www.w3.org/2001/XMLSchema");
 45   
 46    // Use QNames for the elements
 47    private static final QName XSD_ELEMENT = QName
 48    .get("element", XSD_NAMESPACE);
 49   
 50    private static final QName XSD_ATTRIBUTE = QName.get("attribute",
 51    XSD_NAMESPACE);
 52   
 53    private static final QName XSD_SIMPLETYPE = QName.get("simpleType",
 54    XSD_NAMESPACE);
 55   
 56    private static final QName XSD_COMPLEXTYPE = QName.get("complexType",
 57    XSD_NAMESPACE);
 58   
 59    private static final QName XSD_RESTRICTION = QName.get("restriction",
 60    XSD_NAMESPACE);
 61   
 62    private static final QName XSD_SEQUENCE = QName.get("sequence",
 63    XSD_NAMESPACE);
 64   
 65    private static final QName XSD_CHOICE = QName.get("choice", XSD_NAMESPACE);
 66   
 67    private static final QName XSD_ALL = QName.get("all", XSD_NAMESPACE);
 68   
 69    private static final QName XSD_INCLUDE = QName
 70    .get("include", XSD_NAMESPACE);
 71   
 72    /** Document factory used to register Element specific factories */
 73    private DatatypeDocumentFactory documentFactory;
 74   
 75    /**
 76    * Cache of <code>XSDatatype</code> instances loaded or created during
 77    * this build
 78    */
 79    private Map dataTypeCache = new HashMap();
 80   
 81    /** NamedTypeResolver */
 82    private NamedTypeResolver namedTypeResolver;
 83   
 84    /** target namespace */
 85    private Namespace targetNamespace;
 86   
 87  0 public SchemaParser() {
 88  0 this(DatatypeDocumentFactory.singleton);
 89    }
 90   
 91  27 public SchemaParser(DatatypeDocumentFactory documentFactory) {
 92  27 this.documentFactory = documentFactory;
 93  27 this.namedTypeResolver = new NamedTypeResolver(documentFactory);
 94    }
 95   
 96    /**
 97    * Parses the given schema document
 98    *
 99    * @param schemaDocument
 100    * is the document of the XML Schema
 101    */
 102  22 public void build(Document schemaDocument) {
 103  22 this.targetNamespace = null;
 104  22 internalBuild(schemaDocument);
 105    }
 106   
 107  3 public void build(Document schemaDocument, Namespace namespace) {
 108  3 this.targetNamespace = namespace;
 109  3 internalBuild(schemaDocument);
 110    }
 111   
 112  25 private synchronized void internalBuild(Document schemaDocument) {
 113  25 Element root = schemaDocument.getRootElement();
 114   
 115  25 if (root != null) {
 116    // handle schema includes
 117  25 Iterator includeIter = root.elementIterator(XSD_INCLUDE);
 118   
 119  25 while (includeIter.hasNext()) {
 120  0 Element includeElement = (Element) includeIter.next();
 121  0 String inclSchemaInstanceURI = includeElement
 122    .attributeValue("schemaLocation");
 123  0 EntityResolver resolver = schemaDocument.getEntityResolver();
 124   
 125  0 try {
 126  0 if (resolver == null) {
 127  0 String msg = "No EntityResolver available";
 128  0 throw new InvalidSchemaException(msg);
 129    }
 130   
 131  0 InputSource inputSource = resolver.resolveEntity(null,
 132    inclSchemaInstanceURI);
 133   
 134  0 if (inputSource == null) {
 135  0 String msg = "Could not resolve the schema URI: "
 136    + inclSchemaInstanceURI;
 137  0 throw new InvalidSchemaException(msg);
 138    }
 139   
 140  0 SAXReader reader = new SAXReader();
 141  0 Document inclSchemaDocument = reader.read(inputSource);
 142  0 build(inclSchemaDocument);
 143    } catch (Exception e) {
 144  0 System.out.println("Failed to load schema: "
 145    + inclSchemaInstanceURI);
 146  0 System.out.println("Caught: " + e);
 147  0 e.printStackTrace();
 148  0 throw new InvalidSchemaException("Failed to load schema: "
 149    + inclSchemaInstanceURI);
 150    }
 151    }
 152   
 153    // handle elements
 154  25 Iterator iter = root.elementIterator(XSD_ELEMENT);
 155   
 156  25 while (iter.hasNext()) {
 157  180 onDatatypeElement((Element) iter.next(), documentFactory);
 158    }
 159   
 160    // handle named simple types
 161  25 iter = root.elementIterator(XSD_SIMPLETYPE);
 162   
 163  25 while (iter.hasNext()) {
 164  1 onNamedSchemaSimpleType((Element) iter.next());
 165    }
 166   
 167    // hanlde named complex types
 168  25 iter = root.elementIterator(XSD_COMPLEXTYPE);
 169   
 170  25 while (iter.hasNext()) {
 171  2 onNamedSchemaComplexType((Element) iter.next());
 172    }
 173   
 174  25 namedTypeResolver.resolveNamedTypes();
 175    }
 176    }
 177   
 178    // Implementation methods
 179    // -------------------------------------------------------------------------
 180   
 181    /**
 182    * processes an XML Schema &lt;element&gt; tag
 183    *
 184    * @param xsdElement
 185    * DOCUMENT ME!
 186    * @param parentFactory
 187    * DOCUMENT ME!
 188    */
 189  406 private void onDatatypeElement(Element xsdElement,
 190    DocumentFactory parentFactory) {
 191  406 String name = xsdElement.attributeValue("name");
 192  406 String type = xsdElement.attributeValue("type");
 193  406 QName qname = getQName(name);
 194   
 195  406 DatatypeElementFactory factory = getDatatypeElementFactory(qname);
 196   
 197  406 if (type != null) {
 198    // register type with this element name
 199  146 XSDatatype dataType = getTypeByName(type);
 200   
 201  146 if (dataType != null) {
 202  143 factory.setChildElementXSDatatype(qname, dataType);
 203    } else {
 204  3 QName typeQName = getQName(type);
 205  3 namedTypeResolver.registerTypedElement(xsdElement, typeQName,
 206    parentFactory);
 207    }
 208   
 209  146 return;
 210    }
 211   
 212    // handle element types derrived from simpleTypes
 213  260 Element xsdSimpleType = xsdElement.element(XSD_SIMPLETYPE);
 214   
 215  260 if (xsdSimpleType != null) {
 216  0 XSDatatype dataType = loadXSDatatypeFromSimpleType(xsdSimpleType);
 217   
 218  0 if (dataType != null) {
 219  0 factory.setChildElementXSDatatype(qname, dataType);
 220    }
 221    }
 222   
 223  260 Element schemaComplexType = xsdElement.element(XSD_COMPLEXTYPE);
 224   
 225  260 if (schemaComplexType != null) {
 226  107 onSchemaComplexType(schemaComplexType, factory);
 227    }
 228   
 229  260 Iterator iter = xsdElement.elementIterator(XSD_ATTRIBUTE);
 230   
 231  260 if (iter.hasNext()) {
 232  0 do {
 233  0 onDatatypeAttribute(xsdElement, factory, (Element) iter
 234    .next());
 235  0 } while (iter.hasNext());
 236    }
 237    }
 238   
 239    /**
 240    * processes an named XML Schema &lt;complexTypegt; tag
 241    *
 242    * @param schemaComplexType
 243    * DOCUMENT ME!
 244    */
 245  2 private void onNamedSchemaComplexType(Element schemaComplexType) {
 246  2 Attribute nameAttr = schemaComplexType.attribute("name");
 247   
 248  2 if (nameAttr == null) {
 249  0 return;
 250    }
 251   
 252  2 String name = nameAttr.getText();
 253  2 QName qname = getQName(name);
 254   
 255  2 DatatypeElementFactory factory = getDatatypeElementFactory(qname);
 256   
 257  2 onSchemaComplexType(schemaComplexType, factory);
 258  2 namedTypeResolver.registerComplexType(qname, factory);
 259    }
 260   
 261    /**
 262    * processes an XML Schema &lt;complexTypegt; tag
 263    *
 264    * @param schemaComplexType
 265    * DOCUMENT ME!
 266    * @param elementFactory
 267    * DOCUMENT ME!
 268    */
 269  109 private void onSchemaComplexType(Element schemaComplexType,
 270    DatatypeElementFactory elementFactory) {
 271  109 Iterator iter = schemaComplexType.elementIterator(XSD_ATTRIBUTE);
 272   
 273  109 while (iter.hasNext()) {
 274  265 Element xsdAttribute = (Element) iter.next();
 275  265 String name = xsdAttribute.attributeValue("name");
 276  265 QName qname = getQName(name);
 277   
 278  265 XSDatatype dataType = dataTypeForXsdAttribute(xsdAttribute);
 279   
 280  265 if (dataType != null) {
 281    // register the XSDatatype for the given Attribute
 282    // #### should both these be done?
 283    // elementFactory.setChildElementXSDatatype( qname, dataType );
 284  265 elementFactory.setAttributeXSDatatype(qname, dataType);
 285    }
 286    }
 287   
 288    // handle sequence definition
 289  109 Element schemaSequence = schemaComplexType.element(XSD_SEQUENCE);
 290   
 291  109 if (schemaSequence != null) {
 292  49 onChildElements(schemaSequence, elementFactory);
 293    }
 294   
 295    // handle choice definition
 296  109 Element schemaChoice = schemaComplexType.element(XSD_CHOICE);
 297   
 298  109 if (schemaChoice != null) {
 299  0 onChildElements(schemaChoice, elementFactory);
 300    }
 301   
 302    // handle all definition
 303  109 Element schemaAll = schemaComplexType.element(XSD_ALL);
 304   
 305  109 if (schemaAll != null) {
 306  19 onChildElements(schemaAll, elementFactory);
 307    }
 308    }
 309   
 310  68 private void onChildElements(Element element, DatatypeElementFactory fact) {
 311  68 Iterator iter = element.elementIterator(XSD_ELEMENT);
 312   
 313  68 while (iter.hasNext()) {
 314  226 Element xsdElement = (Element) iter.next();
 315  226 onDatatypeElement(xsdElement, fact);
 316    }
 317    }
 318   
 319    /**
 320    * processes an XML Schema &lt;attribute&gt; tag
 321    *
 322    * @param xsdElement
 323    * DOCUMENT ME!
 324    * @param elementFactory
 325    * DOCUMENT ME!
 326    * @param xsdAttribute
 327    * DOCUMENT ME!
 328    */
 329  0 private void onDatatypeAttribute(Element xsdElement,
 330    DatatypeElementFactory elementFactory, Element xsdAttribute) {
 331  0 String name = xsdAttribute.attributeValue("name");
 332  0 QName qname = getQName(name);
 333  0 XSDatatype dataType = dataTypeForXsdAttribute(xsdAttribute);
 334   
 335  0 if (dataType != null) {
 336    // register the XSDatatype for the given Attribute
 337  0 elementFactory.setAttributeXSDatatype(qname, dataType);
 338    } else {
 339  0 String type = xsdAttribute.attributeValue("type");
 340  0 System.out.println("Warning: Couldn't find XSDatatype for type: "
 341    + type + " attribute: " + name);
 342    }
 343    }
 344   
 345    /**
 346    * processes an XML Schema &lt;attribute&gt; tag
 347    *
 348    * @param xsdAttribute
 349    * DOCUMENT ME!
 350    *
 351    * @return DOCUMENT ME!
 352    *
 353    * @throws InvalidSchemaException
 354    * DOCUMENT ME!
 355    */
 356  265 private XSDatatype dataTypeForXsdAttribute(Element xsdAttribute) {
 357  265 String type = xsdAttribute.attributeValue("type");
 358  265 XSDatatype dataType = null;
 359   
 360  265 if (type != null) {
 361  209 dataType = getTypeByName(type);
 362    } else {
 363    // must parse the <simpleType> element
 364  56 Element xsdSimpleType = xsdAttribute.element(XSD_SIMPLETYPE);
 365   
 366  56 if (xsdSimpleType == null) {
 367  0 String name = xsdAttribute.attributeValue("name");
 368  0 String msg = "The attribute: " + name
 369    + " has no type attribute and does not contain a "
 370    + "<simpleType/> element";
 371  0 throw new InvalidSchemaException(msg);
 372    }
 373   
 374  56 dataType = loadXSDatatypeFromSimpleType(xsdSimpleType);
 375    }
 376   
 377  265 return dataType;
 378    }
 379   
 380    /**
 381    * processes an named XML Schema &lt;simpleTypegt; tag
 382    *
 383    * @param schemaSimpleType
 384    * DOCUMENT ME!
 385    */
 386  1 private void onNamedSchemaSimpleType(Element schemaSimpleType) {
 387  1 Attribute nameAttr = schemaSimpleType.attribute("name");
 388   
 389  1 if (nameAttr == null) {
 390  0 return;
 391    }
 392   
 393  1 String name = nameAttr.getText();
 394  1 QName qname = getQName(name);
 395  1 XSDatatype datatype = loadXSDatatypeFromSimpleType(schemaSimpleType);
 396  1 namedTypeResolver.registerSimpleType(qname, datatype);
 397    }
 398   
 399    /**
 400    * Loads a XSDatatype object from a &lt;simpleType&gt; attribute schema
 401    * element
 402    *
 403    * @param xsdSimpleType
 404    * DOCUMENT ME!
 405    *
 406    * @return DOCUMENT ME!
 407    */
 408  57 private XSDatatype loadXSDatatypeFromSimpleType(Element xsdSimpleType) {
 409  57 Element xsdRestriction = xsdSimpleType.element(XSD_RESTRICTION);
 410   
 411  57 if (xsdRestriction != null) {
 412  57 String base = xsdRestriction.attributeValue("base");
 413   
 414  57 if (base != null) {
 415  57 XSDatatype baseType = getTypeByName(base);
 416   
 417  57 if (baseType == null) {
 418  0 onSchemaError("Invalid base type: " + base
 419    + " when trying to build restriction: "
 420    + xsdRestriction);
 421    } else {
 422  57 return deriveSimpleType(baseType, xsdRestriction);
 423    }
 424    } else {
 425    // simpleType and base are mutually exclusive and you
 426    // must have one within a <restriction> tag
 427  0 Element xsdSubType = xsdSimpleType.element(XSD_SIMPLETYPE);
 428   
 429  0 if (xsdSubType == null) {
 430  0 String msg = "The simpleType element: " + xsdSimpleType
 431    + " must contain a base attribute or simpleType"
 432    + " element";
 433  0 onSchemaError(msg);
 434    } else {
 435  0 return loadXSDatatypeFromSimpleType(xsdSubType);
 436    }
 437    }
 438    } else {
 439  0 onSchemaError("No <restriction>. Could not create XSDatatype for"
 440    + " simpleType: " + xsdSimpleType);
 441    }
 442   
 443  0 return null;
 444    }
 445   
 446    /**
 447    * Derives a new type from a base type and a set of restrictions
 448    *
 449    * @param baseType
 450    * DOCUMENT ME!
 451    * @param xsdRestriction
 452    * DOCUMENT ME!
 453    *
 454    * @return DOCUMENT ME!
 455    */
 456  57 private XSDatatype deriveSimpleType(XSDatatype baseType,
 457    Element xsdRestriction) {
 458  57 TypeIncubator incubator = new TypeIncubator(baseType);
 459  57 ValidationContext context = null;
 460   
 461  57 try {
 462  57 for (Iterator iter = xsdRestriction.elementIterator(); iter
 463    .hasNext();) {
 464  103 Element element = (Element) iter.next();
 465  103 String name = element.getName();
 466  103 String value = element.attributeValue("value");
 467  103 boolean fixed = AttributeHelper.booleanValue(element, "fixed");
 468   
 469    // add facet
 470  103 incubator.addFacet(name, value, fixed, context);
 471    }
 472   
 473    // derive a new type by those facets
 474  57 String newTypeName = null;
 475   
 476  57 return incubator.derive("", newTypeName);
 477    } catch (DatatypeException e) {
 478  0 onSchemaError("Invalid restriction: " + e.getMessage()
 479    + " when trying to build restriction: " + xsdRestriction);
 480   
 481  0 return null;
 482    }
 483    }
 484   
 485    /**
 486    * DOCUMENT ME!
 487    *
 488    * @param name
 489    * The name of the element
 490    *
 491    * @return the <code>DatatypeElementFactory</code> for the given element
 492    * QName, creating one if it does not already exist
 493    */
 494  408 private DatatypeElementFactory getDatatypeElementFactory(QName name) {
 495  408 DatatypeElementFactory factory = documentFactory
 496    .getElementFactory(name);
 497   
 498  408 if (factory == null) {
 499  403 factory = new DatatypeElementFactory(name);
 500  403 name.setDocumentFactory(factory);
 501    }
 502   
 503  408 return factory;
 504    }
 505   
 506  412 private XSDatatype getTypeByName(String type) {
 507  412 XSDatatype dataType = (XSDatatype) dataTypeCache.get(type);
 508   
 509  412 if (dataType == null) {
 510    // first check to see if it is a built-in type
 511    // maybe a prefix is being used
 512  190 int idx = type.indexOf(':');
 513   
 514  190 if (idx >= 0) {
 515  50 String localName = type.substring(idx + 1);
 516   
 517  50 try {
 518  50 dataType = DatatypeFactory.getTypeByName(localName);
 519    } catch (DatatypeException e) {
 520    }
 521    }
 522   
 523  190 if (dataType == null) {
 524  140 try {
 525  140 dataType = DatatypeFactory.getTypeByName(type);
 526    } catch (DatatypeException e) {
 527    }
 528    }
 529   
 530  190 if (dataType == null) {
 531    // it's no built-in type, maybe it's a type we defined ourself
 532  3 QName typeQName = getQName(type);
 533  3 dataType = (XSDatatype) namedTypeResolver.simpleTypeMap
 534    .get(typeQName);
 535    }
 536   
 537  190 if (dataType != null) {
 538    // store in cache for later
 539  187 dataTypeCache.put(type, dataType);
 540    }
 541    }
 542   
 543  412 return dataType;
 544    }
 545   
 546  680 private QName getQName(String name) {
 547  680 if (targetNamespace == null) {
 548  596 return documentFactory.createQName(name);
 549    } else {
 550  84 return documentFactory.createQName(name, targetNamespace);
 551    }
 552    }
 553   
 554    /**
 555    * Called when there is a problem with the schema and the builder cannot
 556    * handle the XML Schema Data Types correctly
 557    *
 558    * @param message
 559    * DOCUMENT ME!
 560    *
 561    * @throws InvalidSchemaException
 562    * DOCUMENT ME!
 563    */
 564  0 private void onSchemaError(String message) {
 565    // Some users may wish to disable exception throwing
 566    // and instead use some kind of listener for errors and continue
 567    // System.out.println( "WARNING: " + message );
 568  0 throw new InvalidSchemaException(message);
 569    }
 570    }
 571   
 572    /*
 573    * Redistribution and use of this software and associated documentation
 574    * ("Software"), with or without modification, are permitted provided that the
 575    * following conditions are met:
 576    *
 577    * 1. Redistributions of source code must retain copyright statements and
 578    * notices. Redistributions must also contain a copy of this document.
 579    *
 580    * 2. Redistributions in binary form must reproduce the above copyright notice,
 581    * this list of conditions and the following disclaimer in the documentation
 582    * and/or other materials provided with the distribution.
 583    *
 584    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 585    * from this Software without prior written permission of MetaStuff, Ltd. For
 586    * written permission, please contact dom4j-info@metastuff.com.
 587    *
 588    * 4. Products derived from this Software may not be called "DOM4J" nor may
 589    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 590    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 591    *
 592    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 593    *
 594    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 595    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 596    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 597    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 598    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 599    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 600    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 601    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 602    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 603    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 604    * POSSIBILITY OF SUCH DAMAGE.
 605    *
 606    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 607    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/datatype/DatatypeElement.html0000644000175000017500000016221110242117762023705 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 207   Methods: 16
NCLOC: 95   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DatatypeElement.java 40% 60,5% 50% 54,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.datatype;
 9   
 10    import com.sun.msv.datatype.DatabindableDatatype;
 11    import com.sun.msv.datatype.SerializationContext;
 12    import com.sun.msv.datatype.xsd.XSDatatype;
 13   
 14    import org.dom4j.Element;
 15    import org.dom4j.Namespace;
 16    import org.dom4j.Node;
 17    import org.dom4j.QName;
 18    import org.dom4j.tree.DefaultElement;
 19   
 20    import org.relaxng.datatype.DatatypeException;
 21    import org.relaxng.datatype.ValidationContext;
 22   
 23    /**
 24    * <p>
 25    * <code>DatatypeElement</code> represents an Element which supports the <a
 26    * href="http://www.w3.org/TR/xmlschema-2/">XML Schema Data Types </a>
 27    * specification.
 28    * </p>
 29    *
 30    * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
 31    * @version $Revision: 1.9 $
 32    */
 33    public class DatatypeElement extends DefaultElement implements
 34    SerializationContext, ValidationContext {
 35    /** The <code>XSDatatype</code> of the <code>Attribute</code> */
 36    private XSDatatype datatype;
 37   
 38    /** The data (Object) value of the <code>Attribute</code> */
 39    private Object data;
 40   
 41  1305 public DatatypeElement(QName qname, XSDatatype datatype) {
 42  1305 super(qname);
 43  1305 this.datatype = datatype;
 44    }
 45   
 46  0 public DatatypeElement(QName qname, int attributeCount, XSDatatype type) {
 47  0 super(qname, attributeCount);
 48  0 this.datatype = type;
 49    }
 50   
 51  1 public String toString() {
 52  1 return getClass().getName() + hashCode() + " [Element: <"
 53    + getQualifiedName() + " attributes: " + attributeList()
 54    + " data: " + getData() + " />]";
 55    }
 56   
 57    /**
 58    * Returns the MSV XSDatatype for this node
 59    *
 60    * @return DOCUMENT ME!
 61    */
 62  0 public XSDatatype getXSDatatype() {
 63  0 return datatype;
 64    }
 65   
 66    // SerializationContext interface
 67    // -------------------------------------------------------------------------
 68  0 public String getNamespacePrefix(String uri) {
 69  0 Namespace namespace = getNamespaceForURI(uri);
 70   
 71  0 return (namespace != null) ? namespace.getPrefix() : null;
 72    }
 73   
 74    // ValidationContext interface
 75    // -------------------------------------------------------------------------
 76  0 public String getBaseUri() {
 77    // XXXX: could we use a Document for this?
 78  0 return null;
 79    }
 80   
 81  0 public boolean isNotation(String notationName) {
 82    // XXXX: no way to do this yet in dom4j so assume false
 83  0 return false;
 84    }
 85   
 86  0 public boolean isUnparsedEntity(String entityName) {
 87    // XXXX: no way to do this yet in dom4j so assume valid
 88  0 return true;
 89    }
 90   
 91  0 public String resolveNamespacePrefix(String prefix) {
 92  0 Namespace namespace = getNamespaceForPrefix(prefix);
 93   
 94  0 if (namespace != null) {
 95  0 return namespace.getURI();
 96    }
 97   
 98  0 return null;
 99    }
 100   
 101    // Element interface
 102    // -------------------------------------------------------------------------
 103  75 public Object getData() {
 104  75 if (data == null) {
 105  75 String text = getTextTrim();
 106   
 107  75 if ((text != null) && (text.length() > 0)) {
 108  74 if (datatype instanceof DatabindableDatatype) {
 109  74 DatabindableDatatype bind = (DatabindableDatatype) datatype;
 110  74 data = bind.createJavaObject(text, this);
 111    } else {
 112  0 data = datatype.createValue(text, this);
 113    }
 114    }
 115    }
 116   
 117  75 return data;
 118    }
 119   
 120  2 public void setData(Object data) {
 121  2 String s = datatype.convertToLexicalValue(data, this);
 122  2 validate(s);
 123  2 this.data = data;
 124  2 setText(s);
 125    }
 126   
 127  1307 public Element addText(String text) {
 128  1307 validate(text);
 129   
 130  1307 return super.addText(text);
 131    }
 132   
 133  4 public void setText(String text) {
 134  4 validate(text);
 135  3 super.setText(text);
 136    }
 137   
 138    // Implementation methods
 139    // -------------------------------------------------------------------------
 140   
 141    /**
 142    * Override to force lazy recreation of data object
 143    *
 144    * @param node
 145    * DOCUMENT ME!
 146    */
 147  1307 protected void childAdded(Node node) {
 148  1307 data = null;
 149  1307 super.childAdded(node);
 150    }
 151   
 152    /**
 153    * Override to force lazy recreation of data object
 154    *
 155    * @param node
 156    * DOCUMENT ME!
 157    */
 158  0 protected void childRemoved(Node node) {
 159  0 data = null;
 160  0 super.childRemoved(node);
 161    }
 162   
 163  1313 protected void validate(String text) throws IllegalArgumentException {
 164  1313 try {
 165  1313 datatype.checkValid(text, this);
 166    } catch (DatatypeException e) {
 167  1 throw new IllegalArgumentException(e.getMessage());
 168    }
 169    }
 170    }
 171   
 172    /*
 173    * Redistribution and use of this software and associated documentation
 174    * ("Software"), with or without modification, are permitted provided that the
 175    * following conditions are met:
 176    *
 177    * 1. Redistributions of source code must retain copyright statements and
 178    * notices. Redistributions must also contain a copy of this document.
 179    *
 180    * 2. Redistributions in binary form must reproduce the above copyright notice,
 181    * this list of conditions and the following disclaimer in the documentation
 182    * and/or other materials provided with the distribution.
 183    *
 184    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 185    * from this Software without prior written permission of MetaStuff, Ltd. For
 186    * written permission, please contact dom4j-info@metastuff.com.
 187    *
 188    * 4. Products derived from this Software may not be called "DOM4J" nor may
 189    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 190    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 191    *
 192    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 193    *
 194    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 195    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 196    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 197    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 198    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 199    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 200    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 201    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 202    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 203    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 204    * POSSIBILITY OF SUCH DAMAGE.
 205    *
 206    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 207    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/datatype/DatatypeAttribute.html0000644000175000017500000017603010242117664024264 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 229   Methods: 20
NCLOC: 117   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DatatypeAttribute.java 8,3% 41,3% 50% 38,5%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.datatype;
 9   
 10    import com.sun.msv.datatype.DatabindableDatatype;
 11    import com.sun.msv.datatype.SerializationContext;
 12    import com.sun.msv.datatype.xsd.XSDatatype;
 13   
 14    import org.dom4j.Element;
 15    import org.dom4j.Namespace;
 16    import org.dom4j.QName;
 17    import org.dom4j.tree.AbstractAttribute;
 18   
 19    import org.relaxng.datatype.DatatypeException;
 20    import org.relaxng.datatype.ValidationContext;
 21   
 22    /**
 23    * <p>
 24    * <code>DatatypeAttribute</code> represents an Attribute which supports the
 25    * <a href="http://www.w3.org/TR/xmlschema-2/">XML Schema Data Types </a>
 26    * specification.
 27    * </p>
 28    *
 29    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 30    * @version $Revision: 1.9 $
 31    */
 32    public class DatatypeAttribute extends AbstractAttribute implements
 33    SerializationContext, ValidationContext {
 34    /** The parent <code>Element</code> of the <code>Attribute</code> */
 35    private Element parent;
 36   
 37    /** The <code>QName</code> for this element */
 38    private QName qname;
 39   
 40    /** The <code>XSDatatype</code> of the <code>Attribute</code> */
 41    private XSDatatype datatype;
 42   
 43    /** The data (Object) value of the <code>Attribute</code> */
 44    private Object data;
 45   
 46    /** The text value of the <code>Attribute</code> */
 47    private String text;
 48   
 49  0 public DatatypeAttribute(QName qname, XSDatatype datatype) {
 50  0 this.qname = qname;
 51  0 this.datatype = datatype;
 52    }
 53   
 54  645 public DatatypeAttribute(QName qname, XSDatatype datatype, String text) {
 55  645 this.qname = qname;
 56  645 this.datatype = datatype;
 57  645 this.text = text;
 58  645 this.data = convertToValue(text);
 59    }
 60   
 61  2 public String toString() {
 62  2 return getClass().getName() + hashCode() + " [Attribute: name "
 63    + getQualifiedName() + " value \"" + getValue() + "\" data: "
 64    + getData() + "]";
 65    }
 66   
 67    /**
 68    * Returns the MSV XSDatatype for this node
 69    *
 70    * @return DOCUMENT ME!
 71    */
 72  0 public XSDatatype getXSDatatype() {
 73  0 return datatype;
 74    }
 75   
 76    // SerializationContext interface
 77    // -------------------------------------------------------------------------
 78  0 public String getNamespacePrefix(String uri) {
 79  0 Element parentElement = getParent();
 80   
 81  0 if (parentElement != null) {
 82  0 Namespace namespace = parentElement.getNamespaceForURI(uri);
 83   
 84  0 if (namespace != null) {
 85  0 return namespace.getPrefix();
 86    }
 87    }
 88   
 89  0 return null;
 90    }
 91   
 92    // ValidationContext interface
 93    // -------------------------------------------------------------------------
 94  0 public String getBaseUri() {
 95    // XXXX: could we use a Document for this?
 96  0 return null;
 97    }
 98   
 99  0 public boolean isNotation(String notationName) {
 100    // XXXX: no way to do this yet in dom4j so assume false
 101  0 return false;
 102    }
 103   
 104  0 public boolean isUnparsedEntity(String entityName) {
 105    // XXXX: no way to do this yet in dom4j so assume valid
 106  0 return true;
 107    }
 108   
 109  0 public String resolveNamespacePrefix(String prefix) {
 110    // first lets see if this is our attribute's prefix
 111  0 if (prefix.equals(getNamespacePrefix())) {
 112  0 return getNamespaceURI();
 113    } else {
 114  0 Element parentElement = getParent();
 115   
 116  0 if (parentElement != null) {
 117  0 Namespace namespace = parentElement
 118    .getNamespaceForPrefix(prefix);
 119   
 120  0 if (namespace != null) {
 121  0 return namespace.getURI();
 122    }
 123    }
 124    }
 125   
 126  0 return null;
 127    }
 128   
 129    // Attribute interface
 130    // -------------------------------------------------------------------------
 131  254 public QName getQName() {
 132  254 return qname;
 133    }
 134   
 135  139 public String getValue() {
 136  139 return text;
 137    }
 138   
 139  4 public void setValue(String value) {
 140  4 validate(value);
 141   
 142  2 this.text = value;
 143  2 this.data = convertToValue(value);
 144    }
 145   
 146  76 public Object getData() {
 147  76 return data;
 148    }
 149   
 150  0 public void setData(Object data) {
 151  0 String s = datatype.convertToLexicalValue(data, this);
 152  0 validate(s);
 153  0 this.text = s;
 154  0 this.data = data;
 155    }
 156   
 157  245 public Element getParent() {
 158  245 return parent;
 159    }
 160   
 161  645 public void setParent(Element parent) {
 162  645 this.parent = parent;
 163    }
 164   
 165  0 public boolean supportsParent() {
 166  0 return true;
 167    }
 168   
 169  0 public boolean isReadOnly() {
 170  0 return false;
 171    }
 172   
 173    // Implementation methods
 174    // -------------------------------------------------------------------------
 175  4 protected void validate(String txt) throws IllegalArgumentException {
 176  4 try {
 177  4 datatype.checkValid(txt, this);
 178    } catch (DatatypeException e) {
 179  2 throw new IllegalArgumentException(e.getMessage());
 180    }
 181    }
 182   
 183  647 protected Object convertToValue(String txt) {
 184  647 if (datatype instanceof DatabindableDatatype) {
 185  647 DatabindableDatatype bindable = (DatabindableDatatype) datatype;
 186   
 187  647 return bindable.createJavaObject(txt, this);
 188    } else {
 189  0 return datatype.createValue(txt, this);
 190    }
 191    }
 192    }
 193   
 194    /*
 195    * Redistribution and use of this software and associated documentation
 196    * ("Software"), with or without modification, are permitted provided that the
 197    * following conditions are met:
 198    *
 199    * 1. Redistributions of source code must retain copyright statements and
 200    * notices. Redistributions must also contain a copy of this document.
 201    *
 202    * 2. Redistributions in binary form must reproduce the above copyright notice,
 203    * this list of conditions and the following disclaimer in the documentation
 204    * and/or other materials provided with the distribution.
 205    *
 206    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 207    * from this Software without prior written permission of MetaStuff, Ltd. For
 208    * written permission, please contact dom4j-info@metastuff.com.
 209    *
 210    * 4. Products derived from this Software may not be called "DOM4J" nor may
 211    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 212    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 213    *
 214    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 215    *
 216    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 217    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 218    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 219    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 220    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 221    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 222    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 223    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 224    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 225    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 226    * POSSIBILITY OF SUCH DAMAGE.
 227    *
 228    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 229    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/datatype/InvalidSchemaException.html0000644000175000017500000004370310242117740025206 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 59   Methods: 1
NCLOC: 6   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
InvalidSchemaException.java - 0% 0% 0%
coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.datatype;
 9   
 10    /**
 11    * <p>
 12    * <code>InvalidSchemaException</code> is thrown when an invalid XML Schema
 13    * document is used
 14    * </p>
 15    *
 16    * @version $Revision: 1.6 $
 17    */
 18    public class InvalidSchemaException extends IllegalArgumentException {
 19  0 public InvalidSchemaException(String reason) {
 20  0 super(reason);
 21    }
 22    }
 23   
 24    /*
 25    * Redistribution and use of this software and associated documentation
 26    * ("Software"), with or without modification, are permitted provided that the
 27    * following conditions are met:
 28    *
 29    * 1. Redistributions of source code must retain copyright statements and
 30    * notices. Redistributions must also contain a copy of this document.
 31    *
 32    * 2. Redistributions in binary form must reproduce the above copyright notice,
 33    * this list of conditions and the following disclaimer in the documentation
 34    * and/or other materials provided with the distribution.
 35    *
 36    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 37    * from this Software without prior written permission of MetaStuff, Ltd. For
 38    * written permission, please contact dom4j-info@metastuff.com.
 39    *
 40    * 4. Products derived from this Software may not be called "DOM4J" nor may
 41    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 42    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 43    *
 44    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 45    *
 46    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 47    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 48    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 49    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 50    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 51    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 52    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 53    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 54    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 55    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 56    * POSSIBILITY OF SUCH DAMAGE.
 57    *
 58    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 59    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/datatype/pkg-summary.html0000644000175000017500000002327010242117722023071 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
package stats: LOC: 1.629   Methods: 79
NCLOC: 763   Classes: 7
Files: 7  
 
 Package Conditionals Statements Methods TOTAL
org.dom4j.datatype 58,3% 65,7% 69,6% 64,5%
coverage coverage
 
 Classes Conditionals Statements Methods TOTAL
InvalidSchemaException - 0% 0% 0%
coverage
DatatypeAttribute 8,3% 41,3% 50% 38,5%
coverage coverage
DatatypeDocumentFactory 45% 45,8% 87,5% 50%
coverage coverage
DatatypeElement 40% 60,5% 50% 54,7%
coverage coverage
SchemaParser 67,6% 71,6% 83,3% 71,3%
coverage coverage
DatatypeElementFactory 87,5% 95% 87,5% 91,7%
coverage coverage
NamedTypeResolver 75% 100% 100% 94,7%
coverage coverage
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/datatype/DatatypeDocumentFactory.html0000644000175000017500000017474010242117677025441 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 223   Methods: 8
NCLOC: 107   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DatatypeDocumentFactory.java 45% 45,8% 87,5% 50%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.datatype;
 9   
 10    import org.dom4j.Attribute;
 11    import org.dom4j.Document;
 12    import org.dom4j.DocumentFactory;
 13    import org.dom4j.Element;
 14    import org.dom4j.Namespace;
 15    import org.dom4j.QName;
 16    import org.dom4j.io.SAXReader;
 17   
 18    import org.xml.sax.EntityResolver;
 19    import org.xml.sax.InputSource;
 20   
 21    /**
 22    * <p>
 23    * <code>DatatypeDocumentFactory</code> is a factory of XML objects which
 24    * support the <a href="http://www.w3.org/TR/xmlschema-2/">XML Schema Data Types
 25    * </a> specification.
 26    * </p>
 27    *
 28    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 29    * @version $Revision: 1.9 $
 30    */
 31    public class DatatypeDocumentFactory extends DocumentFactory {
 32    // XXXX: I don't think interning of QNames is necessary
 33    private static final boolean DO_INTERN_QNAME = false;
 34   
 35    /** The Singleton instance */
 36    protected static transient DatatypeDocumentFactory singleton
 37    = new DatatypeDocumentFactory();
 38   
 39    private static final Namespace XSI_NAMESPACE = Namespace.get("xsi",
 40    "http://www.w3.org/2001/XMLSchema-instance");
 41   
 42    private static final QName XSI_SCHEMA_LOCATION = QName.get(
 43    "schemaLocation", XSI_NAMESPACE);
 44   
 45    private static final QName XSI_NO_SCHEMA_LOCATION = QName.get(
 46    "noNamespaceSchemaLocation", XSI_NAMESPACE);
 47   
 48    /** The builder of XML Schemas */
 49    private SchemaParser schemaBuilder;
 50   
 51    /** reader of XML Schemas */
 52    private SAXReader xmlSchemaReader = new SAXReader();
 53   
 54    /** If schemas are automatically loaded when parsing instance documents */
 55    private boolean autoLoadSchema = true;
 56   
 57  27 public DatatypeDocumentFactory() {
 58  27 schemaBuilder = new SchemaParser(this);
 59    }
 60   
 61    /**
 62    * <p>
 63    * Access to the singleton instance of this factory.
 64    * </p>
 65    *
 66    * @return the default singleon instance
 67    */
 68  33 public static DocumentFactory getInstance() {
 69  33 return singleton;
 70    }
 71   
 72    /**
 73    * Loads the given XML Schema document into this factory so schema-aware
 74    * Document, Elements and Attributes will be created by this factory.
 75    *
 76    * @param schemaDocument
 77    * is an XML Schema Document instance.
 78    */
 79  22 public void loadSchema(Document schemaDocument) {
 80  22 schemaBuilder.build(schemaDocument);
 81    }
 82   
 83  3 public void loadSchema(Document schemaDocument, Namespace targetNamespace) {
 84  3 schemaBuilder.build(schemaDocument, targetNamespace);
 85    }
 86   
 87    /**
 88    * Registers the given <code>DatatypeElementFactory</code> for the given
 89    * &lt;element&gt; schema element
 90    *
 91    * @param elementQName
 92    * DOCUMENT ME!
 93    *
 94    * @return DOCUMENT ME!
 95    */
 96  408 public DatatypeElementFactory getElementFactory(QName elementQName) {
 97  408 DatatypeElementFactory result = null;
 98   
 99  408 if (DO_INTERN_QNAME) {
 100  0 elementQName = intern(elementQName);
 101    }
 102   
 103  408 DocumentFactory factory = elementQName.getDocumentFactory();
 104  408 if (factory instanceof DatatypeElementFactory) {
 105  5 result = (DatatypeElementFactory) factory;
 106    }
 107   
 108  408 return result;
 109    }
 110   
 111    // DocumentFactory methods
 112    // -------------------------------------------------------------------------
 113  450 public Attribute createAttribute(Element owner, QName qname, String value) {
 114  450 if (autoLoadSchema && qname.equals(XSI_NO_SCHEMA_LOCATION)) {
 115  2 Document document = (owner != null) ? owner.getDocument() : null;
 116  2 loadSchema(document, value);
 117  448 } else if (autoLoadSchema && qname.equals(XSI_SCHEMA_LOCATION)) {
 118  0 Document document = (owner != null) ? owner.getDocument() : null;
 119  0 String uri = value.substring(0, value.indexOf(' '));
 120  0 Namespace namespace = owner.getNamespaceForURI(uri);
 121  0 loadSchema(document, value.substring(value.indexOf(' ') + 1),
 122    namespace);
 123    }
 124   
 125  450 return super.createAttribute(owner, qname, value);
 126    }
 127   
 128    // Implementation methods
 129    // -------------------------------------------------------------------------
 130  2 protected void loadSchema(Document document, String schemaInstanceURI) {
 131  2 try {
 132  2 EntityResolver resolver = document.getEntityResolver();
 133   
 134  2 if (resolver == null) {
 135  0 String msg = "No EntityResolver available for resolving URI: ";
 136  0 throw new InvalidSchemaException(msg + schemaInstanceURI);
 137    }
 138   
 139  2 InputSource inputSource = resolver.resolveEntity(null,
 140    schemaInstanceURI);
 141   
 142  2 if (resolver == null) {
 143  0 throw new InvalidSchemaException("Could not resolve the URI: "
 144    + schemaInstanceURI);
 145    }
 146   
 147  2 Document schemaDocument = xmlSchemaReader.read(inputSource);
 148  2 loadSchema(schemaDocument);
 149    } catch (Exception e) {
 150  0 System.out.println("Failed to load schema: " + schemaInstanceURI);
 151  0 System.out.println("Caught: " + e);
 152  0 e.printStackTrace();
 153  0 throw new InvalidSchemaException("Failed to load schema: "
 154    + schemaInstanceURI);
 155    }
 156    }
 157   
 158  0 protected void loadSchema(Document document, String schemaInstanceURI,
 159    Namespace namespace) {
 160  0 try {
 161  0 EntityResolver resolver = document.getEntityResolver();
 162   
 163  0 if (resolver == null) {
 164  0 String msg = "No EntityResolver available for resolving URI: ";
 165  0 throw new InvalidSchemaException(msg + schemaInstanceURI);
 166    }
 167   
 168  0 InputSource inputSource = resolver.resolveEntity(null,
 169    schemaInstanceURI);
 170   
 171  0 if (resolver == null) {
 172  0 throw new InvalidSchemaException("Could not resolve the URI: "
 173    + schemaInstanceURI);
 174    }
 175   
 176  0 Document schemaDocument = xmlSchemaReader.read(inputSource);
 177  0 loadSchema(schemaDocument, namespace);
 178    } catch (Exception e) {
 179  0 System.out.println("Failed to load schema: " + schemaInstanceURI);
 180  0 System.out.println("Caught: " + e);
 181  0 e.printStackTrace();
 182  0 throw new InvalidSchemaException("Failed to load schema: "
 183    + schemaInstanceURI);
 184    }
 185    }
 186    }
 187   
 188    /*
 189    * Redistribution and use of this software and associated documentation
 190    * ("Software"), with or without modification, are permitted provided that the
 191    * following conditions are met:
 192    *
 193    * 1. Redistributions of source code must retain copyright statements and
 194    * notices. Redistributions must also contain a copy of this document.
 195    *
 196    * 2. Redistributions in binary form must reproduce the above copyright notice,
 197    * this list of conditions and the following disclaimer in the documentation
 198    * and/or other materials provided with the distribution.
 199    *
 200    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 201    * from this Software without prior written permission of MetaStuff, Ltd. For
 202    * written permission, please contact dom4j-info@metastuff.com.
 203    *
 204    * 4. Products derived from this Software may not be called "DOM4J" nor may
 205    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 206    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 207    *
 208    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 209    *
 210    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 211    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 212    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 213    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 214    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 215    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 216    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 217    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 218    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 219    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 220    * POSSIBILITY OF SUCH DAMAGE.
 221    *
 222    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 223    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/datatype/DatatypeElementFactory.html0000644000175000017500000013530110242117576025240 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 172   Methods: 8
NCLOC: 54   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DatatypeElementFactory.java 87,5% 95% 87,5% 91,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.datatype;
 9   
 10    import com.sun.msv.datatype.xsd.XSDatatype;
 11   
 12    import java.util.HashMap;
 13    import java.util.Map;
 14   
 15    import org.dom4j.Attribute;
 16    import org.dom4j.DocumentFactory;
 17    import org.dom4j.Element;
 18    import org.dom4j.QName;
 19   
 20    /**
 21    * <p>
 22    * <code>DatatypeElementFactory</code> is a factory for a specific Element in
 23    * an XML Schema.
 24    * </p>
 25    *
 26    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 27    * @author Yuxin Ruan
 28    * @version $Revision: 1.9 $
 29    */
 30    public class DatatypeElementFactory extends DocumentFactory {
 31    private QName elementQName;
 32   
 33    /**
 34    * Cache of <code>XSDatatype</code> instances per Attribute
 35    * <code>QName</code>
 36    */
 37    private Map attributeXSDatatypes = new HashMap();
 38   
 39    /**
 40    * Cache of <code>XSDatatype</code> instances per child Element
 41    * <code>QName</code>
 42    */
 43    private Map childrenXSDatatypes = new HashMap();
 44   
 45  403 public DatatypeElementFactory(QName elementQName) {
 46  403 this.elementQName = elementQName;
 47    }
 48   
 49    /**
 50    * DOCUMENT ME!
 51    *
 52    * @return the QName this element factory is associated with
 53    */
 54  0 public QName getQName() {
 55  0 return elementQName;
 56    }
 57   
 58    /**
 59    * DOCUMENT ME!
 60    *
 61    * @param attributeQName
 62    * DOCUMENT ME!
 63    *
 64    * @return the <code>XSDatatype</code> associated with the given Attribute
 65    * QName
 66    */
 67  686 public XSDatatype getAttributeXSDatatype(QName attributeQName) {
 68  686 return (XSDatatype) attributeXSDatatypes.get(attributeQName);
 69    }
 70   
 71    /**
 72    * Registers the given <code>XSDatatype</code> for the given
 73    * &lt;attribute&gt; QNames
 74    *
 75    * @param attributeQName
 76    * DOCUMENT ME!
 77    * @param type
 78    * DOCUMENT ME!
 79    */
 80  265 public void setAttributeXSDatatype(QName attributeQName, XSDatatype type) {
 81  265 attributeXSDatatypes.put(attributeQName, type);
 82    }
 83   
 84    /**
 85    * DOCUMENT ME!
 86    *
 87    * @param qname
 88    * DOCUMENT ME!
 89    *
 90    * @return the <code>XSDatatype</code> associated with the given child
 91    * Element QName
 92    */
 93  3311 public XSDatatype getChildElementXSDatatype(QName qname) {
 94  3311 return (XSDatatype) childrenXSDatatypes.get(qname);
 95    }
 96   
 97  144 public void setChildElementXSDatatype(QName qname, XSDatatype dataType) {
 98  144 childrenXSDatatypes.put(qname, dataType);
 99    }
 100   
 101    // DocumentFactory methods
 102    // -------------------------------------------------------------------------
 103  1656 public Element createElement(QName qname) {
 104    // the element may have its own element factory!
 105    // use factory from the qname for datatype
 106  1656 XSDatatype dataType = getChildElementXSDatatype(qname);
 107   
 108  1656 if (dataType != null) {
 109  1 return new DatatypeElement(qname, dataType);
 110    }
 111   
 112  1655 DocumentFactory factory = qname.getDocumentFactory();
 113   
 114  1655 if (factory instanceof DatatypeElementFactory) {
 115  1655 DatatypeElementFactory dtFactory = (DatatypeElementFactory) factory;
 116  1655 dataType = dtFactory.getChildElementXSDatatype(qname);
 117   
 118  1655 if (dataType != null) {
 119  1304 return new DatatypeElement(qname, dataType);
 120    }
 121    }
 122   
 123  351 return super.createElement(qname);
 124    }
 125   
 126  686 public Attribute createAttribute(Element owner, QName qname, String value) {
 127  686 XSDatatype dataType = getAttributeXSDatatype(qname);
 128   
 129  686 if (dataType == null) {
 130  41 return super.createAttribute(owner, qname, value);
 131    } else {
 132  645 return new DatatypeAttribute(qname, dataType, value);
 133    }
 134    }
 135    }
 136   
 137    /*
 138    * Redistribution and use of this software and associated documentation
 139    * ("Software"), with or without modification, are permitted provided that the
 140    * following conditions are met:
 141    *
 142    * 1. Redistributions of source code must retain copyright statements and
 143    * notices. Redistributions must also contain a copy of this document.
 144    *
 145    * 2. Redistributions in binary form must reproduce the above copyright notice,
 146    * this list of conditions and the following disclaimer in the documentation
 147    * and/or other materials provided with the distribution.
 148    *
 149    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 150    * from this Software without prior written permission of MetaStuff, Ltd. For
 151    * written permission, please contact dom4j-info@metastuff.com.
 152    *
 153    * 4. Products derived from this Software may not be called "DOM4J" nor may
 154    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 155    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 156    *
 157    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 158    *
 159    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 160    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 161    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 162    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 163    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 164    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 165    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 166    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 167    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 168    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 169    * POSSIBILITY OF SUCH DAMAGE.
 170    *
 171    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 172    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/datatype/NamedTypeResolver.html0000644000175000017500000011150210242117720024217 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 132   Methods: 8
NCLOC: 60   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
NamedTypeResolver.java 75% 100% 100% 94,7%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.datatype;
 9   
 10    import com.sun.msv.datatype.xsd.XSDatatype;
 11   
 12    import java.util.HashMap;
 13    import java.util.Iterator;
 14    import java.util.Map;
 15   
 16    import org.dom4j.DocumentFactory;
 17    import org.dom4j.Element;
 18    import org.dom4j.QName;
 19   
 20    /**
 21    * <p>
 22    * <code>NamedTypeResolver</code> resolves named types for a given QName.
 23    * </p>
 24    *
 25    * @author Yuxin Ruan
 26    * @version $Revision: 1.8 $
 27    */
 28    class NamedTypeResolver {
 29    protected Map complexTypeMap = new HashMap();
 30   
 31    protected Map simpleTypeMap = new HashMap();
 32   
 33    protected Map typedElementMap = new HashMap();
 34   
 35    protected Map elementFactoryMap = new HashMap();
 36   
 37    protected DocumentFactory documentFactory;
 38   
 39  27 NamedTypeResolver(DocumentFactory documentFactory) {
 40  27 this.documentFactory = documentFactory;
 41    }
 42   
 43  2 void registerComplexType(QName type, DocumentFactory factory) {
 44  2 complexTypeMap.put(type, factory);
 45    }
 46   
 47  1 void registerSimpleType(QName type, XSDatatype datatype) {
 48  1 simpleTypeMap.put(type, datatype);
 49    }
 50   
 51  3 void registerTypedElement(Element element, QName type,
 52    DocumentFactory parentFactory) {
 53  3 typedElementMap.put(element, type);
 54  3 elementFactoryMap.put(element, parentFactory);
 55    }
 56   
 57  25 void resolveElementTypes() {
 58  25 Iterator iterator = typedElementMap.keySet().iterator();
 59   
 60  25 while (iterator.hasNext()) {
 61  3 Element element = (Element) iterator.next();
 62  3 QName elementQName = getQNameOfSchemaElement(element);
 63  3 QName type = (QName) typedElementMap.get(element);
 64   
 65  3 if (complexTypeMap.containsKey(type)) {
 66  2 DocumentFactory factory = (DocumentFactory) complexTypeMap
 67    .get(type);
 68  2 elementQName.setDocumentFactory(factory);
 69  1 } else if (simpleTypeMap.containsKey(type)) {
 70  1 XSDatatype datatype = (XSDatatype) simpleTypeMap.get(type);
 71  1 DocumentFactory factory = (DocumentFactory) elementFactoryMap
 72    .get(element);
 73   
 74  1 if (factory instanceof DatatypeElementFactory) {
 75  1 ((DatatypeElementFactory) factory)
 76    .setChildElementXSDatatype(elementQName, datatype);
 77    }
 78    }
 79    }
 80    }
 81   
 82  25 void resolveNamedTypes() {
 83  25 resolveElementTypes();
 84    }
 85   
 86  3 private QName getQNameOfSchemaElement(Element element) {
 87  3 String name = element.attributeValue("name");
 88   
 89  3 return getQName(name);
 90    }
 91   
 92  3 private QName getQName(String name) {
 93  3 return documentFactory.createQName(name);
 94    }
 95    }
 96   
 97    /*
 98    * Redistribution and use of this software and associated documentation
 99    * ("Software"), with or without modification, are permitted provided that the
 100    * following conditions are met:
 101    *
 102    * 1. Redistributions of source code must retain copyright statements and
 103    * notices. Redistributions must also contain a copy of this document.
 104    *
 105    * 2. Redistributions in binary form must reproduce the above copyright notice,
 106    * this list of conditions and the following disclaimer in the documentation
 107    * and/or other materials provided with the distribution.
 108    *
 109    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 110    * from this Software without prior written permission of MetaStuff, Ltd. For
 111    * written permission, please contact dom4j-info@metastuff.com.
 112    *
 113    * 4. Products derived from this Software may not be called "DOM4J" nor may
 114    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 115    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 116    *
 117    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 118    *
 119    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 120    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 121    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 122    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 123    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 124    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 125    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 126    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 127    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 128    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 129    * POSSIBILITY OF SUCH DAMAGE.
 130    *
 131    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 132    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/xpath/0000755000175000017500000000000012133227266017242 5ustar ebourgebourgdom4j-1.6.1/docs/clover/org/dom4j/xpath/DefaultNamespaceContext.html0000644000175000017500000007350010242117735024701 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 102   Methods: 3
NCLOC: 37   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DefaultNamespaceContext.java 66,7% 82,4% 100% 78,1%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.xpath;
 9   
 10    import java.io.Serializable;
 11   
 12    import org.dom4j.Document;
 13    import org.dom4j.Element;
 14    import org.dom4j.Namespace;
 15    import org.dom4j.Node;
 16   
 17    import org.jaxen.NamespaceContext;
 18   
 19    /**
 20    * <p>
 21    * <code>DefaultNamespaceContext</code> implements a Jaxen NamespaceContext
 22    * such that a context node is used to determine the current XPath namespace
 23    * prefixes and namespace URIs available.
 24    * </p>
 25    *
 26    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 27    */
 28    public class DefaultNamespaceContext implements NamespaceContext, Serializable {
 29    private final Element element;
 30   
 31  2561 public DefaultNamespaceContext(Element element) {
 32  2561 this.element = element;
 33    }
 34   
 35  2561 public static DefaultNamespaceContext create(Object node) {
 36  2561 Element element = null;
 37   
 38  2561 if (node instanceof Element) {
 39  2169 element = (Element) node;
 40  392 } else if (node instanceof Document) {
 41  392 Document doc = (Document) node;
 42  392 element = doc.getRootElement();
 43  0 } else if (node instanceof Node) {
 44  0 element = ((Node) node).getParent();
 45    }
 46   
 47  2561 if (element != null) {
 48  2561 return new DefaultNamespaceContext(element);
 49    }
 50   
 51  0 return null;
 52    }
 53   
 54  854 public String translateNamespacePrefixToUri(String prefix) {
 55  854 if ((prefix != null) && (prefix.length() > 0)) {
 56  55 Namespace ns = element.getNamespaceForPrefix(prefix);
 57   
 58  55 if (ns != null) {
 59  54 return ns.getURI();
 60    }
 61    }
 62   
 63  800 return null;
 64    }
 65    }
 66   
 67    /*
 68    * Redistribution and use of this software and associated documentation
 69    * ("Software"), with or without modification, are permitted provided that the
 70    * following conditions are met:
 71    *
 72    * 1. Redistributions of source code must retain copyright statements and
 73    * notices. Redistributions must also contain a copy of this document.
 74    *
 75    * 2. Redistributions in binary form must reproduce the above copyright notice,
 76    * this list of conditions and the following disclaimer in the documentation
 77    * and/or other materials provided with the distribution.
 78    *
 79    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 80    * from this Software without prior written permission of MetaStuff, Ltd. For
 81    * written permission, please contact dom4j-info@metastuff.com.
 82    *
 83    * 4. Products derived from this Software may not be called "DOM4J" nor may
 84    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 85    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 86    *
 87    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 88    *
 89    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 90    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 91    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 92    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 93    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 94    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 95    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 96    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 97    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 98    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 99    * POSSIBILITY OF SUCH DAMAGE.
 100    *
 101    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 102    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/xpath/pkg-classes.html0000644000175000017500000000217410242117744022346 0ustar ebourgebourg dom4j - 1.6.1 org.dom4j.xpath
Classes
DefaultNamespaceContext (78,1%)
DefaultXPath (68,6%)
XPathPattern (54,2%)
dom4j-1.6.1/docs/clover/org/dom4j/xpath/DefaultXPath.html0000644000175000017500000033612510242117725022470 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 413   Methods: 29
NCLOC: 229   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
DefaultXPath.java 61,8% 69,7% 72,4% 68,6%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.xpath;
 9   
 10    import java.io.Serializable;
 11    import java.util.Collections;
 12    import java.util.Comparator;
 13    import java.util.HashMap;
 14    import java.util.HashSet;
 15    import java.util.Iterator;
 16    import java.util.List;
 17    import java.util.Map;
 18   
 19    import org.dom4j.InvalidXPathException;
 20    import org.dom4j.Node;
 21    import org.dom4j.NodeFilter;
 22    import org.dom4j.XPathException;
 23   
 24    import org.jaxen.FunctionContext;
 25    import org.jaxen.JaxenException;
 26    import org.jaxen.NamespaceContext;
 27    import org.jaxen.SimpleNamespaceContext;
 28    import org.jaxen.VariableContext;
 29    import org.jaxen.XPath;
 30    import org.jaxen.dom4j.Dom4jXPath;
 31   
 32    /**
 33    * <p>
 34    * Default implementation of {@link org.dom4j.XPath}which uses the <a
 35    * href="http://jaxen.org">Jaxen </a> project.
 36    * </p>
 37    *
 38    * @author bob mcwhirter
 39    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 40    */
 41    public class DefaultXPath implements org.dom4j.XPath, NodeFilter, Serializable {
 42    private String text;
 43   
 44    private XPath xpath;
 45   
 46    private NamespaceContext namespaceContext;
 47   
 48    /**
 49    * Construct an XPath
 50    *
 51    * @param text
 52    * DOCUMENT ME!
 53    *
 54    * @throws InvalidXPathException
 55    * DOCUMENT ME!
 56    */
 57  592 public DefaultXPath(String text) throws InvalidXPathException {
 58  592 this.text = text;
 59  592 this.xpath = parse(text);
 60    }
 61   
 62  11 public String toString() {
 63  11 return "[XPath: " + xpath + "]";
 64    }
 65   
 66    // XPath interface
 67   
 68    /**
 69    * Retrieve the textual XPath string used to initialize this Object
 70    *
 71    * @return The XPath string
 72    */
 73  0 public String getText() {
 74  0 return text;
 75    }
 76   
 77  0 public FunctionContext getFunctionContext() {
 78  0 return xpath.getFunctionContext();
 79    }
 80   
 81  0 public void setFunctionContext(FunctionContext functionContext) {
 82  0 xpath.setFunctionContext(functionContext);
 83    }
 84   
 85  0 public NamespaceContext getNamespaceContext() {
 86  0 return namespaceContext;
 87    }
 88   
 89  4 public void setNamespaceURIs(Map map) {
 90  4 setNamespaceContext(new SimpleNamespaceContext(map));
 91    }
 92   
 93  8 public void setNamespaceContext(NamespaceContext namespaceContext) {
 94  8 this.namespaceContext = namespaceContext;
 95  8 xpath.setNamespaceContext(namespaceContext);
 96    }
 97   
 98  0 public VariableContext getVariableContext() {
 99  0 return xpath.getVariableContext();
 100    }
 101   
 102  7 public void setVariableContext(VariableContext variableContext) {
 103  7 xpath.setVariableContext(variableContext);
 104    }
 105   
 106  7 public Object evaluate(Object context) {
 107  7 try {
 108  7 setNSContext(context);
 109   
 110  7 List answer = xpath.selectNodes(context);
 111   
 112  7 if ((answer != null) && (answer.size() == 1)) {
 113  6 return answer.get(0);
 114    }
 115   
 116  1 return answer;
 117    } catch (JaxenException e) {
 118  0 handleJaxenException(e);
 119   
 120  0 return null;
 121    }
 122    }
 123   
 124  0 public Object selectObject(Object context) {
 125  0 return evaluate(context);
 126    }
 127   
 128  289 public List selectNodes(Object context) {
 129  289 try {
 130  289 setNSContext(context);
 131   
 132  289 return xpath.selectNodes(context);
 133    } catch (JaxenException e) {
 134  1 handleJaxenException(e);
 135   
 136  0 return Collections.EMPTY_LIST;
 137    }
 138    }
 139   
 140  0 public List selectNodes(Object context, org.dom4j.XPath sortXPath) {
 141  0 List answer = selectNodes(context);
 142  0 sortXPath.sort(answer);
 143   
 144  0 return answer;
 145    }
 146   
 147  2 public List selectNodes(Object context, org.dom4j.XPath sortXPath,
 148    boolean distinct) {
 149  2 List answer = selectNodes(context);
 150  2 sortXPath.sort(answer, distinct);
 151   
 152  2 return answer;
 153    }
 154   
 155  71 public Node selectSingleNode(Object context) {
 156  71 try {
 157  71 setNSContext(context);
 158   
 159  71 Object answer = xpath.selectSingleNode(context);
 160   
 161  71 if (answer instanceof Node) {
 162  71 return (Node) answer;
 163    }
 164   
 165  0 if (answer == null) {
 166  0 return null;
 167    }
 168   
 169  0 throw new XPathException("The result of the XPath expression is "
 170    + "not a Node. It was: " + answer + " of type: "
 171    + answer.getClass().getName());
 172    } catch (JaxenException e) {
 173  0 handleJaxenException(e);
 174   
 175  0 return null;
 176    }
 177    }
 178   
 179  2151 public String valueOf(Object context) {
 180  2151 try {
 181  2151 setNSContext(context);
 182   
 183  2151 return xpath.stringValueOf(context);
 184    } catch (JaxenException e) {
 185  0 handleJaxenException(e);
 186   
 187  0 return "";
 188    }
 189    }
 190   
 191  38 public Number numberValueOf(Object context) {
 192  38 try {
 193  38 setNSContext(context);
 194   
 195  38 return xpath.numberValueOf(context);
 196    } catch (JaxenException e) {
 197  0 handleJaxenException(e);
 198   
 199  0 return null;
 200    }
 201    }
 202   
 203  2 public boolean booleanValueOf(Object context) {
 204  2 try {
 205  2 setNSContext(context);
 206   
 207  2 return xpath.booleanValueOf(context);
 208    } catch (JaxenException e) {
 209  0 handleJaxenException(e);
 210   
 211  0 return false;
 212    }
 213    }
 214   
 215    /**
 216    * <p>
 217    * <code>sort</code> sorts the given List of Nodes using this XPath
 218    * expression as a {@link Comparator}.
 219    * </p>
 220    *
 221    * @param list
 222    * is the list of Nodes to sort
 223    */
 224  0 public void sort(List list) {
 225  0 sort(list, false);
 226    }
 227   
 228    /**
 229    * <p>
 230    * <code>sort</code> sorts the given List of Nodes using this XPath
 231    * expression as a {@link Comparator}and optionally removing duplicates.
 232    * </p>
 233    *
 234    * @param list
 235    * is the list of Nodes to sort
 236    * @param distinct
 237    * if true then duplicate values (using the sortXPath for
 238    * comparisions) will be removed from the List
 239    */
 240  2 public void sort(List list, boolean distinct) {
 241  2 if ((list != null) && !list.isEmpty()) {
 242  2 int size = list.size();
 243  2 HashMap sortValues = new HashMap(size);
 244   
 245  2 for (int i = 0; i < size; i++) {
 246  1958 Object object = list.get(i);
 247   
 248  1958 if (object instanceof Node) {
 249  1958 Node node = (Node) object;
 250  1958 Object expression = getCompareValue(node);
 251  1958 sortValues.put(node, expression);
 252    }
 253    }
 254   
 255  2 sort(list, sortValues);
 256   
 257  2 if (distinct) {
 258  1 removeDuplicates(list, sortValues);
 259    }
 260    }
 261    }
 262   
 263  12 public boolean matches(Node node) {
 264  12 try {
 265  12 setNSContext(node);
 266   
 267  12 List answer = xpath.selectNodes(node);
 268   
 269  12 if ((answer != null) && (answer.size() > 0)) {
 270  6 Object item = answer.get(0);
 271   
 272  6 if (item instanceof Boolean) {
 273  0 return ((Boolean) item).booleanValue();
 274    }
 275   
 276  6 return answer.contains(node);
 277    }
 278   
 279  6 return false;
 280    } catch (JaxenException e) {
 281  0 handleJaxenException(e);
 282   
 283  0 return false;
 284    }
 285    }
 286   
 287    /**
 288    * Sorts the list based on the sortValues for each node
 289    *
 290    * @param list
 291    * DOCUMENT ME!
 292    * @param sortValues
 293    * DOCUMENT ME!
 294    */
 295  2 protected void sort(List list, final Map sortValues) {
 296  2 Collections.sort(list, new Comparator() {
 297  9366 public int compare(Object o1, Object o2) {
 298  9366 o1 = sortValues.get(o1);
 299  9366 o2 = sortValues.get(o2);
 300   
 301  9366 if (o1 == o2) {
 302  978 return 0;
 303  8388 } else if (o1 instanceof Comparable) {
 304  8388 Comparable c1 = (Comparable) o1;
 305   
 306  8388 return c1.compareTo(o2);
 307  0 } else if (o1 == null) {
 308  0 return 1;
 309  0 } else if (o2 == null) {
 310  0 return -1;
 311    } else {
 312  0 return o1.equals(o2) ? 0 : (-1);
 313    }
 314    }
 315    });
 316    }
 317   
 318    // Implementation methods
 319   
 320    /**
 321    * Removes items from the list which have duplicate values
 322    *
 323    * @param list
 324    * DOCUMENT ME!
 325    * @param sortValues
 326    * DOCUMENT ME!
 327    */
 328  1 protected void removeDuplicates(List list, Map sortValues) {
 329    // remove distinct
 330  1 HashSet distinctValues = new HashSet();
 331   
 332  1 for (Iterator iter = list.iterator(); iter.hasNext();) {
 333  979 Object node = iter.next();
 334  979 Object value = sortValues.get(node);
 335   
 336  979 if (distinctValues.contains(value)) {
 337  956 iter.remove();
 338    } else {
 339  23 distinctValues.add(value);
 340    }
 341    }
 342    }
 343   
 344    /**
 345    * DOCUMENT ME!
 346    *
 347    * @param node
 348    * DOCUMENT ME!
 349    *
 350    * @return the node expression used for sorting comparisons
 351    */
 352  1958 protected Object getCompareValue(Node node) {
 353  1958 return valueOf(node);
 354    }
 355   
 356  592 protected static XPath parse(String text) {
 357  592 try {
 358  592 return new Dom4jXPath(text);
 359    } catch (JaxenException e) {
 360  4 throw new InvalidXPathException(text, e.getMessage());
 361    } catch (Throwable t) {
 362  0 throw new InvalidXPathException(text, t);
 363    }
 364    }
 365   
 366  2570 protected void setNSContext(Object context) {
 367  2570 if (namespaceContext == null) {
 368  2561 xpath.setNamespaceContext(DefaultNamespaceContext.create(context));
 369    }
 370    }
 371   
 372  1 protected void handleJaxenException(JaxenException exception)
 373    throws XPathException {
 374  1 throw new XPathException(text, exception);
 375    }
 376    }
 377   
 378    /*
 379    * Redistribution and use of this software and associated documentation
 380    * ("Software"), with or without modification, are permitted provided that the
 381    * following conditions are met:
 382    *
 383    * 1. Redistributions of source code must retain copyright statements and
 384    * notices. Redistributions must also contain a copy of this document.
 385    *
 386    * 2. Redistributions in binary form must reproduce the above copyright notice,
 387    * this list of conditions and the following disclaimer in the documentation
 388    * and/or other materials provided with the distribution.
 389    *
 390    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 391    * from this Software without prior written permission of MetaStuff, Ltd. For
 392    * written permission, please contact dom4j-info@metastuff.com.
 393    *
 394    * 4. Products derived from this Software may not be called "DOM4J" nor may
 395    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 396    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 397    *
 398    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 399    *
 400    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 401    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 402    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 403    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 404    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 405    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 406    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 407    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 408    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 409    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 410    * POSSIBILITY OF SUCH DAMAGE.
 411    *
 412    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 413    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/xpath/pkg-summary.html0000644000175000017500000001504710242117715022407 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
package stats: LOC: 680   Methods: 44
NCLOC: 353   Classes: 3
Files: 3  
 
 Package Conditionals Statements Methods TOTAL
org.dom4j.xpath 60% 67,7% 72,7% 67,1%
coverage coverage
 
 Classes Conditionals Statements Methods TOTAL
XPathPattern 25% 53,1% 66,7% 54,2%
coverage coverage
DefaultXPath 61,8% 69,7% 72,4% 68,6%
coverage coverage
DefaultNamespaceContext 66,7% 82,4% 100% 78,1%
coverage coverage
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/org/dom4j/xpath/XPathPattern.html0000644000175000017500000013430010242117721022504 0ustar ebourgebourg dom4j - 1.6.1
Clover coverage report - dom4j - 1.6.1
Coverage timestamp: ma mei 16 2005 14:23:01 GMT+01:00
Overview   Package   File
    FRAMES   NO FRAMES  
file stats: LOC: 165   Methods: 12
NCLOC: 87   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
XPathPattern.java 25% 53,1% 66,7% 54,2%
coverage coverage
 1    /*
 2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 3    *
 4    * This software is open source.
 5    * See the bottom of this file for the licence.
 6    */
 7   
 8    package org.dom4j.xpath;
 9   
 10    import java.util.ArrayList;
 11   
 12    import org.dom4j.InvalidXPathException;
 13    import org.dom4j.Node;
 14    import org.dom4j.XPathException;
 15   
 16    import org.jaxen.Context;
 17    import org.jaxen.ContextSupport;
 18    import org.jaxen.JaxenException;
 19    import org.jaxen.SimpleNamespaceContext;
 20    import org.jaxen.SimpleVariableContext;
 21    import org.jaxen.VariableContext;
 22    import org.jaxen.XPathFunctionContext;
 23    import org.jaxen.dom4j.DocumentNavigator;
 24    import org.jaxen.pattern.Pattern;
 25    import org.jaxen.pattern.PatternParser;
 26    import org.jaxen.saxpath.SAXPathException;
 27   
 28    /**
 29    * <p>
 30    * <code>XPathPattern</code> is an implementation of Pattern which uses an
 31    * XPath xpath.
 32    * </p>
 33    *
 34    * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 35    * @version $Revision: 1.18.2.1 $
 36    */
 37    public class XPathPattern implements org.dom4j.rule.Pattern {
 38    private String text;
 39   
 40    private Pattern pattern;
 41   
 42    private Context context;
 43   
 44  0 public XPathPattern(Pattern pattern) {
 45  0 this.pattern = pattern;
 46  0 this.text = pattern.getText();
 47  0 this.context = new Context(getContextSupport());
 48    }
 49   
 50  37 public XPathPattern(String text) {
 51  37 this.text = text;
 52  37 this.context = new Context(getContextSupport());
 53   
 54  37 try {
 55  37 this.pattern = PatternParser.parse(text);
 56    } catch (SAXPathException e) {
 57  0 throw new InvalidXPathException(text, e.getMessage());
 58    } catch (Throwable t) {
 59  0 throw new InvalidXPathException(text, t);
 60    }
 61    }
 62   
 63  47 public boolean matches(Node node) {
 64  47 try {
 65  47 ArrayList list = new ArrayList(1);
 66  47 list.add(node);
 67  47 context.setNodeSet(list);
 68   
 69  47 return pattern.matches(node, context);
 70    } catch (JaxenException e) {
 71  0 handleJaxenException(e);
 72   
 73  0 return false;
 74    }
 75    }
 76   
 77  0 public String getText() {
 78  0 return text;
 79    }
 80   
 81  22 public double getPriority() {
 82  22 return pattern.getPriority();
 83    }
 84   
 85  14 public org.dom4j.rule.Pattern[] getUnionPatterns() {
 86  14 Pattern[] patterns = pattern.getUnionPatterns();
 87   
 88  14 if (patterns != null) {
 89  0 int size = patterns.length;
 90  0 XPathPattern[] answer = new XPathPattern[size];
 91   
 92  0 for (int i = 0; i < size; i++) {
 93  0 answer[i] = new XPathPattern(patterns[i]);
 94    }
 95   
 96  0 return answer;
 97    }
 98   
 99  14 return null;
 100    }
 101   
 102  14 public short getMatchType() {
 103  14 return pattern.getMatchType();
 104    }
 105   
 106  14 public String getMatchesNodeName() {
 107  14 return pattern.getMatchesNodeName();
 108    }
 109   
 110  0 public void setVariableContext(VariableContext variableContext) {
 111  0 context.getContextSupport().setVariableContext(variableContext);
 112    }
 113   
 114  19 public String toString() {
 115  19 return "[XPathPattern: text: " + text + " Pattern: " + pattern + "]";
 116    }
 117   
 118  37 protected ContextSupport getContextSupport() {
 119  37 return new ContextSupport(new SimpleNamespaceContext(),
 120    XPathFunctionContext.getInstance(),
 121    new SimpleVariableContext(), DocumentNavigator.getInstance());
 122    }
 123   
 124  0 protected void handleJaxenException(JaxenException exception)
 125    throws XPathException {
 126  0 throw new XPathException(text, exception);
 127    }
 128    }
 129   
 130    /*
 131    * Redistribution and use of this software and associated documentation
 132    * ("Software"), with or without modification, are permitted provided that the
 133    * following conditions are met:
 134    *
 135    * 1. Redistributions of source code must retain copyright statements and
 136    * notices. Redistributions must also contain a copy of this document.
 137    *
 138    * 2. Redistributions in binary form must reproduce the above copyright notice,
 139    * this list of conditions and the following disclaimer in the documentation
 140    * and/or other materials provided with the distribution.
 141    *
 142    * 3. The name "DOM4J" must not be used to endorse or promote products derived
 143    * from this Software without prior written permission of MetaStuff, Ltd. For
 144    * written permission, please contact dom4j-info@metastuff.com.
 145    *
 146    * 4. Products derived from this Software may not be called "DOM4J" nor may
 147    * "DOM4J" appear in their names without prior written permission of MetaStuff,
 148    * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 149    *
 150    * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 151    *
 152    * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 153    * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 154    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 155    * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 156    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 157    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 158    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 159    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 160    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 161    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 162    * POSSIBILITY OF SUCH DAMAGE.
 163    *
 164    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 165    */
 
CloverReport generated by Clover Code Coverage v1.3.5
ma mei 16 2005 14:23:02 GMT+01:00
.
  Open Source License registered to the dom4j Project. This license of Clover is provided to support the development of dom4j only.
dom4j-1.6.1/docs/clover/all-classes.html0000644000175000017500000006402410242117752017406 0ustar ebourgebourg dom4j - 1.6.1 All Classes
AbstractAttribute (66,7%)
AbstractBranch (66,7%)
AbstractCDATA (89,5%)
AbstractCharacterData (23,1%)
AbstractComment (21,7%)
AbstractDocument (62,4%)
AbstractDocumentType (50%)
AbstractElement (45,9%)
AbstractEntity (12%)
AbstractNode (67,9%)
AbstractProcessingInstruction (49,5%)
AbstractText (63,6%)
AttributeDecl (78%)
AttributeHelper (28,6%)
BackedList (47,9%)
BaseElement (18,9%)
BeanAttribute (27,8%)
BeanAttributeList (31,9%)
BeanDocumentFactory (28,1%)
BeanElement (63,3%)
BeanMetaData (66,7%)
BranchTreeNode (0%)
ConcurrentReaderHashMap (35%)
ConcurrentReaderHashMap.Entry (17,9%)
ConcurrentReaderHashMap.EntrySet (0%)
ConcurrentReaderHashMap.HashIterator (0%)
ConcurrentReaderHashMap.KeyIterator (0%)
ConcurrentReaderHashMap.KeySet (0%)
ConcurrentReaderHashMap.ValueIterator (0%)
ConcurrentReaderHashMap.Values (0%)
ContentListFacade (27,6%)
DOMAttribute (2,9%)
DOMAttributeNodeMap (10,5%)
DOMCDATA (0%)
DOMComment (2,7%)
DOMDocument (22,7%)
DOMDocumentFactory (41,8%)
DOMDocumentType (0%)
DOMElement (24,1%)
DOMEntityReference (0%)
DOMNamespace (3,8%)
DOMNodeHelper (15,1%)
DOMNodeHelper.EmptyNodeList (0%)
DOMProcessingInstruction (2,9%)
DOMReader (78,2%)
DOMText (6%)
DOMWriter (67,2%)
DatatypeAttribute (38,5%)
DatatypeDocumentFactory (50%)
DatatypeElement (54,7%)
DatatypeElementFactory (91,7%)
DefaultAttribute (50%)
DefaultCDATA (26,7%)
DefaultComment (53,3%)
DefaultDocument (49,5%)
DefaultDocumentType (75%)
DefaultElement (65,5%)
DefaultEntity (21,1%)
DefaultNamespace (90,6%)
DefaultNamespaceContext (78,1%)
DefaultPattern (0%)
DefaultProcessingInstruction (24%)
DefaultText (80%)
DefaultXPath (68,6%)
DispatchHandler (62,9%)
DocumentException (7,7%)
DocumentFactory (80,9%)
DocumentHelper (72,6%)
DocumentInputSource (22,7%)
DocumentResult (40%)
DocumentSource (16,7%)
DocumentTreeModel (0%)
ElementDecl (64,3%)
ElementIterator (0%)
ElementNameIterator (0%)
ElementQNameIterator (0%)
ElementStack (35,2%)
ExternalEntityDecl (80%)
FilterIterator (0%)
FlyweightAttribute (46,7%)
FlyweightCDATA (66,7%)
FlyweightComment (66,7%)
FlyweightEntity (16,7%)
FlyweightProcessingInstruction (57,7%)
FlyweightText (66,7%)
HTMLWriter (37,3%)
HTMLWriter.FormatState (0%)
IllegalAddException (66,7%)
IndexedDocumentFactory (0%)
IndexedElement (0%)
InternalEntityDecl (70,4%)
InvalidSchemaException (0%)
InvalidXPathException (33,3%)
JAXBModifier (0%)
JAXBModifier.JAXBElementModifier (0%)
JAXBReader (0%)
JAXBReader.PruningElementHandler (0%)
JAXBReader.UnmarshalElementHandler (0%)
JAXBRuntimeException (0%)
JAXBSupport (0%)
JAXBWriter (0%)
JAXPHelper (92,3%)
LeafTreeNode (0%)
Mode (45,1%)
NamedTypeResolver (94,7%)
Namespace (84,9%)
NamespaceCache (85,9%)
NamespaceStack (84,9%)
NodeComparator (64%)
NodeTypePattern (83,3%)
NonLazyDocumentFactory (0%)
NonLazyElement (0%)
NullAction (0%)
OutputFormat (51,7%)
PerThreadSingleton (76,2%)
ProxyDocumentFactory (0%)
ProxyXmlStartTag (0%)
PruningDispatchHandler (0%)
PruningElementStack (0%)
QName (73,4%)
QNameCache (78%)
Rule (54,1%)
RuleManager (63,6%)
RuleSet (68,8%)
SAXContentHandler (73,8%)
SAXEventRecorder (0%)
SAXEventRecorder.SAXEvent (0%)
SAXHelper (40,4%)
SAXModifier (0%)
SAXModifyContentHandler (0%)
SAXModifyElementHandler (0%)
SAXModifyException (0%)
SAXModifyReader (0%)
SAXReader (58,4%)
SAXReader.SAXEntityResolver (90,9%)
SAXValidator (0%)
SAXWriter (63,6%)
STAXEventReader (43,1%)
STAXEventWriter (36,2%)
STAXEventWriter.AttributeIterator (36,4%)
STAXEventWriter.NamespaceIterator (36,4%)
SchemaParser (71,3%)
SimpleSingleton (76,5%)
SingleIterator (81,8%)
Stylesheet (41,2%)
UserDataAttribute (25%)
UserDataDocumentFactory (100%)
UserDataElement (74,1%)
VisitorSupport (0%)
XMLErrorHandler (0%)
XMLResult (41,7%)
XMLTableColumnDefinition (25,7%)
XMLTableDefinition (76,7%)
XMLTableModel (56,5%)
XMLWriter (62,3%)
XPP3Reader (46,7%)
XPPReader (0%)
XPathException (27,3%)
XPathPattern (54,2%)
dom4j-1.6.1/docs/mail-lists.html0000644000175000017500000001417010242117720015757 0ustar ebourgebourgdom4j - Mailing Lists

MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
    • Mailing Lists
    • Project Team
    • Dependencies
    • Source Repository
    • Issue Tracking
  • Project Reports
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Mailing Lists

These are the mailing lists that have been established for this project. For each list, there is a subscribe, unsubscribe, and an archive link.

List NameSubscribeUnsubscribeArchive
dom4j user list Subscribe Unsubscribe Archive
dom4j developer list Subscribe Unsubscribe Archive
dom4j commits list Subscribe Unsubscribe Not Available

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/images/0000755000175000017500000000000012133227266014265 5ustar ebourgebourgdom4j-1.6.1/docs/images/icon_warning_sml.gif0000644000175000017500000000110010242117750020267 0ustar ebourgebourgGIF89ab`awr}~j|fsη⣴[M@K? kTN G J$wsrpiffecb_[ZTQOJ E D E ? i2 nm]XWVH A = h2 ]-bz{z&Zi&i(j&127m-D2%p4BI|Du@Ya\}R׈[v[mI:2̓`vّs=.()+*砅.!ӗ<,&餍5&!:*%y*vp묜*,-~zǟ!v,v oaed][sv iT u^PW\ZMIgXUGADSRQ?4VONK)#CnJHFE0=7'6*v B@%+8, l !5"9.:/Lt"$&(-3:c Yf3cđ# ;;dom4j-1.6.1/docs/images/icon_success_lrg.gif0000644000175000017500000000272410242117700020273 0ustar ebourgebourgGIF89a ]yXsTnLcG\|CWu[vWqRjPhNeKaI_H]}DXvb5D[hgpt{Öřǝɡ˨Ϭѱ԰ӳշ׶ָؽۿܾ*7Iʤͺٹ`{gNd|VuvQo}tkRwndq@]G;Q@KuSGkM]bqpËۣ~|àʩ~zQKc[zHpADi=Bd;ۙЇّ㟩⚫>\5:U2╧▩l^5X1S/Q-J}*~MvHW}R|_r{hɞӲƬ|Cv@q=oJJX7yR+Q+O~*N{)Jt)!,  H_$@ǎ衃F q@ǏA`FE@e.#8qt2LCfXItVDc8mJCE|8T)QŠKK!@Ppʥ%K0[\†ϟ<[H%r=%³a3c.1‹=!re1cS4hKӄA-%P`zc;ZCT-NL 31%9i#jrz2,&EDIѶڦ26N#<'O-cRuEyUDR(`=s:`PsgK\^#L8A,\a@J<E_t",pQ=#.Q tB4Q7 1Ũ@EHqhPC~ D6p 3Jͼ+ϱO?Q =(BgnuaG}"~4#e,A9P 1B D ) &'eP ?"'=,,K 4@X`h0<;dom4j-1.6.1/docs/images/logos/0000755000175000017500000000000012133227266015410 5ustar ebourgebourgdom4j-1.6.1/docs/images/logos/maven-built.png0000644000175000017500000000160710242117712020336 0ustar ebourgebourgPNG  IHDRZ#/gAMA7tEXtSoftwareAdobe ImageReadyqe<IDATh햻kQHN2`aW!&D|W%Kt"l,R I* إK><\fܙM\;>w46h4:ޝYZ qlmZ;FVP ]xcRtbUkxO8Gǀ>GUi߂x~p G s8:n Ro㽜o8赔ZkK*_,8j5coح<;ŵa☼x‘sO6K=K ;un @[?9aXyx7Rϓמ4q+]'ؕ#kh ZXBDx2s_3K!rSz.<Zb0`Iqi_dP1ˏM OCyx "m*15#H=ݙ_9l ǍF i- {tD͛AV $&:D|yQ&QDw;FAG(g`4Uz#lR*rYtD>7 5*q""M(=ȍ$stcƁ7Osn$TA֭NwA D\B׳xK')̿izPx "$aMZ\"YHuM ުdp@WÔFf ޻TxĎ C!T~ŤbrEG}A-d\fK(~arEIENDB`dom4j-1.6.1/docs/images/logos/maven-button-2.png0000644000175000017500000000521110242117627020671 0ustar ebourgebourgPNG  IHDRZ#/gAMA7tEXtSoftwareAdobe ImageReadyqe< IDAThYݯ]E)rc{sU *dhc}A'}wTQj(hk"Rs˽̞qsϥDιgϞY5s}ϯsѹuސBr.87{"QMUL`t Q?\u5cyՖڇKIbWLMX>ԥn.ĉ˙9S쭼ޤR7 2 K nІN;-?iON#c!xT4Ha4Ν`:|DC hP1mC|B }](!x F Z%JŎ. >ܥVhZVL~Ќqo2OoZ/!V-Qh^RIg` LTZ0,5WLĉO97 .YD%ʬ 4 >XLv^6zۦAd"$s?:$cU (_<9vX]ۯņnĕ^>BE`~' @Ke Ϳp!Nh[b Ձ)6s{-?2N#2Ɨf^2ggIe  Bz`;xc\g8%gjhoEEN-Y ~;|s3R3AwS"nu'>h(lv {AMzyo:z+U=vמ% /:plqazXE@tB ȇ!HA-vdh/{[\HסRԐ>G&x_Zψ?pN!yI[;xE:C(PX_"-xr (F` T )DB;4M4TZ L":dwaA+/"6İt!bb:ꄼ;$&nԆR#>Zâb̘|ī!, PVU)q7:t;FY"rչ \U{ѥVFҥ~YќuR̕\8J(F rL *7ukR?Ic̑g/X95YvsF͂JR$d9,Vk8.5}<S,ReɕW0SfG*4H/US.,߰ݜ@qte`èa%$76,t] 2F#  HԺH9%#IωA,#\4Q5dհ2 @GKAߎ^zn E8wQ$DIf2F"NO{O`kdx4[ Vn%)/޷W9l`\hSdF [{2YI:B'6ݖ$PC.Wc-5=DІwJs9xkl a?v+9a5u6}K]!LX W]]#w2hמwҼ7%(d3T`q_rJ5#?cle&T"[2W|>uf+fUrdg>jj@Qa[qFb_|AN}|qI2pmvxU\布ss͙ٯ=_;DrPIENDB`dom4j-1.6.1/docs/images/logos/maven-bolt.png0000644000175000017500000000326510242117710020157 0ustar ebourgebourgPNG  IHDRZ#/gAMA7tEXtSoftwareAdobe ImageReadyqe<GIDAThOH\WߦfӍ uQAh H[ H3E$P0 Vf%J(0 ta;T*H XPU颸h6YM7s̽oLsޙq%.ttb\88NNJIR:=Mhy̓ck͆%*|[_R <L's6>^ySPNM hlpLOOӼŬr90pb=#3ZlFO` :DSbm]Xl{>$ֲl[[ۍߟ=+Q!J][9cx% fxO4gMTV ^дjbL9UA>O$lll|H+C[X1Z7HAddd$:I2ott∙Ԙ3DyFr>Ls'yeXaQ`lDLʓ ;;;^@"N^H>tGj<^*rReWq3>^ed 3);;;y!͵C .YB1j\b6M+` >`ݩd16Ce8tF)L *AR0imm%H̖;𰼂"8YEV5:n 4)Iˈk4Jӎ1-UC. AK!j|zV׶{}^ÚnyNLNN&344NUx'w|ϿWeئT^ [KO[޾gy?йŏgp3,,,A]k#n~0ӯئ#?D X"o-v Ym,z8(`ϿE8ΩO~+IT1^f9xX{`pѯc:n! 4/zenti@?_kmSSSw"E; dKc_QuZD#WWn^iWDle_ʧZ#8H^@AN:bN0`md)gX.vlK[$|R Y@D0IwH)X[̴LC,z*;»FȢb6cssνK) 7NߘlWG4J Y tŸ.5@$Mp>mH[D#ߨ 0;|Tl:kncp;D}h6 F Ss MMcq 挗R:/}'DDjOpP ȩF‘*di$#=j>'_G7{5֡ot81hIENDB`dom4j-1.6.1/docs/images/logos/maven-button-pinky.png0000644000175000017500000000503110242117735021662 0ustar ebourgebourgPNG  IHDRZ#/sBITO pHYs  ~ tEXtSoftwareMacromedia Fireworks MX*$tEXtCreation Time03/19/03T} nIDAThY]l>;!#I@bPRj@+8•T$LĿL BiA!5jJy yl6P3WH}#{=gٝo3gبߔ2 ö4˲l)*Ech$I]э3 J-J_Y\byWݜ?Bg):Eh8ݻGpG(ó5XƯ_6l>6#wS!,{JtFjIu(..inQ,4peZCl wy#L3Xd$e(ދL3@L],=vO^CCöm6m4 7o ?h`psuvvuk-̘9&ٰaƶ6p;vt݋v~1~? 7-0qf9lPvݺǎ2g2$,t?|(&u ܹ3CqlB'GBhrJkZ2ƅpzhV\yutA;\ӽW{.r||&'4;1Iss<OLD,M)^ .XY8<8pL)-uc?gmmm,DR h%<---û?r֭xpʔ))$R 1#FЌ]fbx^ÁN >ON]]('OBS__?80G&1^`ٞ={G#L1~IWxyP1Qrt:Õiގ WKR4%ɤA'8;,/Y… ]&x$VXO/s.w~NqJʺ_]d-{ف#vıOW̥K͔*))1؁Hƞ_z5a ˺Vbb ]0u3ŋmڸ1A`Niv #S q^/|S]x'«v̠SNwu$#VXܹst 7.3Ju×جSG/+8V8R ;jk{z@:yʔldJôt S`=J1唖p.jke(V(cb1qKP@i,p|?̙3'%Kr;&|rm.\+̚5 &6Bk&L^rq{l)$>|@S}^}Ք=mǑ}o予#b_e8h̸ VH7Q߁ㅲh( UBWQ"D>ZֵgAMzFC[)1 )I |8ֵfKD!)4Fk3߼pJ/oU0r?_NcJ{/IENDB`dom4j-1.6.1/docs/images/logos/maven-mavenfactured.png0000644000175000017500000000320010242117701022030 0ustar ebourgebourgPNG  IHDRZa xtIME1UbKGDC pHYs  ~ IDATh}LUe\\kD8Zjf%"sYȜs9 I$# RQE4D`ǮT~\1/ek~^ sζl=ĩ4~F9wt{``~XNc, Hgɓ TW+ K9%GjY10 ~= WB6I˰1ʟ@328n2Æa`_N/h}5n\g^{Au&-U{9oƥ4xc3YFX7rs 2"af&OL||EU\Иq%b|!''W>hd zX˼"%%3OSk=՜2;IH U[XBrR&SVxFJ0CKiLjy dx-J,WQk`GڑN˾Uͩa0ZSvyClQAг_3jOa"_qX7gf='\[_cJ{ 3:8n>Uc ]zvd3{ͯיZ9#΋fz)}}3 HPy~ޒ ^z+H Lu?({d-??p㏞f.'lHr>XD4,e̩s~Fr&kҲv'֥%b]eR|#p&m{AbeN4s;lA뇕A!}ehz@f]uWRfv{'kz0Ƚ2@`X+Ce H8/%+mVt#ȎnmuȻoZ?̺V'Q ?MfxKh]GLG@Po+R *Rm6+m@K H%}My2L{+-=]O2ǬmfғC,Gżf.mm@[,hK:.zKIENDB`dom4j-1.6.1/docs/images/logos/maven-button-green.png0000644000175000017500000000367210242117736021642 0ustar ebourgebourgPNG  IHDRZ#/sBITO pHYs  ~ tEXtSoftwareMacromedia Fireworks MX*$tEXtCreation Time03/19/03T}IDAThYMHKҲld%JH uZ(A/FX^" .jQȠ@m!.2R2gf;pfyys~uovS?[BӧT{ŠU9ƒ{,us\iO+'O|p,--1,p0(|`>0@apveye@ SKL( Kig;'O _GA.ږYlt}_VV677Goz ڤ7ntwwCqjgSWfb$jv@hqcPpůبΝ;36Wy&1?<$00(i*bMtt4wAm=5L3lg accc"׸Į59d5;ӧOChA1uw\P8dWC "fPq&a-=8|0+p䅜9 MjE.WE-S񱱱 ?aJ!BfIII9~8d7"IVhn~9 >ʯ_P:%‡qQ `(A#31 h -MdCP#&&˗ȤqqqA>8ָHERRHN[S0W;m%թL'M YUqܹsc;7+(O> j!͖!u]o߾3Q8 Du.*yyyQSW[={ s.]$?AIdtt"s|58\H C+1͠777CGZYYy-P0~]襥EEED:%ґ/{xbvv6hsss } ‡Nt1uzMnI3C\zBE"b OjM)ϟ\#rU<1Ǖ˗/Y")NiW8f`n谶&###h8C2ʔ` OV()$>!La;M81)hfjj*fەIl:9'''JOOӕ\@ϷVvUs`0)^M233kLq 9r 9G}t Bw07l'R)(U3MOO4*[u%]p'xm J ;u xA EDU%#.mYAOLL|E6H+cǎn7W,SIdWԙ3gvaֳYA8ٳgO:8"P}Vof-OjL1E1E"ZAw3W*|=>_~mE#.z$$'' P!,ABivy7orytQN:\ʞf[,l}r#X[x?4 IENDB`dom4j-1.6.1/docs/images/logos/maven-button-1.png0000644000175000017500000000622110242117744020672 0ustar ebourgebourgPNG  IHDRZ#/gAMA7tEXtSoftwareAdobe ImageReadyqe< #IDAThKlU:찃*ꨃ*UHU*Q(EPBx6@CH `eü`ll_c__o?$Y9&2l=gLƳ1p6;+W^?|jݱk'ݺPRz)}Ie{h;wo>6|;Ń>z<~e~E1ɽGeTnܸm%ܻz+ ^lHUԷD .'+wr3/_Ytlɮw?;db!} 8T,O4mGnn oZzp M}]{bxYq<Yzp4tv¦O)\N+g8h .(@Z~ӫ_Qt콂R@oz`kqIiOUnqAR؃b@*OY*381^ ADNb'jPDXƲsJNKv 0@2±5p\!ȌVDDW(CD/R[ 4#*s]<1=aBόJqRX8yy#Kv<0=a[v~^ [/s,(G@RC!})4FelA̕SboRN!JV'"} Fcz%#uB.1Om[s'J!_;"Ld#.xIbVa;^NK!ZH&~u5xܺ"<ũ=םGiՙ4[u8YS2{nr*,ȠH=A*hm;qTz!~ĢPeX\i JȐ iF #H c$E H]k Xy 4!P* @Ԯ(JLxWD>)=%<]3(8jCJ Xŷ*SmaP#S!W<`ѡ%dڕhC4Yۼ΁JOQj + l o=oC圏v^\i妿m).C 0#ɢԒ(XH> GP_ڨaP#3<:HfMd\IHD! QW>CۜLtpz_]\K._[+_0w_l;l*ih ? 8P;KPX Cbyw$:#"<$p_K]Q6y OY,kНR#=)Hё⛏^`Gr̈́_,R$(Q4y*Ŋm[ю:Kf .6Wbei_D Y^p̍&`(/9c4`y2ڃ' yT @!sǛrK lm:Ե9EC8;Wנ P sM]!|&J5@u*".hۺtQ^,F!f>U[ o7Te5(0ZPM RꙎ!**rjW+>'OwT#5' o,4҈>1qzh8@,d‘.2E*ґ\|V$BE#9BqTopↂrCz0'CdC4T9u!x:ࠬpR46iqT'BIZ+8ɔ;HrʻC]07ݖP> 5j)jkw00000o0ũIENDB`dom4j-1.6.1/docs/images/logos/maven-propaganda.png0000644000175000017500000000415110242117746021337 0ustar ebourgebourgPNG  IHDRZ#/tIME'5WbKGDC pHYs  ~IDAThY]LG>QMLL-آ5AZlSL!5`>`Иx4XzI|ЗԦwMjP/pADk[.H,k ۳g wvov2Ξ99_m!9y!E򑏅)"nbi]/"B*'13HM%K1c` /DTi~Mx4=l'fϺhPAa3kl6n`% VڃA Y?-Un˃MWQ]Sp&MPJ'0 l8 o¼x0h1 KfY;qCӞPgL[M/_+*m?>mڴ׼Q]CV²~#̈́˶MeJ kyaoq@ਠF\ $`Ɂx'[BK;pWL4d c[] *ͺ ,~18MqT(dc4a„I&y!.sؑ1\EӺ8XY_q%Ey ;>0+"R0I56ؤZPP0{cDzdxu׽\M[F/޶I+M}fjڀFΚlCC~ر#ER]RzU(P/Jo7qɾTy!mXa! \a`Xh:YK\5m@L £$X}a [?]f0(&?,Z%WTXBE8 |(DE nBe3.X,5P)EoC"qG( 'X\Ny햌KuQYYitF'N.SR~0t }iXqpkZO8a[8F<n$*W$Qۖu%vʠPZ0d(ҐQQR G4j.\ȴ~ %Z'qQvsANsB¿xd8I1Z8Ϛ:"s¸q<& D 7YCddF8>LP~=/(VPEQ8Dس} M)؀-fkكpp"Zv?{;+g r_KA4!GXJVG]JLԀVЙ3gΔ)Somҭl'CZ  Ҹ:F#:} IY CSk tFI9Mauy#MZ(.[h(Vi _i;FM-+/4:j} qus:FENRJJ|%9;,Q[+h{ tRNS8Kg pHYs  IDATHǥsd^6 1I]߼T5M"[EVd[t'CzvMvI&<ϏhtR3t^/(|FVƤӱmKR15hDZ =tDyN?}pъ5O9oޛ߁( k h&vK!Gnj[7$5؛U!hpS <~\Rs_e`A˅7 ҽNaID]4j^:C>'@ &'Їн9Ew*d$owHy 6{o| |vhu!6J$~-a g<}6f@se Xjj~K+ӴK+撆j6WNZ%DzՍA4t2'B|zoWZVWn]aC>OꠌO a@Ncd2o#ƅ$~LZ ꘪVQ^A&!7'$as{Xz=x\4d-^RRDs)0"*9kX < f G1a5Ml pS2XkXʊ 8!uHX, ښb^!X2P$ 58-0pFg&&D)|B4e6Jf`Ԑ$m!PP0fVMu֥-Ψ鰙X)- OBTazu=@6azĒ":,iqh:EaWd5rY6E[1D˄M#S6u`~5fHԜY!1S勌yܣU Av$w,Ӻ.cAY8CocŐ:>|: 1 e )4Wj# F~ˡܡi)|5iYWTqLQhE@-Y_t9G Z sH<׬M8\{=0\ K{{\ayɚIENDB`dom4j-1.6.1/docs/images/logos/maven-petesucks.png0000644000175000017500000000052110242117547021225 0ustar ebourgebourgPNG  IHDRZ} PLTE2I pHYs  ~tIME9 GIDAT(ϭjB1#9 ]eG`h>jWm[, 36|iU @xi ~X*cs~4?kni%'YN.rg-YNWa^ܖʌQb QK+#T5EY71B-PZ~?[PV1XzՇi8'cueXCÏVk1FgђC IENDB`dom4j-1.6.1/docs/images/logos/maven-button-4.png0000644000175000017500000001435110242117753020700 0ustar ebourgebourgPNG  IHDRZ#/gAMA7tEXtSoftwareAdobe ImageReadyqe<{IDAThywy ,z#@ AfIT;\e)rع>Zu;*eU:ɉNuKKDJH$mlߝٝ>s_7xqf{y>m#x׋_/_x35J"L+&ϯ,5:ƫ=3g\uz:?VLYPho"y|{뵉%F>xC[{'e[7{*.wx> PehLYJn-ysAʆubbwvѿsKOC>/׾oo3+y o7[sٖILJbgg? ['|_gy3[ny~M'' 9YŇjfd"ktYD4 mMf*yP^lm\ʱnEDbK65MdbݽO-DX[Zw&l%`ΏMLS;䆴h#cwOd[ 7|{ nW }XC7Lɱ3m|>ѩ'?DYc$KJbkF}[ ksՑōLKZNOTq ɱK>’®J^lxtIj6<9VK=;D[{z;חrfUF+Ԛ)m0kXU7%X׮>LƇg>rT׊|kơN.6+Eyu&#HFrY;<ߵ\.qO'™stK6T^.+"gpqʇl[h*Eޮ|F7M.Ǝ`v>djrbZN"VBEws9PX[b.R./UÅ6&YYHxК@zCXh-Oq,s0'q#"5yz4o[.yLD^,͘+7ef>OE.GXbp'ٚ=nϭVCfبN+M]*¸onT.'xҟtԃ3]Xn:<4ޗ,VzqpWQ4dM\vyt*ҶO6I|A0׆?Ϯ,֝wZhfxTN!ŕT(ّ̒ǚZ<."034V׳b)7>z ph %BTf}NxP`fV7i鉩{ 5-M6eKFT Fe}}ځCNdǏcK 8WjٔL# U 7xk2ڨ[+ݝ死cQm_807ab*"ŗO۟R@'ޱ#~û`<*bY se0:GrTLr-_w5EE139e~j2H9lemE}dm†1'_q}hwW< }OO8eb2me*֕hWsTOРU^JK+XUMe,_ъXs}SVVr!e)8$Iɧs86yߪdgǯz7UY_ywY6GJFj%:ojQ\7M̗S=}LW_^ހAF@@}i|˶O8ϥGґo~ }͗ YyU4}U&O}&7µ7x_ت>toI;r\жk3.X[2p091y%:xy~g#qyVKm~WϽ4-M{~]ҽo0*Z^ZuEzgOgH$4zJ+/zxǑ~{v2X~c{bKKFo:3zljn4߼UM]y? ŹHtɣ?#|ԯN߄C!|kM^ϖ8}(8?USnl4n{ I/"ndUdU_\@*lΎwGC-K6cSЧз_y>Fumbfgnї.{buBx b._&$ L>~̕~yjm||çN\.2Kӳ+)DtKHt>ns~l/J{6f2]._-{w#޹j]ܓvW.vg>Z٤3htkL=:|[wT9v)K#2^k5!o0m߿|@SH/ETU"y X.;י"~qyog7?.ErfܽMqՅ\Mlw9QN4㚻Zۓ'YhuW\ qoW%;*:Z_;)򵯽O't]ǖ֖͘UЄ|ہm'kqq*rhHұ Gc0hA0!$S3b:ZX*6#ر.}1BhPHe(UM^,2Tg'X<]~jUE4g\4cSk>6(\=tl6Pp,(" ./漭:dK+Hvy=m}]yD]}?lR(u!G9p\z_pU٪dɴhWn}&5 %474*6na3dy;OВPmKsq73FcyrA[6p '8.|Ծ0K*b{"r^DY,K#$c~ɷ_y3m:AUqt)‡4K,P*j%M6jXSz4MfJMnA7XҴ]yZl-Q}]#LJօHKXD0xwȟZ)JŸ(rxejfpjy1նBG g\&ݎJsՊX#GVJLT}mU>1zd6 s MCj SSKtjKtwr*ӽgWA͎MJ3XU7=A߳'gϟG-sqv$+0ugb4mm!F/,, C2++3q&.2%wjlD/j J@w6FsPȦbfEpB#4 BNM8)3ialR o V4yP,=FGY@8 @I "Q)APMgaPhLݮIGocmڟRX oTElp8ن9!"pk 3&*Ќ _() T IMݜ{ &7,;͓zTPA08OØ ~BkʣσWnUt'9 qc ev^:dJu5w Mq+ wJ/cd؈X ⥢&mSSMp%e^Bñ TCu(4i&w:چx4\*rCce QrM}^勔r%Po{TԴ ӰQ%jE%k=2P0N#iJS ŚV)A,BAQԄr6Ǥ8 %64fM_G|U:;x? x,hdB5Kr ATu428 m) cEmf~ >tA()"Pp:6`qQp-b1>(8,Br ضfP[j&I&пAHSI`؎s4ZM,;IENDB`dom4j-1.6.1/docs/images/logos/maven-propaganda-2.png0000644000175000017500000000547310242117704021500 0ustar ebourgebourgPNG  IHDRZ#/bKGD pHYs  ~tIME4D IDATxklUUhJK_6N+j8 qP!ʌ~cL4ɽL: s%1'ƞcP;F!w_pĉs(mZ=vG̨4箽^k]M0 GB OQ5ÕyfJCfpGrJ`=NI&y W18uan yLdJOc, ѠLӡ`k F@Up3%E0C̅LI?UM=irCha:J`;\HHnl =TYVd!ǹ'K!ekBͦiѣG}l^)#s>ǧW|<+LgaH# 76?{/PP%2RLne!%==5R6JVn2XjY,Ur)ZValrx A,`HL.M ,eIJ&BJ,+<SA`&sʬ:tPK Zqr63-ƒ[ $}En]_`}(5 LS-u uq9=o|V| AZ[b,suT,ka֜:(pgLؾ";n?ϳQMpݙM*Ufe9J]^-33uhŶtpk+pҶm{6[Śv@*;|{~bX=I4PٴJ~Z?52ΔɊi 6(mcEe"Dx 5r=K4aHd[)a}0kV\\p &2>+%4 )!:dYRO xt&dr0v0&I)eܤ*0U:7 g4R& %,x;;;O>=>>GUΖ-嗇(ԬXbo!+ڪx4be, +v^ubwbA4zmWb'm{$dׄ nuT9:*aQ,\`pp0WXHM 44w..\w9yS&)ŋD_aYM6!w;ѮLͩHAuHl PA,]ܹ>]`Z~`^}E}J2@7{ON9 O{ SqQM0oz ,W:8{rLLL[6&?> YQL&ci e4OhB8 {3ؒ+Z010/۞掛 x!'JP^(<kT޳, !,%%8J0 R>;[*`ev[,)g}P1(=bz7c#GV^<Ԕj /P^ B8QG& HZ_EjLsw\WjN$Mj 4B%a m;X5P`>%Pb[P5{6i?;wr׮y>C1P s JRD o&\3 }D"iy" i~f<BT*I$Dti$ნN)[NI ) }Hud"R&IH)-,M+ k%h{P@_.dq p$Ʋ,'|6444=v#!۹/uu+40s,Q}!+*#)=6u!Wm>boRe-,uϥ|O9 BGB,T>}EP yq@~P(^G2h+koBlm0"| xVC[8 uˠO4P p8g\TI :ăґ W3m'oJ4(0 AY8 ߄ςA)Snݺ'N6 –||P>)}ŵTXچm̞]B`x5塧mG{˗/}߇[h9ћ7oDρ1ƍ=awEwwwwuue1s eH^ % qh瑰cذaTWXɓg~嗮GȰvYYmСAn-[x&e4ݻwӋ<1183TLkG w@8_pn_wvЂ+AϧuuoߢgÇ[===JG۷9˞y+B&#G r2/X4Ç%/kK;0ݬ olL,|u" "m 2%ĆV6, F*wc%v -v(R Z4;‚3;::{zK#*4Df.q=IO#W[j&LfEp{SiWf̘1j(XTͥ=t- .?@c,U*'3!9r_?ߣF5WVJ e \d b;%0( mpŅOuvP(ƍtғ55 ;z{%Nq% 2)S +KnX^w^Ca<@;[Z$I"PUC$;@'ڛ֥aG/5 ;*++ F!fA{Yʒ%U8u|48czj?s J!/]wիЙ?y&Wؙ^pMѭfG?W- 8r|ʊaԩSc|CAFnرc"o"a( пjժ˗:uUC< <ژh/^dE^\~ҼyfϞ Dt~ƦBN0%ptvv}n 9O Gb9 Ep=sѨۦM2\&iߡ֯|?e(q֖\񏰘>}:%0ߏ,?ٸ2,Zh… ,L† <ӊsLvHak@wu֬Y桙H}rJ6o/]fEE7o|T#PIGz>8A?A;fΜܹÁ)ŎXӖsߪXU,^"#e pKfVɩb{Nu9X[޸~4u)^IY ؑb>U!ȕ+WMH$w5#@CaMgQ Ya%)y$a6̙s0h\J:KJ!~ǹ|rRFܹszVr¢^caAˍr¿8p2y䚚 l">X%&g(Uk҉,wzB'ٝƙHR%)ӏ=A'g;wx9^S8LO{0f KLmĕ~Ե/ tPm<~x‡RAmv%ݾ}{ĉ87V[y$ۇ>}`ɒ%HKK謬,,_ׯǍ7Ľ#;;}ff&\aMp[ w.B Gaݺuҥ pС׀0`<==}vZJ`;"N:b8__ݺu//@ u/_^;+c\Jb"Ty+.A2ܾP;~9r$N:] AkEPQE!I9zp,C>نC{!wt QO)S^32/--JJJz.u//4Pq eeeĉ$=6l2_QUgVi%yȖ!U3U]os 倶®]Ē|VX!  k,ͼyдiSAٳG[q%\vM)|>.qU'[e'DJCR!9!9A(WOd4S㈈رcѹsgfΜ)P =z3g7qDᕳg6F*sEqqk?)1bv*ƪ-Zȶm3V:ű ~2z¹3j m}t5 o ?L?[",Fa?K;@o}H mnٓKmIyl܁ [v z~NVS4F ;|z5GKwL2 A;[ew+#^̒#3rd j:"2|ܰy8s䟸VRϞ@scsvv4L B졎HA;’a }{|i եۻ:tj}0l%W/^!O y"SKoh56a66ףfr8?58# OJ0Veל*hGo 5ݤL1^3 -#"keI ZoW .6F|Fn[6.ͳ{qRQ0%犐Cap dM></x@úXo>kL.`W]oؙ٢ɗh"{}#]C4E7u1L `>\=N\S51JAұ`ݎ'~@SA2+- C+qry E֮ȫ&(gi<'c{LSjX#{T3_62%9Y}uOk G=FX~<׸%Y.=ŋq(rmG̓&ðv kVn FE!H[ ppi#qGD٫yrg8d'!=}D@WrzDzexdށuG%H" HdpCpEr7Od ~H5IK2$ !f>HG!א*ʄ;0z>S{V%ٸ 8qAAH_.uɓrXaNOؽ{"yd "ܿ𱱱ŽU>{EEE…rߥg(EQh4%IBƍQNgZ]hڵk+k/^5kmz)]ߺur!7jHx%##۷/7X*$XF ժm۶m+wheYرjdC}f̈́AbQX m;)LLL@Zj077/wh } Q8ԵjJ ^@RYw'Աd.3@޽{С7o\p%''D޺uKˮʉ # ,hz>Aiӄ3?z*KII:a3ddǎv\u,p>}auu{瀦I_ zVZ8w\q 24e˖-[l)6zB3OWt,ײrH YJ=ͦ>|BGt \\J=W o 4ٯ_~_WWr@3-'GaN͛7܌y SjJSh^//ܽ{WphɓT.8)Ms ,l,rcVfh4088XDEyKWࡃZƍ'}4Eԓ>VBwOɿ6"UQIENDB`dom4j-1.6.1/docs/images/logos/maven-build-successfull.png0000644000175000017500000000205610242117735022653 0ustar ebourgebourgPNG  IHDRZ#/gAMA atIME".bKGD pHYs  ~IDAThX=kUA_!$QųDDQAAAJB0X6bca!$B(MO9Nffޛdُٳg޼h?|eYlnq9>W3*b KͲ=>T7-v/:?\C 0N:jTC@ ʁ boP kQ5ˑۘr۞Ax^drG ٗI394998( ch) I1A8 W.wZת%\:A!/%!i/5ʡX_N=ş.TAws(:!Àˇ8> Xd2Đޓr>__V&AʄrW[\`,k;-'z 0B}S.Cg~@k1r{'ELXj#j G{r_!-.r#Y!){:zéOvQ(s]-;5Q3v/߸w؆M[P!/\ p}TD!xaT^8<1M1R!&> >/ :DOh Eս֚sp.hMg^̯Xc@yq' b`* g<38NЀ.m @ ۀs` 篠݇=bm,u}eh"j3e&~HH[Z7@c`ha3"Ev\0Ub#$TiijTZN6JM]Y 2VU0LGsPOhˈ> >230}]~"h-u!2hw95@ZbXB a[Rtg^D)F!RyC]s)gylu#VM,I9 d&I01#" sIQ5lx Z:[L̴yxwiw>x."2#_+O H8sMO cdd SAE*[T楔JQNjdfFw=̳l$"0b @RbM,Ʌ(Ui-rGuIw>˲eumb؝AIFMx7`2y\# &Z =}bB}N5eNV+Vig̓l7U;ŔA p"p1  A8q 9!%p,Ȧɺcvdur P(i E=C#)Ɨw %c;}0$P$E3nU۷z<4hF թv{vm NNO7әpl' E"o$6%*Pc] `f etEP!^+y^Vե&+MiїeE\}'qB'ܹ# >Yw{R@iGil[o:;5"[QQQϬ?qzsNȭy8g((/LB2 0 yNtɦ&k1ڲ;s,c]je-\h競Z`I6D'r@`+?|nlÃ#CH)&PJB b{ړ:ٜzƢHX:&( P4w[͈rK @d p% $ct:QJt!aVQ Ɗ>rvQڏjrV;?dԋ2ZuTɈ\!$<׼/|ߍl҇\%$#36prrm[D2Um;[$x+TDpyˮ\1>"@( Ğ,0Ifk-kV1$բz} B)d'4*Jc#Ž̈̀덵iU &9z"v[S @9p>$W.?niKa %9N` *z2 (4TjܤHTFxJË-c=X{:rGxn#djLzdD&qRo}GNvZ>KHJ# `$IX<7h<2b `AX["p`̉!G7@Zi\Cڐup9_/.XzC6r]9X"OvTUhljWnfܸ~~?u6[A 0^RL@)_8"\ ( 3@G{x4ET&]LBT:w.o}Y[͗CҜ.C>hH!IjbadZpqq޼v]TlH B&q,@NR;d@"fBKKSL9_K-lo[-:) G!X=wvޖ}&=8YyX,c3[/~K& aTTb>vc+cQ"t`$<c{1|tEff`d&@fo a( 0GWT;3Zy̫@yx (@HAO"$IBdƕ0?+a?Dվ)7U \*ʣ&@gOcs'x #A MR+M  H "i ;hBI%: U* d&!%/a Hg? @ \mk颈HFJf$/Eq3q(6P2syl}732>:}?{W}W_y+}?7?pW}+}~/}_q/|4K1L^2 j/^VT;uYfJΎ|>s|FE..7e=b:܂Kquղ  sO'SZ}OͿ4"}8y) "k]&4Z֩qGluŨQ}G7ބOHm>^);~2d}\W%o'>;? .]\z>}3~!()*R3STl2NLHyEW,o: 8%6FG;$t${yI8RD @dIdGr ӇLjQ|)r#R <7B_Rpw,(T}kh}Nt%L^%R#+_:j`IENDB`dom4j-1.6.1/docs/images/logos/maven-button-blue.png0000644000175000017500000000401710242117752021461 0ustar ebourgebourgPNG  IHDRZ#/sBITO pHYs  ~ tEXtSoftwareMacromedia Fireworks MX*$tEXtCreation Time03/19/03T}dIDAThYKHM֯,n]ETD YA.H[X3L] YR"Q "n`t1|<g}}?fysΜ/2;99ӧəza("BX 3gu %jIYMHOlԈ p,J]]]A@ 5z^޳D-=`S"Ed@yIIXh k8ll#iCg'vNZt&wuƍV{ر7oܹsǫ~jll]xqʕ2IYYYEEH'N;wiΆ hRP~*% ́޾}{uP͹sʼn?Aa(BY'e/D A"p$$$0;n޼ c޸FFi#8}4p=񶅝uL{6}Dy477KS$[nA{ngʨ?~ XMtvQC a#(kRLH^x1>U$,h8')j "^_PG1::*;"Xs\+(5x4 v8vŋ扈y GXeLL#Ovfd!ZhѢ5k֤(?$ v>fÑ800iӦ˗#213m{5^s杣ϟ?Hzzza#IKjFg,8ك3[8g:o_yYC.p8 j$''$MKKf߿ ygAƑ| "_H_z_,]Ci̱RK|H8333{{{SSS,K,k(#5/ >|B}evCO}SS̃[wޘh'O|Ey|8ύ\@2ډj֯_!gΜ $aE%!@s5EEE DV-l}GG[hΟ?DvDj,XwgC0yz8 _ 2灇2N S^ @O'4-\ ^&Tl`qF#2ܝ;wرC;:ԩS.|ĉN7q'6'fn۶УN`No>C` ꠠB"]7U9$4;`"K6bc˖-?~xX<}6^UlӡϮ] wfF^'\q/uf30>_IiUԈ0hki6ymyma9G߿#a2 ^^Zg(|.Qawiyƶq.˰6dw~޽{v8bN'r>bX |Čhy5p~:==ϓ}6KbƤ᧑z ]hԄlW/˖-CނG-5˼ nws8jgZ/PիWψ .3Q3ҶG]6))I^d$#^M{M{ľ?nݺ ^ρ+ϧO:Q34ۡ '7o[5`=©]7l,4rI5db_U k#x!Hhag6.oPع1$ "xxfIENDB`dom4j-1.6.1/docs/images/logos/maven-frankenstein.png0000644000175000017500000000201610242117750021703 0ustar ebourgebourgPNG  IHDRZ#/gAMA|Q cHRMz%u0`:o_F pHYs  IDATh=r@' qH@U.gpSHJ|=u"\WS3ʬQ?uO-FB؏6qȼppmfI>?PSa&Y4 g-9?R=Y4SC@&b}8lnAwfR,PMx5Q3"#e:Y p(\ }rXX?gށ>-\C:A"Klk[(U۾I1_>]8`-!=;&ףh-p ,v mdԅ6(qP\J,,8V}r%ҫ[1~\6 hVjlR5#n\MX(|ˁqq8`31ˬ_Dfgaq0&q:),UѴC-e$L:8B',]u`s%C ^Iו,%h D[!jף?\whIaI)Z9 Ԩr8hL ǣ\'kH%R̈F Y9ܕI=^3kq#|/&^8#"uhV/ܤƗdzC1e򎜵#'X4"Bu8d3ؒJ+vX ؛/jZ6ط- w}J2^Рw,dӂ U4گf%x\;Įn8XzZw=k2^LgA,[ж!G5`ݡo;s* yOLƋPq+ gEno Ĺƭ$&nezw S[50sIENDB`dom4j-1.6.1/docs/images/logos/maven-button-teal.png0000644000175000017500000000356710242117714021466 0ustar ebourgebourgPNG  IHDRZ#/sBITO pHYs  ~ tEXtSoftwareMacromedia Fireworks MX*$tEXtCreation Time03/19/03T}IDAThYIK]Kv(8]|?AA0 1†8!(8[]DAE .@q8滷eܣ:}\??{4?<}OzZI@@|9Q""YqPF3!҅)7 +͋PPPVn\J www-Y`Qlb)Z7AAA+,J 8>zʍ Vq OW,(]]] ӧO}}}P`̓ CMMM?nmmA0`yy9Hotn:^j3Sdp:777c ˦`8 `Eww_ ^'t[mi!L!;߽?? Kuu?qA OA@K8; VQtt^а2GFϟ5z{{ jRх75eAÆl ES#wiK#s&n8...%(H50 m.suuuM8gtd0#:HEIOʰMN{!|QN ^3$}8̸EAcv0 ЕV|C92K:;pDEE҃ G4 AN%V+خ2 ȴd  0F:ɒ@3h§}/j"mmmD}VFGG0 G,.. |,+}l86ra^*1쓓JKK,x0$1i?yx5zP.\]]3//-TNyXS읟źnW#_ 0J7kQlEMWEvv6WqL(eT]Kʊ; !'n .!C. ƑYZZ³@۳u,'&&䭳p@)A=aSeGʽIK|4]gU[Kf~c>vuJZ+c toLNjj*proS76mnkVV!tÁK=:q #3|EOݨ)O֯6b8R]~W D ߝ6@<siIENDB`dom4j-1.6.1/docs/images/logos/maven-bulldozer.png0000644000175000017500000001044310242117740021220 0ustar ebourgebourgPNG  IHDRZa xgAMA|Q cHRMz%u0`:o_F pHYs  IDAThZ XTe۞>26+424-$?}}eUdE6UdDAP 3HpDMet= *W}xλ~~sUFD󟵐8oookSSәo2_("M>+mV`Iu &Q=7os\68 C||| Z,;/"bH}&,z fܢY$fLLBS2gޫb bEVNHYM+Fk<Wn,nlv]]i߻,̫۱r|{y.ꄵnhn9sO1==kYH{&gǼKL =cNlx@k`uu )3T$JۄGj#ï,n ?Z`fbQPaM w\'@;PN+..,G7a:76 #g;zQ*LO| 7ok.)nv0u ? ӦM1߅5rٜ%%@Δ K`O`2}-a,0008dPeh@1c g㛇s=\Bc3\N8p ed¬ʘ;O A?`?(ZtaK؆) Cmccð>#n1 vWrqLul!;,H ,dɴ{ k&% 2(dXt٫ tPcPf@WeeFK`"o}%A=%xb4/E{z0Y@rKץ[|}5 d'LLLFJ wct8ePVehcNX 8'Z>t%?+3xn.FqE_;6Cꞣ'O52sL-%pJMREؑ.(p҇nƉxϗwVK`lVRpI }iFD 5} &6ˑYOTv|V R-\9 [#Mm>#rĘ|H߬ V6PYCo ܜ7 ;9HT<%¢ENRi7Ά2 RTqa!@.11,C=m;٨pA و7&`GCoW5<];St [ "@O !.i2-I4_fve1M H:X Go5iyC©)K?3u :[|;p'2-~A11vx*.'bWDSh/T/ qvL\ګt6/a4nԎe`3Kd_+3\?%p#gUl@jPio^zS<?-F%wKIghb^Ǒwd*&S⹊yWNg r1HupJe7JL7q',s~ߐM|-7FH qVH!tBE Dp>JBe8XmT/&}8m ~ٮ[2Vڀg=kif^aʣM1 52 e(62Kb V?C`="\a6{٠,9ui8Y(GrxA m"vk Icq*IgҴpy*3 m.?X`SR><e@S]7o_wkEqnWϠ1[>s] v4EijD"71 Y(s¡=b_lRO_{H \9{%j6No/\9zZ9UizЬ$QU#OsĿеcq5 $lD[mNaճ1C5|4a N:~}|$YFXH!ۋζ8ߥmĩ4qzs6bBF۸W3%v|Lrd$LKIT[g$Hȅ,V(ig,>8A4dV4C|0c_+NIl9q "gAw:Vtj#5y[QXǣ2~KQipgSס2 e^$ܪY cc,/Q adLXGI@4}k<Y.B \UIA[=pE+]< \DdoX`%fkRm(t1_~"7,h¦eoAKy W#PhoSlB#8 D +XPY_+k8\1KN^!":vJ&:9m:,HL>N i8`RuCXڱԧV,5I76w}B+ȷK6 /+ FfTB^@q1ӌ akoJEhn8W()p1NMpj_" ꉔͶȌv@|$xp;jR'^5 ݢ8{89#ȤLn4 '}5qD+8N+xƼ0Z9.Gg nUKR򩴫7 ۬q$M-I;ZA83!7D}@G7Cm ~,h(K@YvCb`OpEe Ib帻wn ] Ry, aAي!>:==uH C6'RR V 嶸\fsBq0Wh*Fc']p,y8ڊXw|;#q2?)8.MGQnPene) \lQ܍7NP sXұ_yT8]jkp#8XvXёþNv\9=#@'xx*Lf '4ZM2 ? 1?-v!L.wT "i]2mP}iB9#&Q8@a R|$LRƸ5$7KǮqLyi# I;b˴INug]9ϢDz'mBz$:*Qj4`Ai)b6"&%|dK -3 'QD+kkd52\=c.MA܅8ORAgްR˂% uT`MHMח v2=f׵93Y̠Oo^0-%>@,̕f&_)ͺRк71af#gk$cㇼH vm 󉃜3En(Ď/?ȌH f[kmD!}}~K^nAJiS6nuyСGS]w; NL8>|tvw\q;mm7ojhyf-ɵnr`1޾!$֘)fBcNfˈ"͖9\c>yYMM@pr{gIENDB`dom4j-1.6.1/docs/images/logos/maven-button-black.png0000644000175000017500000000366210242117702021606 0ustar ebourgebourgPNG  IHDRZ#/sBITO pHYs  ~ tEXtSoftwareMacromedia Fireworks MX*$tEXtCreation Time03/19/03T}IDAThYKK]rJ-M& S$TJ"D"18k JAh8 Q(4䥴M=sZrΫo׻g6& >ho߾]\\/ة_A]VHWl#Y-|JKKɓ'aJ[xl > 2>x={ _߃ޚCIIIo@:vE12F0+F0K{ KA _dH^h_w&!`deje#Ƨ:;A$;p$&&..k7"G@UN)Xme2@v 4!!a홙 h߿06..ݻwONNFU 3$d_~!DBcӦMw,8+**#8؊w[9o; z!xR A D}dҬ3 *|Tb(FKMtQ@q,*I␖A]ɥ)?9;K3uݻmf`#Bo(4"7߻w8%c3HT}}}رCt|Q\@@ki P}5͠AGt,G9tݻw]b 1/_D`pں:Z5Ү ϟ>.EEEl3QW:ñfe?rcL/le)Se-aw^\ث&vHW}׮];w\ף={< Fv7x"sȣ!rO8žW4F2Ӱ$ϟ:s*Ǟ'w]EdG q G6ϳ+Gƀ(IrN[e/ƪK`U*y?#t t-Qֿ2v-^Pyn9F:zLy;$=:o{`G{kjj^{{ߝ蟚~}`pK?ƃ.^HgϞt߹z=$FffyZ]jA)2ԖVJR <3WFDQZR :ܹs𿧧X,bBAbII ;::?\ii)… 333NEzS ɅEL66S-ImcBH-9zÇq>}1haa ϟ?PC Ιf=vahR">Fd11d4^c!p5 ; 'O>zȆG~.EC(GWzӧLhǏ5m_D8/6'T᾵ulBp,-- 1G`?uPl``@0GOa2QTBVVVqvUV@C N P#HI>BdMC r:g`r@v] cFo|lgʤ܌YRẇgd"cccbt֮/mA6V R8eJa'RE.f1v8vA@*08C -S<4Ԍ_G쳼QӔ(/ `~/8zRvL>y>J2fgW?aS2BeD6g92DCyafPFBcx͛7^NRQ #kT8t6#;Sy^N̒jW|I!ά*axԇPڹGIcc #Mleir xtSt/aP%{ckkkmk}uOq@nC'}yF#ڧTLƗ6 ?n1ux2LhwU"cr&_uQ$dKwՌV& 96zwEk&߻wodSS/_Α2e[,w^=la y o񋓳6^IJf:nfcfqxݻ@ v&37xGomߤ KCruHA ;VlR29ԈC#:99?ƫ={ SmD>oݺe;[;JRث(Qt8|L O?~XY_Q"A33l۶oA)gԐnᘟ|'~̯@iU[{AVKU"Ad+Y˅# ǝ;wH= cQIENDB`dom4j-1.6.1/docs/images/logos/maven-button-5.png0000644000175000017500000001070110242117665020676 0ustar ebourgebourgPNG  IHDRZ#/gAMA7tEXtSoftwareAdobe ImageReadyqe<SIDAThYYeU{sPcWUWWUnwvlj1J "xL J$HD! Abplرq<$Cjꪺu=a-ν 9/js[%UϮeUTeݺO^|5.{H@JO~~RVd}|D XĮ6 &ڝIkd4T![ukWqRZ~?{oyˋPSiՃ/j/Cue]no=9Ozw;֭q70"HHbQ;{?/0P<^yiW7+Ï؞j݂|%:`1N>|wf{] j$PB ftǓLK_9}Ë._0 \yk cZ2ʧ&]p^ s=NJ&xx깟0QT "'_85;1"lG/O->,8t敕'}}b03!2R@b؈}(=qeHYzG/]EWHL"D$qZr X֔T;4=A==!CJ!ZҽOߦGnYI")%)11JÓnz1_*t3cyuwj0mn~D\=G'1B170#Ygp kTKf= !ˆ*Q@ALe'K! G&h$a̫W{Uoܻ|]Yf^Ω]K@t9q>qxc%DP˔$#&It'g&;k[ICTvNF}Gn겟dC6pY۱{nJ[),83= ՘)CԸ@ :NRPHTXE%-ȧ\|~c}[juYNۊTɛw372 !@ ("ILVv$ŭjo` W7/{޾smi@yc, 9ϊ$Fu`gSf9s+CR&@ 0Ib"'pX Ƹz^:u-MWnr{Q!uۭV=y?s|#'4EqTᬩhTDQ@EU2bΝX6I">zƻ_9;s$,o]KeQePq6UTˊƤ;G:t",IBT%A /oVD0LeJR:[ooCе^!=]@k;^.6/N"JDDf)dSm# ]ހ9M.#fN0}6<CD[*_ۜH &ʭup8@kg5DQ2"%*DώN)-SELb2FOPf3Teru9.lٿ\IF,m]/ȹ^h ƈdECU%U mgVrdlnrBȹ"7eYn_ݘlg)!*Sr0}5:)("d /rǙAqom ) wGp i&CEqP-e̱+D EIw{Uj^R <11Sӭ_>͜|eR0dQBDV5Q;19>;2J!q0Qcdej )h4l ) ;_;s$ !H\˝u{PÐzmۓ)5U)uTe,3k?5wA{ѤdQCj@89b̄ړI1 ( D&hIk_9 b0S9Ǩc4LJ\Pep1B Ri\OU~}0\.tfX+oUrYUyf) RhZ63U^;oj$5STPDTT;X! ?|_' p8\DʌQyl0a?tfsK?poyaASj\s3e|N|֝H璉D?5fb&b >ĕՇ{عGعebR]}G`W=2R#ỹ >x샇>8;cv<a)98IO_YZ}*PI)+8͗x6^/&տlR3w߀jJ1u5$X{gZ}m__-Y=Хg:z^|++t*c gG9c/=vx/B Dj6XBQ%ULh'cܗJiq.HFG f+JbkU$ @9%)hqxnpF1({>oшoUB4> 4-QahQ cAe+b wq~j׭/: $cLl @Tjze&huL.~ˆq7 "xKjcVj7^sf r:cl&MԴ1C)(*xDG\~+"wh7'} /?>/l_k1F`>ϲV[מb`yu ]Vf3mLFcʳ_[{6^z}zכAU|-4:Ʃg!WMHd4P!3Lm&ZY#I|]DakMv_jM6T]1v@`a2MyHPpR[ۚpc 2l?}4:@"ƴ/ Jw#~$_8QI1`e6t(_{|0:VUhJ*MnrDUD$i"YA$$*BڛL^roEC05IENDB`dom4j-1.6.1/docs/images/icon_warning_lrg.gif0000644000175000017500000000272310242117607020275 0ustar ebourgebourgGIF89a fbd|P]ylexVdzam]yXsTnLcG\|CWu[vWqRjPhNeKaI_H]}DXvb5D[ghprYlu{~—ŝɡ˨ϧάѱ԰ӳյַ׶ֵոؽۿܾ*7IÕŚǟʤͺٹkW?^P?eI+eVFmN/hK-\B(bG+n?j6rJ|Qibgrq|Ҍlyv{䞇ǛТxw!,  HdNeI@ǏHaF`@ .G8q<^f YIT nD#sJN`8T8A`ÊB4 pCbo߿)GO<8UDyܵsɀ˘/qSc|8X7^9wAFylM[8 LK{\`ϝ:ٮM{\̗kc8GiϜ rʤcWNО)u;lqGܸo]%#7d/$@aւ9`5ijQ<*CA@Q f`cM5Șa ܂J#F1 'tr+œ@\A\> xhnj( J*B2"B ()@9hS<фY%r( " )+,@2TAE7X|!v{G CL:NE @Ѕ[݀I+#0C 6АI!p $P |p (,̤;dom4j-1.6.1/docs/images/icon_arrowmembers1_sml.gif0000644000175000017500000000206110242117742021420 0ustar ebourgebourgGIF89a4D[Rj4CY!*8tds^hwgp~ѱԲԽۿܾ7H`=PjŚǺ[jzYjnY[ZTlXC\A>l*6]#`Gfs`TxAd&c&T+r>r?R.Ew(hF= c&a&a&f-i/h0c.j3j4l6i4s;,JxEa"`&_(r?6XTY ](S[(PLq(-OJvN|!1Knjoc#Ed?P 9=wtz~иkc͵jսoηp'D\b«igf  TXrMP`hrFmEnGrJVUU̫lll!,? H*HP> (P aΡ? @H|iH8 ! i` H-'A1]ĉSN0R X02HO^ZRk"MzD)Xt+ VDJ &w;%(a&( "nj)IpĀ^$G!E R2X@@EIO :@00" G\0E@ ANd4i~4K*]ȜQhQ@;dom4j-1.6.1/docs/images/sw_min.gif0000644000175000017500000000005510242117712016241 0ustar ebourgebourgGIF89a!,DP;dom4j-1.6.1/docs/images/nw_maj_rond.gif0000644000175000017500000000006310242117754017247 0ustar ebourgebourgGIF89a!,  ;dom4j-1.6.1/docs/images/poweredby_036.gif0000644000175000017500000000145010242117715017340 0ustar ebourgebourgGIF89af&3f@p0YPsq! ,f&pI8;`(dihľp,ρ;S{5n䁌2[Wc"MfFҘR#F*Tbi[X ڊK Juv7$f}W<VVZ,sA.cBihj Ĭ %  !    #Pw`@\ {U@2&4& Xŗ aX@H N`e,lC*43iFV2L ZЌBہЧ"ZVvC\|8duRԴ )%@@S pVl. -CprN 3fB] B|VqY3;{XjDI5L8"lwZ`ɗ?w,"s dܰ ӳ.gaptL@^RCYBXD=LS]G^@UJbF!H"M%ܶOiT*PjQlPjIaH%Zh]#09L= UqToOi[jXvYxZyJ*Xv`^~e-Jʆ ;T`Ê,][Ī ɾpGW3ok1v4_*5jO1% \(L,ARd(7m=

L3ჺ ^` d<86B aju bq 8D%)} 姀I A"x+L01X 4|L yE䐶`lz!a2C(XuͣEHHHkH0jbCSB~KnCBtkwFÐlMvR P)`B nY7,T1A`z#{u6Oq=~ 8̄HЧE SC{t|-" Trʆ2D BDE$= 1brۄO\vYFTzF\{,0W>3W{1"!ʉ:AD Wr`dH. ^_6J !7"LZ& awf9HP[SG~@ CĒT@?GB(# ddm*Q ZժRh=Zc\!$pp=PlIqĪIOĊ,4)Mn@QX<@hzÒ`DE$lp+{ GH[RW,Iglq$`si |&;dom4j-1.6.1/docs/images/icon_arrowusergroups2_sml.gif0000644000175000017500000000206410242117631022205 0ustar ebourgebourgGIF89aJS SAb.iVm[DCY^#T"[5bFIK /a PR@;%P<} f|T:{:u!=|VNɌwt}{z~̴иkc͵j˳iսoӼnηphǵx՜'D\b«igfWTYrw|ILM}LP`huHrFtHrJya|jZAzTl_KoHwS(QF9]OVK?U*wvsrpvzys_yz"$`8*r4x>zell iwv|'P%Zad}m_WRO]IJKM% FD C<0=%;7 3 2VUUӫlll!,k H",c"a)zb9ya9lY:nV2mU2kT1jZBdM.bM1bM2VUU׫lll!, H`%H$y2pDN J   b&8ƅ(P@ 4|b`>$"g ?,B]lÏ X:h9ϟ?L%^A$p Zl~-nذa3nE.?t%V9Qd(B؀!$H N&UX H3I"AdBǏM9  `3G9ad/WACrD7r0'YCΝy}@;dom4j-1.6.1/docs/images/icon_alert.gif0000644000175000017500000000214010242117637017067 0ustar ebourgebourgGIF89ajg((;;QQ__~~!,jg` dihlp,tmx|pH,#A0h pZV \tZ tiv2 ݂dH^wtGlrHmHewFw@ _ 6  W 1 m+ ¿f  %Т_۬# w  f ͭ[`Pz n IA@kP\[ nD7'hP$[dڥls-Mo,tĈHY2WT1NhItJ6a\$7 A)0j&֩# i6n]ݦhVHegOr4bvJ^}_4WVfG \c2Cv-CI7.j( 6.~:{[os 9.>Y +@{կڏr|(ٿX'v3lO=47< V@`#) 0B_pVy<$a ‰4Ő\ :TX":Ds;d c7CBP =z4†`)K swS$fRa`=f%Hsb &0s͛)i3e .Rw8l^(y yX_#ʐb@ #|z] Em * z&\a(G) ɑa kښ6M`H`[,(*M4$;[~xQ l:V"]N2,tZӎdG!VQ!(/+ [׊"yQJI aƒU%- =n}BbY=0Fg("E է0c ;dom4j-1.6.1/docs/images/icon_waste_lrg.gif0000644000175000017500000000141410242117623017745 0ustar ebourgebourgGIF89a PqRiy~[vYsWqTmRjOfNe_{]x\wWpSkPgMccb~UmQhOeNdgjkppqtu|ÙǗŘŝɜȡ˨ϩϭҬѰӳշ׸ؼھ\uÓßʤ͹؃ɝظѫ!T, TEGD C A F'2CC:?>F:QQ:BXKtx0H%$+jbB_ʐ]1ä# ˜ EaKRZ"1!l̚4a=0?]AJa45tHN)jS$Ԫ 5LWi<vdSTu"%a,l*6]#`Gfs`TxAd&c&T+r>r?R.Ew(hF= c&a&a&f-i/h0c.j3j4l6i4s;,JxEa"`&_(r?6XTY ](S[(PLq(-OJvN|!1Knjoc#Ed?P 9=wtz~иkc͵jսoηp'D\b«igf  TXrMP`hrFmEnGrJVUU̫lll!,? H*HP>3)Q: C1%d !s B3]ypC\СQ=u!'K\j鏟zb9ya9lY:nV2mU2kT1jZBdM.bM1bM2VUU׫lll!, H`%H$y2pDN J   b&x‚T( @iL13R" "r˒+D p0ѥ3#6`1à 蠁fX!xe!  @4\hgϞ? -nذa3ne rJrȊ~QCƑ)H[ p48F(FT c @ ~H"/ R% :~$ƖHeNeL9=NTæ%_FH7r0'5߬!cz^D1;dom4j-1.6.1/docs/images/newwindow-classic.png0000644000175000017500000000166710242117710020434 0ustar ebourgebourgPNG  IHDR Ӻ&tIME 8e1 pHYsiTSgAMA aPLTE0`etRNS A+IDATxc`bbb& L2022"x0s`dZIENDB`dom4j-1.6.1/docs/images/icon_usergroups_sml.gif0000644000175000017500000000200210242117733021043 0ustar ebourgebourgGIF89aJS SAb.iVm[DCY^#T"[5bFIK /a PR@;%P<} f|T:{:u!=|VNɌwt}{z~̴иkc͵j˳iսoӼnηphǵx՜'D\b«igfWTYrw|ILM}LP`huHrFtHrJya|jZAzTl_KoHwS(QF9]OVK?U*wvsrpvzys_yz"$`8*r4x>zell iwv|'P%Zad}m_WRO]IJKM% FD C<0=%;7 3 2!,m HAjD@14N`)kBD< 3><9ŋ+ɱF7L 19PĐc ,M!/eHL%t'G0=jtI`\8PgP F2B$A`PgQ"@ QDg &P?&u 2l ǐ%NBJu >(QVrʖ!HCJRZ%+ ;dom4j-1.6.1/docs/images/nw_med_rond.gif0000644000175000017500000000005610242117562017244 0ustar ebourgebourgGIF89a!,\;dom4j-1.6.1/docs/images/icon_doc_sml.gif0000644000175000017500000000054310242117752017403 0ustar ebourgebourgGIF89aхtWp#.>]y[wYtXsUoJ`\xRjDXvtzŧΩЬѰӳյֶֽۿܾßʣ̢!<,@/Z,&N($lrh[@W'CH`Fhp(i4咉8dVTmo%'d:5 $M2%Nd-4*#N vM.;63 ($ 1N9n%/M)"0/BBA;dom4j-1.6.1/docs/images/nw_min_036.gif0000644000175000017500000000005510242117742016627 0ustar ebourgebourgGIF89a3f!,Q;dom4j-1.6.1/docs/images/icon_sortup.gif0000644000175000017500000000016510242117652017316 0ustar ebourgebourgGIF89aj?S-Z}ZJt)!,"I8ͩql!AXIZVGmn<;dom4j-1.6.1/docs/images/sw_med_rond.gif0000644000175000017500000000005610242117677017260 0ustar ebourgebourgGIF89a!,DnP;dom4j-1.6.1/docs/images/icon_members_lrg.gif0000644000175000017500000000304210242117724020255 0ustar ebourgebourgGIF89a! 燱ԋDXv]]b&2CXsSlRk^zWqH]}EYxdhz˧βԷ׶ֽ۲߹Ўtɣ̺ٞvyz⢦iT^sNq/-//.37<>CEKn9PVT\\e|TczKeՊgxUy}*{),~+|*8EITb8_mr}w%{(y'x&z(}-}.2:MR[`etxLUAu$t#r"u$t#s#v%w'z,j(~5FYjpr!p o q!q"t'>Rbmnu*Ekiw/Wq(ghy4eg"ca|_w_yvX^t]q[len;UcFK~HMW\*GJxylHKEFFF?>lhNutsۀ}{yxx܁иkʳhȰgԼnѹl͵jrӼnb^[ªdaŭfWKyGOMqAzf?k?lAoX4eM-e\P!,!  Hq@Wd`Ae5q"x>yEV`rxAMa$9JHD ;4QTX! sB!\r &t7RHFmQp bI!„ V:RYk1~H Tʥp =Yq!zAy(҈$P (b BYh!~q"8ˆ&|b* C :@ Ђ\B#tI) + +.B0{jvI)+B .@j $0I#k.hpmd "! JH" 1L/4P38 ]!P?PvIX0 sDwwA;dom4j-1.6.1/docs/images/strich.gif0000644000175000017500000000005310242117747016247 0ustar ebourgebourgGIF89a!, ;dom4j-1.6.1/docs/images/icon_info_sml.gif0000644000175000017500000000113610242117705017566 0ustar ebourgebourgGIF89ar 'SG]}]yVpOgLcJ`EYxCWtI^~FZyehgjlmpXltvdyw|~wunzw…ǘƂ˦ΩЭҬџ԰ӵָؼݲ@TpAUqy}ŞɧŹ!r,r`fg`l\d LG^qqopnQmbj.MObhNgr\oP6 [ig%dmE4k_^eL PRah YcHBjfV F`\- 5Z=97D`] I' 130@KICA@,"c $XA ?tr兊!8h2† @Pab ;dom4j-1.6.1/docs/images/icon_alertsml.gif0000644000175000017500000000023210242117716017601 0ustar ebourgebourgGIF89aӯz{{aaj__! ,GLFU6*J|޼He" q a, r0b)ϖ;dom4j-1.6.1/docs/images/icon_members_sml.gif0000644000175000017500000000177710242117702020275 0ustar ebourgebourgGIF89a4D[Rj4CY!*8tds^hwgp~ѱԲԽۿܾ7H`=PjŚǺ[jzYjnY[ZTlXC\A>l*6]#`Gfs`TxAd&c&T+r>r?R.Ew(hF= c&a&a&f-i/h0c.j3j4l6i4s;,JxEa"`&_(r?6XTY ](S[(PLq(-OJvN|!1Knjoc#Ed?P 9=wtz~иkc͵jսoηp'D\b«igf  TXrMP`hrFmEnGrJ!,3 HA JG p 6n!BcN<2mp@ :4 72?yG 2` =RqMI(z4+Zh"%L<^RB "Bx̘ N uƒA12X@@E pǑ(Wl#&2!HI,^1&MALc҅5;dom4j-1.6.1/docs/images/icon_arrowfolderclosed1_sml.gif0000644000175000017500000000067110242117717022442 0ustar ebourgebourgGIF89a뀀יވً|vutqվo}x{~ك{̴ipѹlϷkɱhsӼnl„`]ZŭecOWT}IwFLoBh=u^7jR0VUUmmm!;,pH,HQ(V0;oPaaPZ(q -#L q0$+_sP(w D722E, & 0_C,x2;!&' "q:;#+'C7B1' "#3_t4+ &15,rt;/+-4ha `ԸF4D Za;dom4j-1.6.1/docs/images/icon_arrowfolderopen2_sml.gif0000644000175000017500000000123010242117725022122 0ustar ebourgebourgGIF89a!י}~ً|vutqվo}x{tكӂ{̴ipѹlϷkɱhsӼnDznlijzż`]ZŭecOWT}IwFLoBh=u^7jR0VUUmmm!C,!C.-,,"!0C0 )*,30%/1 52 !/6,-44C?>1 "$56-#-'>=88Bׄ2014<+ h.^( Q*X>@Gh 6& 1@:.A=I0EA^?&;dom4j-1.6.1/docs/images/icon_confirmsml.gif0000644000175000017500000000013610242117737020135 0ustar ebourgebourgGIF89a!,/+(7`נꙆ+BBZ";dom4j-1.6.1/docs/images/product_logo.gif0000644000175000017500000000125010242117636017450 0ustar ebourgebourgGIF89a3f5]u! ,I8ͻ`(dih,Am}/υ0Hlv$1cS*'Jt {2DSOK MBcuTwM}%O k2 {B10b/g[n1{f V&^PrfbOCh BŚxCJ&J1̼P [gz F AfY#O$cC`L=D<ŒI Q T,Y8S&O`{ӂ]FM0cLn%)҃G;0mR-zÂY&])tG !pY!miE8gP e*{4i6YCG]o 9"_QNr,Wn쵲O,KS$s+f?ZOX-\T 0Mdh(iL./UeV5sn@bUд1vht СklO%DUmM M'AwuLE쀍I:C a}2G(@%9J.FprN3Ovx{@-EL6RO8V08G3O1:bGm3=4>7 C5AgOx?2ME7TmW|d}gu^V!,; H AJgN޴Yc* FrM/]HIh $5iΌ %BT 0P8$2,ㅋ,Z(DL@;Gk$<Hd >`'!\2?vhp  u@ .X = q0 )f$Tp"FQGr̉C;dom4j-1.6.1/docs/images/icon_help_sml.gif0000644000175000017500000000177310242117744017575 0ustar ebourgebourgGIF89a~K|sH~݁{ۃ*$6/KB"bW/aV/HRSWW}{wuttq[݁~}|{zyyxwvuuƱh܁ڀ}zw܂<4dW/rd8~GSζjʳhȰg`qpҺmйl͵j˳icr׿pӼn4,Y[Xb`_]\ZƮfŭeªdǯgXWVUTSRQPYwEJ}I{HN~J|IOMuDqBn@m@yG{d:k>|e;rZ4x`8t]6jS0nV2qY4iR0X@&!,5JF7pرBF6.H( :F` $Xx@aB AftltA &@DH 7s4!" $?h#"2f*W¡  F݈Ds ,;dom4j-1.6.1/docs/images/icon_sortdown.gif0000644000175000017500000000016510242117710017634 0ustar ebourgebourgGIF89aj?S-Z}ZJt)!,"I8뽅QAE1qk檬\|E;dom4j-1.6.1/docs/images/folder-open.gif0000644000175000017500000000034510242117565017167 0ustar ebourgebourgGIF89a fffvvv! ,pIx ! 0d@ @:m.4R @ @ЂJ CPD%l "(`@@ {Ԑ괶uNo lO)L&s# !PxYE<'M4%w LB|;dom4j-1.6.1/docs/images/add.gif0000644000175000017500000000031710242117705015500 0ustar ebourgebourgGIF89a*|~Η0XpN>tA9CGOs+ج!,|I8kl_@4DJ,l Ѡ*e|q8HH ET8(`"B`A`iM0[!KǸ|NianVXp\ KXDNNRmKcEXcJn#;dom4j-1.6.1/docs/images/icon_success_sml.gif0000644000175000017500000000173610242117562020312 0ustar ebourgebourgGIF89aΧμc~w˗éSq*/%(#8='*!37,/(CH'AF&>B/2*,)FI"!PrkjtŲFcO7G;ȝȣ֩۴߲2B.ᥳ⦷㫸䬸䭺导屏€㩲ࢲࣜΈޘܙٗۗ]B΅ԋۑ̈́՗]>Ԅሻfrmjb7Jw*U0W2im;Ag$r?o=e8f8b7Z2Y1S.Jt)Qy1WYuQeFcE{{hGv@u?k:h7`3Jr(E^3Q|,S~-Dh%}DEi&QŢIm&Qx+Ot)Mo(Ll&Ig%Gc$!, HA!,XE aCF5pAƏ *01#"NT0A=Y& NRI1bJ':o8b3-e˓у>|¥ (qŋ4hԱ(ЋmT"J;*d("4lp ,P( ;dom4j-1.6.1/docs/images/icon_sortright.gif0000644000175000017500000000017210242117717020007 0ustar ebourgebourgGIF89aj?S-Z}ZJt)!,'IW`+Φ}@fE[ =d[;dom4j-1.6.1/docs/images/nw_min_hi.gif0000644000175000017500000000005610242117666016725 0ustar ebourgebourgGIF89a!,sP;dom4j-1.6.1/docs/images/icon_infosml.gif0000644000175000017500000000011510242117760017424 0ustar ebourgebourgGIF89a !,  wlzO=wiXMbL[;dom4j-1.6.1/docs/images/icon_folder_sml.gif0000644000175000017500000000117210242117647020113 0ustar ebourgebourgGIF89aـ{~r}|wvuts~}|zyxxwtиkζj̴iʲhȰgcq־oԼnӻmѹl͵j˳irսoӼnb\[aa``__^]]\[ƮfŭeĬeëdyOPWVUTTSRRPNYXwEJ}IMK|IO}\oAtDpBoAm@yGi=j>zb9ya9lY:nV2mU2kT1jZBdM.bM1bM2!|,׀eJHHIO|#!:N|_ UH`@F78b7 * 4i_Sf$A"%4?_KWD&]|g#XF;* f|W#B   4.Z|[#-7#)371?\|U'E+(!602GSH|40p N&UX!xxB$H,TADeNeL9=ad/WAȑ9GhGJ͚o֐sQ/z;dom4j-1.6.1/docs/images/sw_maj_rond.gif0000644000175000017500000000006310242117677017260 0ustar ebourgebourgGIF89a!, D~Κ;dom4j-1.6.1/docs/images/icon_usergroups_lrg.gif0000644000175000017500000000276010242117760021047 0ustar ebourgebourgGIF89a 燦  k @C_e&,2&6ഺ4J]h>XN&Mg]|tfbdb`arIjzgJ2M5= 'SG]~\wRipƣ̱Ծ.?S,0FkDؕ߬ȓvtN s?wDairBVq;ZXcn8P;{k3\;hg.Mh2x[opnFhd):PnX|}y}~mڎݮ鷈}njB@0*&ƸxٞMD%r|ueۀxƱh߃иkȰgpԼnѹl˴iӼni{'Db`^[ƮfĬeªdRQNLV|IOsCm@^T?{_wb>;/{_(o-],\rtz9LޓPn@xJvګ͸aiemlx%ۀ2܇=ۋHZ<#ؓYenM1fM~wp\> OaXdr)w6ӈOە_ǐekwme۷SXG'h&l4{D~L W"k:D ĀZ9W"@_?/1S(z!:??fff!,  H*\ȐL2Y4BO3`@M4 .^(dA~ 8̙p-tiӢJ菡Ho)5!' AeN%>D RQu3L 1/y@zh^XBxѠm^7JYAvv< ޾lR (L|2Y'š:j4SBs'~EYZN)6$F~ PѨzh>9j!Q*-r*>:Uԩ4ʔ-ӢPODeޔTL?].,P?X6D2B -1?2 O6E?E',ޢ?V!t:C b0-4٤.hDA# I,F^x13 1R1XsiC<St,BK,RK09L8Tch5D8 DD+yRK 0L)5Ԅ#8H? :J //@#7k2HCC$qıP/é14 7l 9ؒLADDN S1Lͻ#:3NJ;O8G/F;mی9鸣0<ܳHB,o: <ē?WhqOTDLDQ ŔM7o!S AW'gc';ﰓM$TOtH;dom4j-1.6.1/docs/images/expanded.gif0000644000175000017500000000006410242117701016533 0ustar ebourgebourgGIF89a! , j ;dom4j-1.6.1/docs/images/external.png0000644000175000017500000000034610242117744016616 0ustar ebourgebourgPNG  IHDR Ӻ&gAMA7tEXtSoftwareAdobe ImageReadyqe< PLTEuuuPtRNS@*PIDATxb`&& @ P6#@ `XĆ2 d@A3 ( *tIENDB`dom4j-1.6.1/docs/images/fix.gif0000644000175000017500000000026510242117743015542 0ustar ebourgebourgGIF89a-H/Ʊ8)&#騦rT:$TRTxwv!,b9 ^+_'nYE1REAeWܮQ!{pKe0`!5 VJ`Q7  );dom4j-1.6.1/docs/images/help_logo.gif0000644000175000017500000000410110242117707016715 0ustar ebourgebourgGIF89a4111mb6a䅳_܅ߍ! 1*KB!_T,^S,ZP*OF%SJ'dY0nb5l`4h]3yCi]4|EK~GzDwk|e;x`8t]6r[5{c:w_8nV2qY4ȼ}}}pppcccWWWJJJ>>>!,4 H*\ȰÇ#JHŋ3jȱǏ CIɓ(S\ɲ˗0cʜI͛8sɳϟ@ JtKa6TɑK IBHHEwZ `( 44TVbHH@B xEA=|AFۚ_^(` mɣgӤLH(؀"ɕ-cFO5<ˬ@ 0BDА#VXVfa0-Y!j&K$lB'PON ~bswy{GrŐMkзysˤm\7_.I 1XtJpӍ~qxI E uKx N\A EGmaِe#7l 9`c,)r 1!r<1vdFA9q39shĊ >drI!%qG_R#ŒyAPZ73Jp׭!tTd0uT(zФe*pR()qtXlXH$Tc*qj4d^ zUA77Iݔ{.BvHκ6߈#7ꍾ{)rqpa$tH'ɀ;ݔ3M $l<8$I豙tq9 1cIct<2"I(<3"Nja8+8b9$$8#'6**8]3q8p㦬FvmcmDr 3G#=!;6!=6\M!fMP[N6rp]|H%1У'Ҍ NNڬi7d.D@aLw]xaz%PM"z.貌Qh9/NȎ.zA`s$2Q.L!Sq+P QE,dROlԧM.x $x?mDȳ2NbUT'L@ɂˆBP%65YQ͑aP~d"n%.@DokgQ fT!4f~-8|xC ~kc,1 ^43q dLp 9FǕ##Q|? h?+2鍐 f$FhB )Hh^a cpd$5Aqs&Ւ(k!I8)#HB͓XpLڸbXDLYO\f?ρՉڙІ: ;dom4j-1.6.1/docs/images/icon_help_lrg.gif0000644000175000017500000000261210242117600017546 0ustar ebourgebourgGIF89a mb6a䅳_܅ߍ! 1*KB!_T,^S,ZP*OF%SJ'dY0nb5l`4h]3yCi]4|EK~GzDwk|e;x`8t]6r[5{c:w_8nV2qY4!,  Hv"IQ$C}zp % 8РA %?|!`Hu#8H+~ٳ̙5zqB *jHO=CE*L0Ubz+>idh(2D#UںMFMR*r## `n5[^ltaR$rs Cm_OIi6nhA X"'acd1}p-t eF+s,H7\ulljd%u#IT)zlEϟJHt' #rP"1 ejDY TQUb1yofGDvd1 %<0 Fd\R%*s)5noQQ$&ɈF*ׅd4r"'0s-k`w!QI($s+G|L""@ tAE|NBdL r 2Hr*b'R-('E.fgh2/t!*,$#MGK/K.(sk'.3 1Ō,`0~kn3ܢVC,j32 4$DQ@;dom4j-1.6.1/docs/images/file.gif0000644000175000017500000000023010242117677015671 0ustar ebourgebourgGIF89a  鯯333! , EHr#iDp$(16H` Hnr lIraL.";dom4j-1.6.1/docs/images/icon_arrowwaste2_sml.gif0000644000175000017500000000114110242117723021107 0ustar ebourgebourgGIF89a4W냗Ӱ`}\xPhEYxbUn`{hjlkyƗŝɧΩЭҫб԰ӲԳյֶּڿcǟʮҹVUUlll!O,O'!!;< F 3/6)BA+ 817*+?C77D6KJ*5C%9JIILLMMN 11,(:J؆)72#"م8C-:JM Xw `6LxP+҂ˀ!.9ЃGC`)"'QF9P ;dom4j-1.6.1/docs/images/icon_doc_lrg.gif0000644000175000017500000000246710242117617017403 0ustar ebourgebourgGIF89a ]y[wYtXsUoSlOgLcJ`G\|CWua~ZuWqRjQiPhNeMdKaI_H]}DXv?Rm5E\bUnLbI^~6F]3BXhgmprtwz{~’ØƗŝɜȡ˦ΨϧΩЭҬѫб԰ӲԳյַ׶ָؽۼڿܾ^{*7IcÕŔĚǟʞɤ̢ͣˮҺٹ!, + H+A9`0#B #% v 1 AE\ R %`D c8qDdELuP.aI"DPJ =|fdlJ σ`zH Pxl5[ #Rp3ċڄ\ ˷/'y\A.S)I$PLLre2쀜8|:Rƍg Hq4Hx?nA8q;vAPA& {"5zA:iի[>M ȟnӘ"@ *pV/\90]U$#҇!,dхYwlWL@FGH"h^lGSD#Cˑd$" Ca||X!O,GGD)jajGdCi WPEL$t1@t  !8$t1@0cN,jE!Dp !dd `@HЁ|@(P (k%;dom4j-1.6.1/docs/images/nw_min.gif0000644000175000017500000000006310242117713016234 0ustar ebourgebourgGIF89a!,-!R;dom4j-1.6.1/docs/images/rss.png0000644000175000017500000000037110242117704015575 0ustar ebourgebourgPNG  IHDR"MD.tEXtCreation Timejeu. 8 juil. 2004 00:26:46 +0100tIME,h pHYs  ~gAMA a PLTEffff/bSp9IDATxc`qv@t&8` Fbч AU#iE3:SOx?#USIENDB`dom4j-1.6.1/docs/images/icon_arrowusergroups1_sml.gif0000644000175000017500000000206010242117723022202 0ustar ebourgebourgGIF89aJS SAb.iVm[DCY^#T"[5bFIK /a PR@;%P<} f|T:{:u!=|VNɌwt}{z~̴иkc͵j˳iսoӼnηphǵx՜'D\b«igfWTYrw|ILM}LP`huHrFtHrJya|jZAzTl_KoHwS(QF9]OVK?U*wvsrpvzys_yz"$`8*r4x>zell iwv|'P%Zad}m_WRO]IJKM% FD C<0=%;7 3 2VUUӫlll!,k H",c" #"U$d̓Zcظq`B.JhB@X8s|EP *hHsĈ1 |ʕ,YfI͒ / a zu5_hӃ3a18V*UY@KSL!Dw]@H`?|-$hP(@v #HoP*Ѐ r ʣ#L \B  %NHBaC>atiSQNRV  F N%PPb* ;dom4j-1.6.1/docs/images/icon_folder_lrg.gif0000644000175000017500000000301410242117714020074 0ustar ebourgebourgGIF89a ߭׈ܑܓٓߪڴچ֍ԌˉǽwyLjʜ䈾puzۂr}|{wvuttssۀۀ~}|{zzyyxxwvڀиkζj̴iʲhʳhɱgȰgǯfcqp־oԼnӻmҺmѹlϷk͵j˳irq׿pսoӼnYb[Zbaa`__^^]]\[ƮfŭeĬeëdªdOWVUUTSSRQY|zGwEJxFM~JLKxuDsCqBoAn@xFvEpBoAm@yGʁɀg<}f;{d:k>i=~f<|e;l?j>rZ4s\5r[5{c:ya9kT1fN.٪vԠt節|ަ{ۢyߢ|ߞ}~桂ܛ|!,  Hʳg>n"=m ظCHadHԨM N\iQJ$yѣPtLh@B.6>hybTyL5p]ŠCB N,\ɲE#JLQo [e 2fȑ!+@ "Af ԂGl1wzI+8:Ј+Y1FB@r@l152Elxaod \@ƒXQ/P FFH$#w.Q5Ҙ w}ыA%*huRK~2CeqVWlGqCH2cPF&!grԑA&fT1EoaP'Ё .(AaWg\Bs`r-E&,)UaFXlȚn!bGek|h&4.-hjDxP pڱH'(3`_ZH!Hp  2X 0\la hH.Ǥb@ x BA%|2L2\<*RC~!%b ,*J,o G#K0A\"tRL2} Xr""-ŞhM@;dom4j-1.6.1/docs/images/pdf.gif0000644000175000017500000000166610242117723015531 0ustar ebourgebourgGIF89a  ?&#"5*++A:@1G8Z>ecGJ^O[bhaeqmw~zxr5' ,942&(ITBYWL\O^]HHMTWa[jLa_t`MdYarfpffinayrz~xwvKOMSKPKQPKPJ^ZCgrqvxsyzws}̉oσưЀӇ݁܊ډވًݐӜݙٞڗۧߧܮνئޡؽ珍툎鎝钘䟤䪞릟梡楫䮢꯱ೠⳡ簩꽸ôƶ!,  8cA*rE 5A.^`ɓw&`s)yBh˴5]LJ0 cU*a Ac!;=iQ R7*SAb([m4@slQ1Opę#D%  ;dom4j-1.6.1/docs/images/icon_info_lrg.gif0000644000175000017500000000254710242117727017572 0ustar ebourgebourgGIF89a Um 'S(Bi+Fm6OsG_H^H^_|]yYtVpSlRkLcJ``}XrRjQiOfNeMdH]}bLbI^~egjlmoWlpqtuzg|{~luxzt~wz’Å|ǘƗŗÝɜȐ˕ΨϧΩМѫС±԰ӲԳյֶ֧Ÿؽۼڬȯʭȿ߸\xco}Ŕǃʤ̢ͣˮҤúٹدɮȳ!, k H*\ȰBqsGΜ:qAL10*Rʚ5`'B8NJ)`%K)j(%|ҩrOvJUL:eO4h0!PTӍtx%KBŊ*WDƑ5w'էW88'PZ9hH-T72kKSChS8h ̪`bMLRAd0S-:mAdom4j - Issue Tracking

MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
    • Mailing Lists
    • Project Team
    • Dependencies
    • Source Repository
    • Issue Tracking
  • Project Reports
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Issue Tracking

http://sourceforge.net/tracker/?group_id=16035


2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/cvs-usage.html0000644000175000017500000001673310242117730015606 0ustar ebourgebourgdom4j - CVS
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
    • Mailing Lists
    • Project Team
    • Dependencies
    • Source Repository
    • Issue Tracking
  • Project Reports
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Web Access

http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/dom4j/dom4j/

Anonymous Access with Maven

This project's CVS repository can be checked out through anonymous (pserver) CVS with the following instruction on a single line.

          maven scm:checkout-project
            -Dmaven.scm.method=cvs
            -Dmaven.scm.cvs.module=dom4j
            -Dmaven.scm.cvs.root=:pserver:anonymous@cvs.sourceforge.net:/cvsroot/dom4j
            -Dmaven.scm.checkout.dir=.
        

Anonymous CVS Access

This project's CVS repository can be checked out through anonymous (pserver) CVS with the following instruction set. When prompted for a password for anonymous, simply press the Enter key.

cvs -d :pserver:anonymous@cvs.sourceforge.net:/cvsroot/dom4j login

cvs -z3 -d :pserver:anonymous@cvs.sourceforge.net:/cvsroot/dom4j co dom4j

Updates from within the module's directory do not need the -d parameter.

Developer Access with Maven

Only project developers can access the CVS tree via this method. Substitute username with the proper value.

          maven scm:checkout-project
            -Dmaven.scm.method=cvs
            -Dmaven.scm.cvs.module=dom4j
            -Dmaven.scm.cvs.root=:ext:username@cvs.sourceforge.net:/cvsroot/dom4j
            -Dmaven.scm.checkout.dir=.
            -Dmaven.scm.cvs.rsh=ssh
        

Remember to replace 'username' with your actual username on cvs.sourceforge.net.

Also change ssh in maven.scm.cvs.rsh=ssh to the name of your ssh executable.

Developer CVS Access via SSH

Only project developers can access the CVS tree via this method. SSH1 must be installed on your client machine. Substitute username with the proper value. Enter your site password when prompted.

export CVS_RSH=ssh

cvs -z3 -d :ext:username@cvs.sourceforge.net:/cvsroot/dom4j co dom4j

Remember to replace 'username' with your actual username on cvs.sourceforge.net.

CVS Access behind a firewall

For those developers who are stuck behind a corporate firewall, CVSGrab can use the viewcvs web interface to checkout the source code.


2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/xref-test/0000755000175000017500000000000012133227266014741 5ustar ebourgebourgdom4j-1.6.1/docs/xref-test/overview-frame.html0000644000175000017500000000400510242117750020557 0ustar ebourgebourg dom4j 1.6.1 Reference

All Classes

Packages

  • org.dom4j
  • org.dom4j.bean
  • org.dom4j.datatype
  • org.dom4j.dom
  • org.dom4j.dtd
  • org.dom4j.io
  • org.dom4j.rule
  • org.dom4j.swing
  • org.dom4j.tree
  • org.dom4j.util
  • org.dom4j.xpath
dom4j-1.6.1/docs/xref-test/allclasses-frame.html0000644000175000017500000003113310242117755021046 0ustar ebourgebourg All Classes

All Classes

  • AbstractDataTypeTestCase
  • AbstractTestCase
  • AddAttributeTest
  • AddNodeTest
  • AttributeDeclTest
  • AttributeDetachTest
  • AttributeTest
  • AutoSchemaTest
  • BackedListTest
  • BadPathTest
  • BeansTest
  • BooleanTest
  • CDataTest
  • CloneTest
  • ContentTest
  • CopyTest
  • DOMReaderTest
  • DOMTest
  • DOMWriterTest
  • DTDTest
  • DataTypesTest
  • Datatype2Test
  • DefaultDocumentTest
  • DefaultElementTest
  • DetachTest
  • DispatchHandlerTest
  • DocTypeTest
  • DocumentSourceTest
  • ElementByIDTest
  • ElementDeclTest
  • EmbeddedHandlerTest
  • ExternalEntityDeclTest
  • FilterTest
  • GetPathTest
  • GetQNamesTest
  • GetXMLEncodingTest
  • HTMLWriterTest
  • IndexedElementTest
  • InternalEntityDeclTest
  • IsTextOnlyTest
  • IteratorTest
  • LineFeedTest
  • MakeElementTest
  • ManualSchemaPrefixTest
  • ManualSchemaTest
  • MatrixConcatTest
  • MergeTextTest
  • NamespaceCacheTest
  • NamespaceTest
  • NamespacesTest
  • NodeTypeNameTest
  • NormalizeTest
  • NullAttributesTest
  • NumberTest
  • ObjectTest
  • ParentTest
  • ParseTextTest
  • PerThreadSingletonTest
  • PrefixTest
  • PriorityTest
  • ProcessingInstructionTest
  • RoundTripTest
  • RuleTest
  • SAXContentHandlerTest
  • SAXReaderTest
  • SchemaParseTest
  • SelectSingleNodeTest
  • SerializeTest
  • SetContentTest
  • SetDataTest
  • SetTextTest
  • SimpleSingletonTest
  • SortByTest
  • StaxTest
  • StylesheetTest
  • SubstringTest
  • TableModelTest
  • TextTest
  • ThreadingTest
  • UriMapTest
  • UserDataTest
  • ValidationTest
  • ValueOfTest
  • VariableTest
  • WriteUnmergedTextTest
  • XMLResultTest
  • XMLSpaceAttributeTest
  • XMLWriterTest
  • XPP3ReaderTest
  • XPathBugTest
  • XPathExamplesTest
  • XPathTest
  • XSLTTest
dom4j-1.6.1/docs/xref-test/stylesheet.css0000644000175000017500000000243410242117721017640 0ustar ebourgebourg/* Javadoc style sheet */ /* Define colors, fonts and other style attributes here to override the defaults */ body { background-color: #fff; font-family: Arial, Helvetica, sans-serif; } a:link { color: #00f; } a:visited { color: #00a; } a:active, a:hover { color: #f30 !important; } ul, li { list-style-type:none ; margin:0; padding:0; } table td{ padding: 3px; border: 1px solid #000; } table{ width:100%; border: 1px solid #000; border-collapse: collapse; } div.overview { background-color:#ddd; padding: 4px 4px 4px 0; } div.overview li, div.framenoframe li { display: inline; } div.framenoframe { text-align: center; font-size: x-small; } div.framenoframe li { margin: 0 3px 0 3px; } div.overview li { margin:3px 3px 0 3px; padding: 4px; } li.selected { background-color:#888; color: #fff; font-weight: bold; } table.summary { margin-bottom: 20px; } table.summary td, table.summary th { font-weight: bold; text-align: left; padding: 3px; } table.summary th{ background-color:#036; color: #fff; } table.summary td{ background-color:#eee; border: 1px solid black; } em { color: #A00; } em.comment { color: #390; } .string { color: #009; } div#footer { text-align:center; } #overview { padding:2px; } hr { height: 1px; color: #000; }dom4j-1.6.1/docs/xref-test/overview-summary.html0000644000175000017500000000665210242117744021177 0ustar ebourgebourg dom4j 1.6.1 Reference
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

dom4j 1.6.1 Reference

Packages
org.dom4j
org.dom4j.bean
org.dom4j.datatype
org.dom4j.dom
org.dom4j.dtd
org.dom4j.io
org.dom4j.rule
org.dom4j.swing
org.dom4j.tree
org.dom4j.util
org.dom4j.xpath
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref-test/index.html0000644000175000017500000000134610242117757016744 0ustar ebourgebourg dom4j 1.6.1 Reference <h1>Frame Alert</h1> <p> You don't have frames. Go <a href="overview-summary.html">here</a> </p> dom4j-1.6.1/docs/xref-test/org/0000755000175000017500000000000010242117544015524 5ustar ebourgebourgdom4j-1.6.1/docs/xref-test/org/dom4j/0000755000175000017500000000000012133227266016545 5ustar ebourgebourgdom4j-1.6.1/docs/xref-test/org/dom4j/CloneTest.html0000644000175000017500000003741610242117734021343 0ustar ebourgebourg CloneTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.Comparator;
13  
14  import org.dom4j.dom.DOMDocument;
15  import org.dom4j.dom.DOMDocumentFactory;
16  import org.dom4j.util.NodeComparator;
17  
18  /***
19   * A test harness to test the clone() methods on Nodes
20   * 
21   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
22   * @version $Revision: 1.6 $
23   */
24  public class CloneTest extends AbstractTestCase {
25      private Comparator comparator = new NodeComparator();
26  
27      public static void main(String[] args) {
28          TestRunner.run(CloneTest.class);
29      }
30  
31      // Test case(s)
32      // -------------------------------------------------------------------------
33      public void testBug1148333() {
34          DOMDocumentFactory factory = (DOMDocumentFactory) DOMDocumentFactory
35                  .getInstance();
36          DOMDocument doc = (DOMDocument) factory.createDocument();
37          Element el = doc.addElement("root");
38          el.addNamespace("pref2", "uri2");
39  
40          DOMDocument clone = (DOMDocument) doc.cloneNode(true);
41          
42          assertNotSame(doc, clone);
43          assertNodesEqual(doc, clone);
44      }
45  
46      public void testElementWithNamespaceClone() {
47          Element element = DocumentFactory.getInstance()
48                  .createElement("element");
49          element.addNamespace("prefix", "uri");
50          Element clone = (Element) element.clone();
51  
52          assertNotSame(element, clone);
53          assertNodesEqual(element, clone);
54      }
55  
56      public void testDocumentClone() throws Exception {
57          document.setName("doc1");
58  
59          Document doc2 = (Document) document.clone();
60  
61          assertNotSame(document, doc2);
62          assertNodesEqual(document, doc2);
63      }
64  
65      public void testAddCloneToOtherElement() {
66          DocumentFactory factory = DocumentFactory.getInstance();
67          Document doc = factory.createDocument();
68          Element root = doc.addElement("root");
69          Element parent1 = root.addElement("parent");
70          Element child1 = parent1.addElement("child");
71  
72          Element parent2 = (Element) parent1.clone();
73          root.add(parent2);
74  
75          assertSame("parent not correct", root, parent2.getParent());
76          assertSame("document not correct", doc, parent2.getDocument());
77  
78          Element child2 = parent2.element("child");
79  
80          assertNotSame("child not cloned", child1, child2);
81          assertSame("parent not correct", parent2, child2.getParent());
82          assertSame("document not correct", doc, child2.getDocument());
83      }
84  
85      public void testRootElementClone() throws Exception {
86          testElementClone(document.getRootElement());
87      }
88  
89      public void testAuthorElementClone() throws Exception {
90          testElementClone((Element) document.selectSingleNode("//author"));
91      }
92  
93      public void testRootCompare1() throws Exception {
94          Document doc2 = (Document) document.clone();
95          Element author = doc2.getRootElement();
96          author.addAttribute("foo", "bar");
97  
98          assertTrue("Documents are not equal", comparator
99                  .compare(document, doc2) != 0);
100     }
101 
102     public void testRootCompare2() throws Exception {
103         Document doc2 = (Document) document.clone();
104         Element author = doc2.getRootElement();
105 
106         author.addText("foo");
107 
108         assertTrue("Documents are not equal", comparator
109                 .compare(document, doc2) != 0);
110     }
111 
112     public void testAuthorCompare1() throws Exception {
113         Document doc2 = (Document) document.clone();
114         Element author = (Element) doc2.selectSingleNode("//author");
115         author.addAttribute("name", "James Strachan");
116 
117         assertTrue("Documents are not equal", comparator
118                 .compare(document, doc2) != 0);
119     }
120 
121     public void testAuthorCompare2() throws Exception {
122         Document doc2 = (Document) document.clone();
123         Element author = (Element) doc2.selectSingleNode("//author");
124 
125         author.addText("foo");
126 
127         assertTrue("Documents are not equal", comparator
128                 .compare(document, doc2) != 0);
129     }
130 
131     protected void testElementClone(Element element) throws Exception {
132         Element element2 = (Element) element.clone();
133 
134         assertTrue("Returned a new Element", element2 != element);
135         assertNull("New element has no parent", element2.getParent());
136         assertNull("New element has no Document", element2.getDocument());
137 
138         assertTrue("Element fragments are equal", comparator.compare(element,
139                 element2) == 0);
140     }
141 }
142 
143 /*
144  * Redistribution and use of this software and associated documentation
145  * ("Software"), with or without modification, are permitted provided that the
146  * following conditions are met:
147  * 
148  * 1. Redistributions of source code must retain copyright statements and
149  * notices. Redistributions must also contain a copy of this document.
150  * 
151  * 2. Redistributions in binary form must reproduce the above copyright notice,
152  * this list of conditions and the following disclaimer in the documentation
153  * and/or other materials provided with the distribution.
154  * 
155  * 3. The name "DOM4J" must not be used to endorse or promote products derived
156  * from this Software without prior written permission of MetaStuff, Ltd. For
157  * written permission, please contact dom4j-info@metastuff.com.
158  * 
159  * 4. Products derived from this Software may not be called "DOM4J" nor may
160  * "DOM4J" appear in their names without prior written permission of MetaStuff,
161  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
162  * 
163  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
164  * 
165  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
166  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
167  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
168  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
169  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
170  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
171  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
172  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
173  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
174  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
175  * POSSIBILITY OF SUCH DAMAGE.
176  * 
177  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
178  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/CopyTest.html0000644000175000017500000002565110242117650021210 0ustar ebourgebourg CopyTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.List;
13  
14  /***
15   * A test harness to test the copy() methods on Element
16   * 
17   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
18   * @version $Revision: 1.3 $
19   */
20  public class CopyTest extends AbstractTestCase {
21      public static void main(String[] args) {
22          TestRunner.run(CopyTest.class);
23      }
24  
25      // Test case(s)
26      // -------------------------------------------------------------------------
27      public void testRoot() throws Exception {
28          document.setName("doc1");
29  
30          Element root = document.getRootElement();
31          List authors = root.elements("author");
32  
33          assertTrue("Should be at least 2 authors", authors.size() == 2);
34  
35          Element author1 = (Element) authors.get(0);
36          Element author2 = (Element) authors.get(1);
37  
38          testCopy(root);
39          testCopy(author1);
40          testCopy(author2);
41      }
42  
43      protected void testCopy(Element element) throws Exception {
44          assertTrue("Not null", element != null);
45  
46          int attributeCount = element.attributeCount();
47          int nodeCount = element.nodeCount();
48  
49          Element copy = element.createCopy();
50  
51          assertEquals("Node size not equal after copy", element.nodeCount(),
52                  nodeCount);
53          assertTrue("Same attribute size after copy",
54                  element.attributeCount() == attributeCount);
55  
56          assertTrue("Copy has same node size", copy.nodeCount() == nodeCount);
57          assertTrue("Copy has same attribute size",
58                  copy.attributeCount() == attributeCount);
59  
60          for (int i = 0; i < attributeCount; i++) {
61              Attribute attr1 = element.attribute(i);
62              Attribute attr2 = copy.attribute(i);
63  
64              assertTrue("Attribute: " + i + " name is equal", attr1.getName()
65                      .equals(attr2.getName()));
66              assertTrue("Attribute: " + i + " value is equal", attr1.getValue()
67                      .equals(attr2.getValue()));
68          }
69  
70          for (int i = 0; i < nodeCount; i++) {
71              Node node1 = element.node(i);
72              Node node2 = copy.node(i);
73  
74              assertTrue("Node: " + i + " type is equal",
75                      node1.getNodeType() == node2.getNodeType());
76              assertTrue("Node: " + i + " value is equal", node1.getText()
77                      .equals(node2.getText()));
78          }
79      }
80  }
81  
82  /*
83   * Redistribution and use of this software and associated documentation
84   * ("Software"), with or without modification, are permitted provided that the
85   * following conditions are met:
86   * 
87   * 1. Redistributions of source code must retain copyright statements and
88   * notices. Redistributions must also contain a copy of this document.
89   * 
90   * 2. Redistributions in binary form must reproduce the above copyright notice,
91   * this list of conditions and the following disclaimer in the documentation
92   * and/or other materials provided with the distribution.
93   * 
94   * 3. The name "DOM4J" must not be used to endorse or promote products derived
95   * from this Software without prior written permission of MetaStuff, Ltd. For
96   * written permission, please contact dom4j-info@metastuff.com.
97   * 
98   * 4. Products derived from this Software may not be called "DOM4J" nor may
99   * "DOM4J" appear in their names without prior written permission of MetaStuff,
100  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
101  * 
102  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
103  * 
104  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
105  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
106  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
107  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
108  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
109  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
110  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
111  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
112  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
113  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
114  * POSSIBILITY OF SUCH DAMAGE.
115  * 
116  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
117  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/ThreadingTest.html0000644000175000017500000007257310242117757022220 0ustar ebourgebourg ThreadingTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import com.clarkware.junitperf.LoadTest;
11  import com.clarkware.junitperf.TimedTest;
12  
13  import junit.extensions.RepeatedTest;
14  
15  import junit.framework.Test;
16  import junit.framework.TestSuite;
17  
18  import junit.textui.TestRunner;
19  
20  import java.text.FieldPosition;
21  import java.text.SimpleDateFormat;
22  import java.util.Date;
23  
24  /***
25   * A test harness to test the dom4j package in a threaded environment
26   * 
27   * @author <a href="mailto:ddlucas@lse.com">David Lucas </a>
28   * @version $Revision: 1.3 $
29   */
30  public class ThreadingTest extends AbstractTestCase {
31      private static final ThreadLocal FORMATTER_CACHE = new ThreadLocal();
32  
33      private static final String SEPERATOR = " - ";
34  
35      private static final FieldPosition FIELD_ZERO = new FieldPosition(0);
36  
37      public ThreadingTest(String name) {
38          super(name);
39      }
40  
41      private static void preformat(StringBuffer strBuf, String context) {
42          long now = System.currentTimeMillis();
43          Date currentTime = new Date(now);
44          SimpleDateFormat formatter = (SimpleDateFormat) FORMATTER_CACHE.get();
45  
46          if (formatter == null) {
47              formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS zzz");
48              FORMATTER_CACHE.set(formatter);
49          }
50  
51          strBuf.append("[");
52          formatter.format(currentTime, strBuf, FIELD_ZERO);
53          strBuf.append(" (").append(now).append(") ]");
54  
55          strBuf.append(SEPERATOR);
56          strBuf.append(getThreadId());
57          strBuf.append(SEPERATOR);
58          strBuf.append(context);
59          strBuf.append(SEPERATOR);
60      }
61  
62      private static String getThreadId() {
63          String tid = Thread.currentThread().getName();
64  
65          return tid;
66      }
67  
68      /***
69       * This test combines many different types of operations on DOM4J in a
70       * threaded environment. If a problem occurs with threading, the tests will
71       * fail. This was used to help isolate an internal threading issue.
72       * Unfortunately it may not always create the condition necessary to break
73       * un-thread-safe code. This is due to the nature of the machine, JVM, and
74       * application and if the conditions are right. Typically the problems of
75       * multithreading occur due to an unprotected HashMap or ArrayList in a
76       * class being used by more than one thread. Also, most developers think
77       * that their class or object instance will only be used by one thread. But
78       * if a factory or singleton caches a class or instance, it can quickly
79       * become an unsafe environment. Hence this test to assist in locating
80       * threading issues.
81       */
82      public void testCombo() {
83          int loop = 10;
84  
85          try {
86              long begin = System.currentTimeMillis();
87              String value = null;
88              String expected = null;
89              String xml = null;
90              Document doc = null;
91              Element root = null;
92              Element item = null;
93              Element newItem = null;
94              QName qn = null;
95              Namespace ns = null;
96              long now = 0;
97  
98              xml = "<ROOT xmlns:t0=\"http://www.lse.com/t0\" >"
99                      + "  <ctx><type>Context</type></ctx>"
100                     + "  <A><B><C><D>This is a TEST</D></C></B></A>"
101                     + "  <t0:Signon><A>xyz</A><t0:Cust>customer</t0:Cust>"
102                     + "</t0:Signon></ROOT>";
103 
104             for (int i = 0; i < loop; i++) {
105                 doc = DocumentHelper.parseText(xml);
106 
107                 root = doc.getRootElement();
108                 ns = Namespace.get("t0", "http://www.lse.com/t0");
109                 qn = QName.get("Signon", ns);
110                 item = root.element(qn);
111                 value = item.asXML();
112                 expected = "<t0:Signon xmlns:t0=\"http://www.lse.com/t0\">"
113                         + "<A>xyz</A><t0:Cust>customer</t0:Cust></t0:Signon>";
114                 assertEquals("test t0:Signon ", expected, value);
115 
116                 qn = root.getQName("Test");
117                 newItem = DocumentHelper.createElement(qn);
118                 now = System.currentTimeMillis();
119                 newItem.setText(String.valueOf(now));
120                 root.add(newItem);
121 
122                 qn = root.getQName("Test2");
123                 newItem = DocumentHelper.createElement(qn);
124                 now = System.currentTimeMillis();
125                 newItem.setText(String.valueOf(now));
126                 root.add(newItem);
127 
128                 item = root.element(qn);
129                 item.detach();
130                 item.setQName(qn);
131                 root.add(item);
132                 value = item.asXML();
133                 expected = "<Test2>" + now + "</Test2>";
134                 assertEquals("test Test2 ", expected, value);
135 
136                 qn = root.getQName("Test3");
137                 newItem = DocumentHelper.createElement(qn);
138                 now = System.currentTimeMillis();
139                 newItem.setText(String.valueOf(now));
140                 root.add(newItem);
141 
142                 item = root.element(qn);
143                 item.detach();
144                 item.setQName(qn);
145                 root.add(item);
146                 value = item.asXML();
147                 expected = "<Test3>" + now + "</Test3>";
148                 assertEquals("test Test3 ", expected, value);
149 
150                 qn = item.getQName("Test4");
151                 newItem = DocumentHelper.createElement(qn);
152                 now = System.currentTimeMillis();
153                 newItem.setText(String.valueOf(now));
154                 root.add(newItem);
155 
156                 item = root.element(qn);
157                 item.detach();
158                 item.setQName(qn);
159                 root.add(item);
160                 value = item.asXML();
161                 expected = "<Test4>" + now + "</Test4>";
162                 assertEquals("test Test4 ", expected, value);
163             }
164 
165             double duration = System.currentTimeMillis() - begin;
166             double avg = duration / loop;
167         } catch (Exception e) {
168             e.printStackTrace();
169             assertTrue("Exception in test: " + e.getMessage(), false);
170         }
171     }
172 
173     /***
174      * This test isolates QNameCache in a multithreaded environment.
175      */
176     public void testQNameCache() {
177         int loop = 100;
178 
179         try {
180             long begin = System.currentTimeMillis();
181             String value = null;
182             String expected = null;
183             String xml = null;
184             Document doc = null;
185             Element root = null;
186             Element item = null;
187             Element newItem = null;
188             QName qn = null;
189             Namespace ns = null;
190             long now = 0;
191 
192             xml = "<ROOT xmlns:t0=\"http://www.lse.com/t0\" >"
193                     + "  <ctx><type>Context</type></ctx>"
194                     + "  <A><B><C><D>This is a TEST</D></C></B></A>"
195                     + "  <t0:Signon><A>xyz</A><t0:Cust>customer</t0:Cust>"
196                     + "</t0:Signon></ROOT>";
197 
198             for (int i = 0; i < loop; i++) {
199                 doc = DocumentHelper.parseText(xml);
200                 root = doc.getRootElement();
201 
202                 qn = DocumentHelper.createQName("test");
203                 value = fetchValue(qn);
204                 expected = "<test/>";
205                 assertEquals("test test ", expected, value);
206 
207                 // creat it again
208                 qn = DocumentHelper.createQName("test");
209                 value = fetchValue(qn);
210                 expected = "<test/>";
211                 assertEquals("test test again ", expected, value);
212 
213                 qn = root.getQName("t0:Signon");
214                 value = fetchValue(qn);
215                 expected = "<t0:Signon xmlns:t0=\"http://www.lse.com/t0\"/>";
216                 assertEquals("test t0:Signon ", expected, value);
217             }
218 
219             double duration = System.currentTimeMillis() - begin;
220             double avg = duration / loop;
221         } catch (Exception e) {
222             e.printStackTrace();
223             assertTrue("Exception in test: " + e.getMessage(), false);
224         }
225     }
226 
227     /***
228      * This method creates a value that can be expected during a test
229      * 
230      * @param qn
231      * 
232      * @return
233      */
234     public String fetchValue(QName qn) {
235         String value = null;
236 
237         StringBuffer sb = new StringBuffer();
238         sb.append("<");
239 
240         String prefix = qn.getNamespacePrefix();
241 
242         if ((prefix != null) && (prefix.length() > 0)) {
243             sb.append(prefix).append(":");
244         }
245 
246         sb.append(qn.getName());
247 
248         String uri = qn.getNamespaceURI();
249 
250         if ((uri != null) && (uri.length() > 0)) {
251             sb.append(" xmlns");
252 
253             if ((prefix != null) && (prefix.length() > 0)) {
254                 sb.append(":").append(prefix);
255             }
256 
257             sb.append("=\"").append(uri).append("\"");
258         }
259 
260         sb.append("/>");
261 
262         value = sb.toString();
263 
264         return value;
265     }
266 
267     /***
268      * Assembles and returns a test suite.
269      * 
270      * @return The suite
271      */
272     public static Test suite() {
273         TestSuite suite = new TestSuite();
274         suite.addTest(makeRepeatedLoadTest(5, 10, "testCombo"));
275         suite.addTest(makeRepeatedLoadTest(5, 10, "testQNameCache"));
276 
277         return suite;
278     }
279 
280     /***
281      * JUnit method to exercise test via threads and loops
282      * 
283      * @param users
284      *            Number of users to simulate (i.e. Threads).
285      * @param iterations
286      *            Number of iterations per user ( repeat the test x times).
287      * @param testMethod
288      *            method to execute (testXXX).
289      * 
290      * @return A Junit test
291      */
292     protected static Test makeRepeatedLoadTest(int users, int iterations,
293             String testMethod) {
294         long maxElapsedTime = 120000 + (1000 * users * iterations);
295 
296         Test testCase = new ThreadingTest(testMethod);
297 
298         Test repeatedTest = new RepeatedTest(testCase, iterations);
299         Test loadTest = new LoadTest(repeatedTest, users);
300         Test timedTest = new TimedTest(loadTest, maxElapsedTime);
301 
302         return timedTest;
303     }
304 
305     public static void main(String[] args) {
306         TestRunner.run(ThreadingTest.class);
307     }
308 }
309 
310 /*
311  * Redistribution and use of this software and associated documentation
312  * ("Software"), with or without modification, are permitted provided that the
313  * following conditions are met:
314  * 
315  * 1. Redistributions of source code must retain copyright statements and
316  * notices. Redistributions must also contain a copy of this document.
317  * 
318  * 2. Redistributions in binary form must reproduce the above copyright notice,
319  * this list of conditions and the following disclaimer in the documentation
320  * and/or other materials provided with the distribution.
321  * 
322  * 3. The name "DOM4J" must not be used to endorse or promote products derived
323  * from this Software without prior written permission of MetaStuff, Ltd. For
324  * written permission, please contact dom4j-info@metastuff.com.
325  * 
326  * 4. Products derived from this Software may not be called "DOM4J" nor may
327  * "DOM4J" appear in their names without prior written permission of MetaStuff,
328  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
329  * 
330  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
331  * 
332  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
333  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
334  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
335  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
336  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
337  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
338  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
339  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
340  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
341  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
342  * POSSIBILITY OF SUCH DAMAGE.
343  * 
344  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
345  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/bean/0000755000175000017500000000000012133227266017452 5ustar ebourgebourgdom4j-1.6.1/docs/xref-test/org/dom4j/bean/package-summary.html0000644000175000017500000000374410242117562023432 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.bean

Class Summary
BeansTest
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref-test/org/dom4j/bean/package-frame.html0000644000175000017500000000126610242117745023027 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.bean

org.dom4j.bean

Classes

  • BeansTest
dom4j-1.6.1/docs/xref-test/org/dom4j/bean/BeansTest.html0000644000175000017500000001612010242117677022233 0ustar ebourgebourg BeansTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.bean;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.AbstractTestCase;
13  import org.dom4j.io.SAXReader;
14  
15  /***
16   * DOCUMENT ME!
17   * 
18   * @author <a href="mailto:maartenc@users.sourceforge.net">Maarten Coene </a>
19   */
20  public class BeansTest extends AbstractTestCase {
21      public static void main(String[] args) {
22          TestRunner.run(BeansTest.class);
23      }
24  
25      // Test case(s)
26      // -------------------------------------------------------------------------
27      public void testReadXML() throws Exception {
28          SAXReader reader = new SAXReader(BeanDocumentFactory.getInstance());
29          getDocument("/xml/bean/gui.xml", reader);
30      }
31  }
32  
33  /*
34   * Redistribution and use of this software and associated documentation
35   * ("Software"), with or without modification, are permitted provided that the
36   * following conditions are met:
37   * 
38   * 1. Redistributions of source code must retain copyright statements and
39   * notices. Redistributions must also contain a copy of this document.
40   * 
41   * 2. Redistributions in binary form must reproduce the above copyright notice,
42   * this list of conditions and the following disclaimer in the documentation
43   * and/or other materials provided with the distribution.
44   * 
45   * 3. The name "DOM4J" must not be used to endorse or promote products derived
46   * from this Software without prior written permission of MetaStuff, Ltd. For
47   * written permission, please contact dom4j-info@metastuff.com.
48   * 
49   * 4. Products derived from this Software may not be called "DOM4J" nor may
50   * "DOM4J" appear in their names without prior written permission of MetaStuff,
51   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
52   * 
53   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
54   * 
55   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
56   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
59   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
60   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
61   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
62   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
63   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
64   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
65   * POSSIBILITY OF SUCH DAMAGE.
66   * 
67   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
68   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/SetTextTest.html0000644000175000017500000002167010242117756021702 0ustar ebourgebourg SetTextTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  /***
13   * Tests the setText method
14   * 
15   * @author <a href="mailto:maartenc@users.sourceforge.net">Maarten Coene </a>
16   */
17  public class SetTextTest extends AbstractTestCase {
18      public static void main(String[] args) {
19          TestRunner.run(SetTextTest.class);
20      }
21  
22      /*
23       * The structure of the test document is: [root] [author name="James"
24       * location="UK"] James Strachem
25       * [url]http://sourceforge.net/users/jstrachan/[/url] [/author] [author
26       * name="Bob" location="Canada"] Bob McWhirter
27       * [url]http://sourceforge.net/users/werken/[/url] [/author] [/root]
28       */
29      public void testSetText1() throws Exception {
30          String newURL = "newURL";
31  
32          Node urlNode = document.selectSingleNode("//root/author[1]/url");
33          urlNode.setText(newURL);
34  
35          assertEquals(newURL, urlNode.getText());
36          assertTrue(urlNode instanceof Element);
37  
38          Element urlElement = (Element) urlNode;
39          assertEquals(0, urlElement.elements().size());
40      }
41  
42      public void testSetText2() throws Exception {
43          String newName = "Strachem James";
44  
45          Node authorNode = document.selectSingleNode("//root/author[1]");
46          authorNode.setText(newName);
47  
48          assertEquals(newName, authorNode.getText());
49          assertTrue(authorNode instanceof Element);
50  
51          Element urlElement = (Element) authorNode;
52          assertEquals(1, urlElement.elements().size());
53      }
54  }
55  
56  /*
57   * Redistribution and use of this software and associated documentation
58   * ("Software"), with or without modification, are permitted provided that the
59   * following conditions are met:
60   * 
61   * 1. Redistributions of source code must retain copyright statements and
62   * notices. Redistributions must also contain a copy of this document.
63   * 
64   * 2. Redistributions in binary form must reproduce the above copyright notice,
65   * this list of conditions and the following disclaimer in the documentation
66   * and/or other materials provided with the distribution.
67   * 
68   * 3. The name "DOM4J" must not be used to endorse or promote products derived
69   * from this Software without prior written permission of MetaStuff, Ltd. For
70   * written permission, please contact dom4j-info@metastuff.com.
71   * 
72   * 4. Products derived from this Software may not be called "DOM4J" nor may
73   * "DOM4J" appear in their names without prior written permission of MetaStuff,
74   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
75   * 
76   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
77   * 
78   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
79   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
81   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
82   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
83   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
84   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
85   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
86   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
87   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
88   * POSSIBILITY OF SUCH DAMAGE.
89   * 
90   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
91   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/ProcessingInstructionTest.html0000644000175000017500000002011710242117757024654 0ustar ebourgebourg ProcessingInstructionTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.Map;
13  
14  /***
15   * DOCUMENT ME!
16   * 
17   * @author kralik
18   * @author Maarten Coene
19   */
20  public class ProcessingInstructionTest extends AbstractTestCase {
21      public static void main(String[] args) {
22          TestRunner.run(ProcessingInstructionTest.class);
23      }
24  
25      public void testParseValues() {
26          String data = " abc='123' def=\"2!=3\" ghi=' 4 = '";
27          ProcessingInstruction pi = DocumentHelper.createProcessingInstruction(
28                  "pi", data);
29  
30          Map values = pi.getValues();
31          assertEquals(3, values.size());
32          assertEquals("123", pi.getValue("abc"));
33          assertEquals("2!=3", pi.getValue("def"));
34          assertEquals(" 4 = ", pi.getValue("ghi"));
35      }
36  
37      public void testBug787428() {
38          String data = "xpath=\"/abc/cde[@id='qqq']\"";
39          ProcessingInstruction pi = DocumentHelper.createProcessingInstruction(
40                  "merge", data);
41  
42          assertEquals("/abc/cde[@id='qqq']", pi.getValue("xpath"));
43      }
44  }
45  
46  /*
47   * Redistribution and use of this software and associated documentation
48   * ("Software"), with or without modification, are permitted provided that the
49   * following conditions are met:
50   * 
51   * 1. Redistributions of source code must retain copyright statements and
52   * notices. Redistributions must also contain a copy of this document.
53   * 
54   * 2. Redistributions in binary form must reproduce the above copyright notice,
55   * this list of conditions and the following disclaimer in the documentation
56   * and/or other materials provided with the distribution.
57   * 
58   * 3. The name "DOM4J" must not be used to endorse or promote products derived
59   * from this Software without prior written permission of MetaStuff, Ltd. For
60   * written permission, please contact dom4j-info@metastuff.com.
61   * 
62   * 4. Products derived from this Software may not be called "DOM4J" nor may
63   * "DOM4J" appear in their names without prior written permission of MetaStuff,
64   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
65   * 
66   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
67   * 
68   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
69   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
70   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
71   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
72   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
73   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
74   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
75   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
76   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
77   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
78   * POSSIBILITY OF SUCH DAMAGE.
79   * 
80   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
81   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/ContentTest.html0000644000175000017500000005373110242117702021706 0ustar ebourgebourg ContentTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.Iterator;
13  import java.util.List;
14  
15  /***
16   * A test harness to test the content API in DOM4J
17   * 
18   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
19   * @version $Revision: 1.3 $
20   */
21  public class ContentTest extends AbstractTestCase {
22      protected DocumentFactory factory = new DocumentFactory();
23  
24      public static void main(String[] args) {
25          TestRunner.run(ContentTest.class);
26      }
27  
28      // Test case(s)
29      // -------------------------------------------------------------------------
30      public void testRoot() throws Exception {
31          Element root = document.getRootElement();
32          assertTrue("Has root element", root != null);
33  
34          List authors = root.elements("author");
35          assertTrue("Root has children", (authors != null)
36                  && (authors.size() == 2));
37  
38          Element author1 = (Element) authors.get(0);
39          Element author2 = (Element) authors.get(1);
40  
41          assertTrue("Author1 is James", author1.attributeValue("name").equals(
42                  "James"));
43          assertTrue("Author2 is Bob", author2.attributeValue("name").equals(
44                  "Bob"));
45  
46          testGetAttributes(author1);
47          testGetAttributes(author2);
48      }
49  
50      public void testContent() throws Exception {
51          Element root = document.getRootElement();
52          assertTrue("Has root element", root != null);
53  
54          List content = root.content();
55          assertTrue("Root has content", (content != null)
56                  && (content.size() >= 2));
57  
58          boolean iterated = false;
59  
60          for (Iterator iter = content.iterator(); iter.hasNext();) {
61              Object object = iter.next();
62              assertTrue("Content object is a node", object instanceof Node);
63              iterated = true;
64          }
65  
66          assertTrue("Iteration completed", iterated);
67      }
68  
69      public void testGetNode() throws Exception {
70          Element root = document.getRootElement();
71          assertTrue("Has root element", root != null);
72  
73          int count = root.nodeCount();
74          assertTrue("Root has correct node count", count == 2);
75  
76          boolean iterated = false;
77  
78          for (int i = 0; i < count; i++) {
79              Node node = root.node(i);
80              assertTrue("Valid node returned from node()", node != null);
81              iterated = true;
82          }
83  
84          assertTrue("Iteration completed", iterated);
85      }
86  
87      public void testGetXPathNode() throws Exception {
88          Element root = document.getRootElement();
89          assertTrue("Has root element", root != null);
90  
91          int count = root.nodeCount();
92          assertTrue("Root has correct node count", count == 2);
93  
94          boolean iterated = false;
95  
96          for (int i = 0; i < count; i++) {
97              Node node = root.getXPathResult(i);
98              assertTrue("Valid node returned from node()", node != null);
99              assertTrue("Node supports the parent relationship", node
100                     .supportsParent());
101             iterated = true;
102         }
103 
104         assertTrue("Iteration completed", iterated);
105     }
106 
107     public void testOrderOfPI() throws Exception {
108         Document document = factory.createDocument();
109         document.addProcessingInstruction("xml-stylesheet",
110                 "type=\"text/xsl\" href=\"...\"");
111         document.addElement("root");
112 
113         List list = document.content();
114 
115         assertNotNull(list);
116         assertEquals(2, list.size());
117 
118         Object pi = list.get(0);
119         Object root = list.get(1);
120 
121         assertTrue("First element is not a PI",
122                 pi instanceof ProcessingInstruction);
123         assertTrue("Second element is an element", root instanceof Element);
124 
125         String xml = "<?xml version=\"1.0\" ?>\n"
126                 + "<?xml-stylesheet type=\"text/xsl\" href=\"foo\" ?>\n"
127                 + "<root/>";
128         document = DocumentHelper.parseText(xml);
129 
130         list = document.content();
131 
132         assertNotNull(list);
133         assertEquals(2, list.size());
134         pi = list.get(0);
135         root = list.get(1);
136 
137         assertTrue("First element is not a PI",
138                 pi instanceof ProcessingInstruction);
139         assertTrue("Second element is an element", root instanceof Element);
140     }
141 
142     public void testAddingInTheMiddle() throws Exception {
143         Document doc = factory.createDocument();
144         Element root = doc.addElement("html");
145         Element header = root.addElement("header");
146         Element footer = root.addElement("footer");
147 
148         // now lets add <foo> in between header & footer
149         List list = root.content();
150         Element foo = factory.createElement("foo");
151         list.add(1, foo);
152 
153         // assertions
154         assertTrue(list.size() == 3);
155         assertTrue(list.get(0) == header);
156         assertTrue(list.get(1) == foo);
157         assertTrue(list.get(2) == footer);
158     }
159 
160     public void testAddAtIndex() throws Exception {
161         Document doc = factory.createDocument();
162         Element root = doc.addElement("html");
163         Element header = root.addElement("header");
164         Element body = root.addElement("body");
165 
166         Element foo = factory.createElement("foo");
167         Element bar = factory.createElement("bar");
168 
169         List content = header.content();
170         content.add(0, foo);
171         content.add(0, bar);
172 
173         assertEquals("foo", header.node(1).getName());
174         assertEquals("bar", header.node(0).getName());
175 
176         foo = factory.createElement("foo");
177         bar = factory.createElement("bar");
178 
179         content = body.content();
180         content.add(0, foo);
181         content.add(1, bar);
182 
183         assertEquals("foo", body.node(0).getName());
184         assertEquals("bar", body.node(1).getName());
185     }
186 
187     public void testAddAtIndex2() throws Exception {
188         Document doc = factory.createDocument();
189         Element parent = doc.addElement("parent");
190         Element child = parent.addElement("child");
191         Element anotherChild = factory.createElement("child2");
192 
193         List elements = parent.elements();
194         int index = elements.indexOf(child);
195 
196         assertEquals(0, index);
197 
198         elements.add(1, anotherChild);
199         elements = parent.elements();
200         assertEquals(child, elements.get(0));
201         assertEquals(anotherChild, elements.get(1));
202     }
203 
204     // Implementation methods
205     // -------------------------------------------------------------------------
206     protected void testGetAttributes(Element author) throws Exception {
207         String definedName = "name";
208         String undefinedName = "undefined-attribute-name";
209         String defaultValue = "** Default Value **";
210 
211         String value = author.attributeValue(definedName, defaultValue);
212         assertTrue("Defined value doesn't return specified default value",
213                 value != defaultValue);
214 
215         value = author.attributeValue(undefinedName, defaultValue);
216         assertTrue("Undefined value returns specified default value",
217                 value == defaultValue);
218     }
219 }
220 
221 /*
222  * Redistribution and use of this software and associated documentation
223  * ("Software"), with or without modification, are permitted provided that the
224  * following conditions are met:
225  * 
226  * 1. Redistributions of source code must retain copyright statements and
227  * notices. Redistributions must also contain a copy of this document.
228  * 
229  * 2. Redistributions in binary form must reproduce the above copyright notice,
230  * this list of conditions and the following disclaimer in the documentation
231  * and/or other materials provided with the distribution.
232  * 
233  * 3. The name "DOM4J" must not be used to endorse or promote products derived
234  * from this Software without prior written permission of MetaStuff, Ltd. For
235  * written permission, please contact dom4j-info@metastuff.com.
236  * 
237  * 4. Products derived from this Software may not be called "DOM4J" nor may
238  * "DOM4J" appear in their names without prior written permission of MetaStuff,
239  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
240  * 
241  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
242  * 
243  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
244  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
245  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
246  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
247  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
248  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
249  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
250  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
251  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
252  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
253  * POSSIBILITY OF SUCH DAMAGE.
254  * 
255  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
256  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/NodeTypeNameTest.html0000644000175000017500000003236110242117714022623 0ustar ebourgebourg NodeTypeNameTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.Iterator;
13  
14  /***
15   * Tests the getNodeNameType() method
16   * 
17   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
18   * @version $Revision: 1.4 $
19   */
20  public class NodeTypeNameTest extends AbstractTestCase {
21      public static void main(String[] args) {
22          TestRunner.run(NodeTypeNameTest.class);
23      }
24  
25      // Test case(s)
26      // -------------------------------------------------------------------------
27      public void testDocument() throws Exception {
28          testDocument(getDocument());
29      }
30  
31      public void testCDATA() throws Exception {
32          testDocument("/xml/cdata.xml");
33      }
34  
35      public void testNamespaces() throws Exception {
36          testDocument("/xml/namespaces.xml");
37          testDocument("/xml/testNamespaces.xml");
38      }
39  
40      public void testPI() throws Exception {
41          testDocument("/xml/testPI.xml");
42      }
43  
44      public void testInline() throws Exception {
45          testDocument("/xml/inline.xml");
46      }
47  
48      // Implementation methods
49      // -------------------------------------------------------------------------
50      protected void testDocument(String fileName) throws Exception {
51          Document document = getDocument(fileName);
52          testDocument(document);
53      }
54  
55      protected void testDocument(Document document) throws Exception {
56          assertEquals(document.getNodeTypeName(), "Document");
57  
58          DocumentType docType = document.getDocType();
59  
60          if (docType != null) {
61              assertEquals(docType.getNodeTypeName(), "DocumentType");
62          }
63  
64          testElement(document.getRootElement());
65      }
66  
67      protected void testElement(Element element) {
68          assertEquals(element.getNodeTypeName(), "Element");
69  
70          for (Iterator iter = element.attributeIterator(); iter.hasNext();) {
71              Attribute attribute = (Attribute) iter.next();
72              assertEquals(attribute.getNodeTypeName(), "Attribute");
73          }
74  
75          for (Iterator iter = element.nodeIterator(); iter.hasNext();) {
76              Node node = (Node) iter.next();
77              String nodeTypeName = node.getNodeTypeName();
78  
79              if (node instanceof Attribute) {
80                  assertEquals(nodeTypeName, "Attribute");
81              } else if (node instanceof CDATA) {
82                  assertEquals(nodeTypeName, "CDATA");
83              } else if (node instanceof Comment) {
84                  assertEquals(nodeTypeName, "Comment");
85              } else if (node instanceof Element) {
86                  assertEquals(nodeTypeName, "Element");
87                  testElement((Element) node);
88              } else if (node instanceof Entity) {
89                  assertEquals(nodeTypeName, "Entity");
90              } else if (node instanceof Element) {
91                  assertEquals(nodeTypeName, "Element");
92              } else if (node instanceof Namespace) {
93                  assertEquals(nodeTypeName, "Namespace");
94              } else if (node instanceof ProcessingInstruction) {
95                  assertEquals(nodeTypeName, "ProcessingInstruction");
96              } else if (node instanceof Text) {
97                  assertEquals(nodeTypeName, "Text");
98              } else {
99                  assertTrue("Invalid node type: " + nodeTypeName + " for node: "
100                         + node, false);
101             }
102         }
103     }
104 }
105 
106 /*
107  * Redistribution and use of this software and associated documentation
108  * ("Software"), with or without modification, are permitted provided that the
109  * following conditions are met:
110  * 
111  * 1. Redistributions of source code must retain copyright statements and
112  * notices. Redistributions must also contain a copy of this document.
113  * 
114  * 2. Redistributions in binary form must reproduce the above copyright notice,
115  * this list of conditions and the following disclaimer in the documentation
116  * and/or other materials provided with the distribution.
117  * 
118  * 3. The name "DOM4J" must not be used to endorse or promote products derived
119  * from this Software without prior written permission of MetaStuff, Ltd. For
120  * written permission, please contact dom4j-info@metastuff.com.
121  * 
122  * 4. Products derived from this Software may not be called "DOM4J" nor may
123  * "DOM4J" appear in their names without prior written permission of MetaStuff,
124  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
125  * 
126  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
127  * 
128  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
129  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
130  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
131  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
132  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
133  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
134  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
135  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
136  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
137  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
138  * POSSIBILITY OF SUCH DAMAGE.
139  * 
140  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
141  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/MakeElementTest.html0000644000175000017500000002613210242117753022464 0ustar ebourgebourg MakeElementTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  /***
13   * A test harness to test the DocumentHelper.makeElement() methodt
14   * 
15   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
16   * @version $Revision: 1.3 $
17   */
18  public class MakeElementTest extends AbstractTestCase {
19      public static void main(String[] args) {
20          TestRunner.run(MakeElementTest.class);
21      }
22  
23      // Test case(s)
24      // -------------------------------------------------------------------------
25      public void testMakeElement() throws Exception {
26          Document doc = DocumentHelper.createDocument();
27  
28          Element c = DocumentHelper.makeElement(doc, "a/b/c");
29          assertTrue("Should return a valid element", c != null);
30  
31          Element c2 = DocumentHelper.makeElement(doc, "a/b/c");
32  
33          assertTrue("Found same element again", c == c2);
34  
35          c.addAttribute("x", "123");
36  
37          Node found = doc.selectSingleNode("/a/b/c[@x='123']");
38  
39          assertEquals("Found same node via XPath", c, found);
40  
41          Element b = c.getParent();
42  
43          Element e = DocumentHelper.makeElement(b, "c/d/e");
44  
45          assertTrue("Should return a valid element", e != null);
46  
47          Element e2 = DocumentHelper.makeElement(b, "c/d/e");
48  
49          assertTrue("Found same element again", e == e2);
50  
51          e.addAttribute("y", "456");
52  
53          found = b.selectSingleNode("c/d/e[@y='456']");
54  
55          assertEquals("Found same node via XPath", e, found);
56      }
57  
58      public void testMakeQualifiedElement() throws Exception {
59          Document doc = DocumentHelper.createDocument();
60          Element root = doc.addElement("root");
61          root.addNamespace("", "defaultURI");
62          root.addNamespace("foo", "fooURI");
63          root.addNamespace("bar", "barURI");
64  
65          Element c = DocumentHelper.makeElement(doc, "root/foo:b/bar:c");
66          assertTrue("Should return a valid element", c != null);
67  
68          assertEquals("c has a valid namespace", "barURI", c.getNamespaceURI());
69  
70          Element b = c.getParent();
71  
72          assertEquals("b has a valid namespace", "fooURI", b.getNamespaceURI());
73  
74          log("Created: " + c);
75  
76          Element c2 = DocumentHelper.makeElement(doc, "root/foo:b/bar:c");
77          assertTrue("Found same element again", c == c2);
78      }
79  }
80  
81  /*
82   * Redistribution and use of this software and associated documentation
83   * ("Software"), with or without modification, are permitted provided that the
84   * following conditions are met:
85   * 
86   * 1. Redistributions of source code must retain copyright statements and
87   * notices. Redistributions must also contain a copy of this document.
88   * 
89   * 2. Redistributions in binary form must reproduce the above copyright notice,
90   * this list of conditions and the following disclaimer in the documentation
91   * and/or other materials provided with the distribution.
92   * 
93   * 3. The name "DOM4J" must not be used to endorse or promote products derived
94   * from this Software without prior written permission of MetaStuff, Ltd. For
95   * written permission, please contact dom4j-info@metastuff.com.
96   * 
97   * 4. Products derived from this Software may not be called "DOM4J" nor may
98   * "DOM4J" appear in their names without prior written permission of MetaStuff,
99   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
100  * 
101  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
102  * 
103  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
104  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
105  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
106  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
107  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
108  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
109  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
110  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
111  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
112  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
113  * POSSIBILITY OF SUCH DAMAGE.
114  * 
115  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
116  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/IteratorTest.html0000644000175000017500000004122610242117723022064 0ustar ebourgebourg IteratorTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.Iterator;
13  import java.util.List;
14  
15  /***
16   * A test harness to test the Iterator API in DOM4J
17   * 
18   * @author <a href="mailto:jdoughty@jdoughty@cs.gmu.edu">Jonathan Doughty </a>
19   * @version $Revision: 1.4 $
20   */
21  public class IteratorTest extends AbstractTestCase {
22      private static final int NUMELE = 10;
23  
24      protected Document iterDocument;
25  
26      public static void main(String[] args) {
27          TestRunner.run(IteratorTest.class);
28      }
29  
30      protected void setUp() throws Exception {
31          super.setUp();
32          iterDocument = DocumentHelper.createDocument();
33  
34          Element root = iterDocument.addElement("root");
35  
36          for (int i = 0; i < NUMELE; i++) {
37              root.addElement("iterator test").addAttribute("instance",
38                      Integer.toString(i));
39          }
40      }
41  
42      // Test case(s)
43      // -------------------------------------------------------------------------
44      public void testElementCount() throws Exception {
45          Element root = iterDocument.getRootElement();
46          assertTrue("Has root element", root != null);
47  
48          List elements = root.elements("iterator test");
49          int elementSize = elements.size();
50          assertTrue("Root has " + elementSize + " children", (elements != null)
51                  && (elementSize == NUMELE));
52      }
53  
54      public void testPlainIteration() throws Exception {
55          Element root = iterDocument.getRootElement();
56          List elements = root.elements("iterator test");
57          Iterator iter = root.elementIterator("iterator test");
58          int elementSize = elements.size();
59  
60          int count = 0;
61  
62          for (; iter.hasNext();) {
63              Element e = (Element) iter.next();
64              assertEquals("instance " + e.attribute("instance").getValue()
65                      + " equals " + count, e.attribute("instance").getValue(),
66                      Integer.toString(count));
67              count++;
68          }
69  
70          assertTrue(elementSize + " elements iterated", count == elementSize);
71      }
72  
73      public void testSkipAlternates() throws Exception {
74          Element root = iterDocument.getRootElement();
75          List elements = root.elements("iterator test");
76          Iterator iter = root.elementIterator("iterator test");
77          int elementSize = elements.size();
78          int count = 0;
79  
80          for (; iter.hasNext();) {
81              Element e = (Element) iter.next();
82              assertEquals("instance " + e.attribute("instance").getValue()
83                      + " equals " + (count * 2), e.attribute("instance")
84                      .getValue(), Integer.toString(count * 2));
85              iter.next();
86              count++;
87          }
88  
89          assertTrue((elementSize / 2) + " alternate elements iterated",
90                  count == (elementSize / 2));
91      }
92  
93      public void testNoHasNext() throws Exception {
94          Element root = iterDocument.getRootElement();
95          List elements = root.elements("iterator test");
96          Iterator iter = root.elementIterator("iterator test");
97          int elementSize = elements.size();
98          int count = 0;
99          Element e = null;
100 
101         for (; count < elementSize;) {
102             e = (Element) iter.next();
103             assertEquals("instance " + e.attribute("instance").getValue()
104                     + " equals " + count, e.attribute("instance").getValue(),
105                     Integer.toString(count));
106             System.out.println("instance " + e.attribute("instance").getValue()
107                     + " equals " + count);
108             count++;
109         }
110 
111         try {
112             e = (Element) iter.next();
113 
114             if (e != null) {
115                 // Real Iterators wouldn't get here
116                 assertTrue("no more elements,value instead is "
117                         + e.attribute("instance").getValue(), e == null);
118             }
119         } catch (Exception exp) {
120             assertTrue("Real iterators throw NoSuchElementException",
121                     exp instanceof java.util.NoSuchElementException);
122         }
123     }
124 
125     public void testExtraHasNexts() throws Exception {
126         Element root = iterDocument.getRootElement();
127         List elements = root.elements("iterator test");
128         Iterator iter = root.elementIterator("iterator test");
129         int elementSize = elements.size();
130         int count = 0;
131 
132         for (; iter.hasNext();) {
133             Element e = (Element) iter.next();
134             assertEquals("instance " + e.attribute("instance").getValue()
135                     + " equals " + count, e.attribute("instance").getValue(),
136                     Integer.toString(count));
137             iter.hasNext();
138             count++;
139         }
140 
141         assertTrue(elementSize + " elements iterated with extra hasNexts",
142                 count == elementSize);
143     }
144 }
145 
146 /*
147  * Redistribution and use of this software and associated documentation
148  * ("Software"), with or without modification, are permitted provided that the
149  * following conditions are met:
150  * 
151  * 1. Redistributions of source code must retain copyright statements and
152  * notices. Redistributions must also contain a copy of this document.
153  * 
154  * 2. Redistributions in binary form must reproduce the above copyright notice,
155  * this list of conditions and the following disclaimer in the documentation
156  * and/or other materials provided with the distribution.
157  * 
158  * 3. The name "DOM4J" must not be used to endorse or promote products derived
159  * from this Software without prior written permission of MetaStuff, Ltd. For
160  * written permission, please contact dom4j-info@metastuff.com.
161  * 
162  * 4. Products derived from this Software may not be called "DOM4J" nor may
163  * "DOM4J" appear in their names without prior written permission of MetaStuff,
164  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
165  * 
166  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
167  * 
168  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
169  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
170  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
171  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
172  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
173  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
174  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
175  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
176  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
177  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
178  * POSSIBILITY OF SUCH DAMAGE.
179  * 
180  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
181  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/XPathTest.html0000644000175000017500000003755610242117713021331 0ustar ebourgebourg XPathTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.List;
13  
14  import org.dom4j.tree.DefaultElement;
15  import org.dom4j.xpath.DefaultXPath;
16  
17  /***
18   * A test harness to test XPath expression evaluation in DOM4J
19   * 
20   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
21   * @version $Revision: 1.4 $
22   */
23  public class XPathTest extends AbstractTestCase {
24      protected static String[] paths = {
25              ".",
26              "*",
27              "/",
28              "/.",
29              "/*",
30              "/node()",
31              "/child::node()",
32              "/self::node()",
33              "root",
34              "/root",
35              "/root/author",
36              "text()",
37              "//author",
38              "//author/text()",
39              "//@location",
40              "//attribute::*",
41              "//namespace::*",
42              "normalize-space(/root)",
43              "//author[@location]",
44              "//author[@location='UK']",
45              "root|author",
46              "//*[.='James Strachan']",
47              "//root/author[1]",
48              "normalize-space(/root/author)",
49              "normalize-space(' a  b  c  d ')",
50              "//root|//author[1]|//author[2]",
51              "//root/author[2]",
52              "//root/author[3]"};
53  
54      public static void main(String[] args) {
55          TestRunner.run(XPathTest.class);
56      }
57  
58      // Test case(s)
59      // -------------------------------------------------------------------------
60      public void testBug1116471() throws Exception {
61          String xml = "<a><b>Water T &amp; D-46816</b></a>";
62          String expected = "Water T & D-46816";
63  
64          Document doc = DocumentHelper.parseText(xml);
65          String result = (String) doc.selectObject("string(a/b[1])");
66          
67          assertEquals("xpath result not correct", expected, result);
68          
69          Node node = doc.selectSingleNode("a/b");
70          String result2 = node.getStringValue();
71          
72          assertEquals("xpath result not correct", expected, result2);        
73      }
74      
75      public void testXPaths() throws Exception {
76          int size = paths.length;
77  
78          for (int i = 0; i < size; i++) {
79              testXPath(paths[i]);
80          }
81      }
82  
83      public void testCreateXPathBug() throws Exception {
84          Element element = new DefaultElement("foo");
85          XPath xpath = element.createXPath("//bar");
86  
87          assertTrue(("created a valid XPath: " + xpath) != null);
88      }
89  
90      public void testBug857704() throws Exception {
91          Document doc = DocumentHelper
92                  .parseText("<foo xmlns:bar='http://blort'/>");
93          doc.selectNodes("//*[preceding-sibling::*]"); // shouldn't throw NPE
94      }
95  
96      public void testBooleanValueOf() throws Exception {
97          Document doc = DocumentHelper.parseText("<root><foo>blah</foo></root>");
98  
99          XPath path = new DefaultXPath("//root");
100         assertTrue(path.booleanValueOf(doc));
101 
102         path = new DefaultXPath("//root2");
103         assertFalse(path.booleanValueOf(doc));
104     }
105 
106     // Implementation methods
107     // -------------------------------------------------------------------------
108     protected void testXPath(String xpathExpression) {
109         log("Searched path: " + xpathExpression);
110 
111         XPath xpath = DocumentHelper.createXPath(xpathExpression);
112 
113         List list = xpath.selectNodes(document);
114 
115         if (list == null) {
116             log("null");
117         } else {
118             log("[");
119 
120             for (int i = 0, size = list.size(); i < size; i++) {
121                 Object object = list.get(i);
122 
123                 String text = "null";
124 
125                 if (object instanceof Node) {
126                     Node node = (Node) object;
127 
128                     text = node.asXML();
129                 } else if (object != null) {
130                     text = object.toString();
131                 }
132 
133                 log("    " + text);
134             }
135 
136             log("]");
137         }
138 
139         log("...........................................");
140     }
141 }
142 
143 /*
144  * Redistribution and use of this software and associated documentation
145  * ("Software"), with or without modification, are permitted provided that the
146  * following conditions are met:
147  * 
148  * 1. Redistributions of source code must retain copyright statements and
149  * notices. Redistributions must also contain a copy of this document.
150  * 
151  * 2. Redistributions in binary form must reproduce the above copyright notice,
152  * this list of conditions and the following disclaimer in the documentation
153  * and/or other materials provided with the distribution.
154  * 
155  * 3. The name "DOM4J" must not be used to endorse or promote products derived
156  * from this Software without prior written permission of MetaStuff, Ltd. For
157  * written permission, please contact dom4j-info@metastuff.com.
158  * 
159  * 4. Products derived from this Software may not be called "DOM4J" nor may
160  * "DOM4J" appear in their names without prior written permission of MetaStuff,
161  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
162  * 
163  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
164  * 
165  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
166  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
167  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
168  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
169  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
170  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
171  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
172  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
173  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
174  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
175  * POSSIBILITY OF SUCH DAMAGE.
176  * 
177  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
178  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/EmbeddedHandlerTest.html0000644000175000017500000003612310242117743023264 0ustar ebourgebourg EmbeddedHandlerTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.File;
13  
14  import org.dom4j.io.SAXReader;
15  
16  /***
17   * TestEmbeddedHandler
18   * 
19   * @author <a href="mailto:franz.beil@temis-group.com">FB </a>
20   */
21  public class EmbeddedHandlerTest extends AbstractTestCase {
22      private static final int MAIN_READER = 0;
23  
24      private static final int ON_END_READER = 1;
25  
26      protected String[] testDocuments = {"xml/test/FranzBeilMain.xml"};
27  
28      private StringBuffer[] results = {new StringBuffer(), new StringBuffer()};
29  
30      protected int test;
31  
32      public static void main(String[] args) {
33          TestRunner.run(EmbeddedHandlerTest.class);
34      }
35  
36      // ---------------------------------------------
37      // Test case(s)
38      // ---------------------------------------------
39      public void testMainReader() throws Exception {
40          test = MAIN_READER;
41          readDocuments();
42      }
43  
44      public void testOnEndReader() throws Exception {
45          test = ON_END_READER;
46          readDocuments();
47      }
48  
49      public void testBothReaders() throws Exception {
50          testMainReader();
51          testOnEndReader();
52  
53          if (!results[MAIN_READER].toString().equals(
54                  results[ON_END_READER].toString())) {
55              StringBuffer msg = new StringBuffer();
56              msg.append("Results of tests should be equal!\n");
57              msg.append("Results testMainReader():\n"
58                      + results[MAIN_READER].toString());
59              msg.append("Results testOnEndReader():\n"
60                      + results[ON_END_READER].toString());
61              throw new Exception(msg.toString());
62          }
63      }
64  
65      // ---------------------------------------------
66      // Implementation methods
67      // ---------------------------------------------
68      private void readDocuments() throws Exception {
69          for (int i = 0; i < testDocuments.length; i++) {
70              File testDoc = getFile(testDocuments[i]);
71              String mainDir = testDoc.getParent();
72              SAXReader reader = new SAXReader();
73              ElementHandler mainHandler = new MainHandler(mainDir);
74              reader.addHandler("/main/import", mainHandler);
75              getDocument(testDocuments[i], reader);
76          }
77      }
78  
79      // Handler classes
80      // ---------------------------------------------
81      class MainHandler implements ElementHandler {
82          private SAXReader mainReader;
83  
84          private String mainDir;
85  
86          public MainHandler(String dir) {
87              mainReader = new SAXReader();
88              mainDir = dir;
89              mainReader.addHandler("/import/stuff", new EmbeddedHandler());
90          }
91  
92          public void onStart(ElementPath path) {
93          }
94  
95          public void onEnd(ElementPath path) {
96              String href = path.getCurrent().attribute("href").getValue();
97              Element importRef = path.getCurrent();
98              Element parentElement = importRef.getParent();
99              SAXReader onEndReader = new SAXReader();
100             onEndReader.addHandler("/import/stuff", new EmbeddedHandler());
101 
102             File file = new File(mainDir + File.separator + href);
103             Element importElement = null;
104 
105             try {
106                 if (test == MAIN_READER) {
107                     importElement = mainReader.read(file).getRootElement();
108                 } else if (test == ON_END_READER) {
109                     importElement = onEndReader.read(file).getRootElement();
110                 }
111             } catch (Exception e) {
112                 // too bad that it's not possible to throw the exception at the
113                 // caller
114                 e.printStackTrace();
115             }
116 
117             // prune and replace
118             importRef.detach();
119             parentElement.add(importElement);
120         }
121     }
122 
123     public class EmbeddedHandler implements ElementHandler {
124         public void onStart(ElementPath path) {
125             results[test].append(path.getCurrent().attribute("name").getValue()
126                     + "\n");
127         }
128 
129         public void onEnd(ElementPath path) {
130         }
131     }
132 }
133 
134 /*
135  * Redistribution and use of this software and associated documentation
136  * ("Software"), with or without modification, are permitted provided that the
137  * following conditions are met:
138  * 
139  * 1. Redistributions of source code must retain copyright statements and
140  * notices. Redistributions must also contain a copy of this document.
141  * 
142  * 2. Redistributions in binary form must reproduce the above copyright notice,
143  * this list of conditions and the following disclaimer in the documentation
144  * and/or other materials provided with the distribution.
145  * 
146  * 3. The name "DOM4J" must not be used to endorse or promote products derived
147  * from this Software without prior written permission of MetaStuff, Ltd. For
148  * written permission, please contact dom4j-info@metastuff.com.
149  * 
150  * 4. Products derived from this Software may not be called "DOM4J" nor may
151  * "DOM4J" appear in their names without prior written permission of MetaStuff,
152  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
153  * 
154  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
155  * 
156  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
157  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
158  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
159  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
160  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
161  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
162  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
163  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
164  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
165  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
166  * POSSIBILITY OF SUCH DAMAGE.
167  * 
168  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
169  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/ParentTest.html0000644000175000017500000002556610242117740021534 0ustar ebourgebourg ParentTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.Iterator;
13  import java.util.List;
14  
15  /***
16   * A test harness to test the parent relationship and use of the {@link
17   * Node#asXPathResult} method.
18   * 
19   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
20   * @version $Revision: 1.3 $
21   */
22  public class ParentTest extends AbstractTestCase {
23      public static void main(String[] args) {
24          TestRunner.run(ParentTest.class);
25      }
26  
27      // Test case(s)
28      // -------------------------------------------------------------------------
29      public void testDocument() throws Exception {
30          testParentRelationship(document.getRootElement());
31      }
32  
33      public void testFragment() throws Exception {
34          DocumentFactory factory = new DocumentFactory();
35          Element root = factory.createElement("root");
36          Element first = root.addElement("child");
37          Element second = root.addElement("child");
38  
39          testXPathNode(root, first);
40          testXPathNode(root, second);
41      }
42  
43      // Implementation methods
44      // -------------------------------------------------------------------------
45      protected void testParentRelationship(Element parent, List content) {
46          for (Iterator iter = content.iterator(); iter.hasNext();) {
47              Object object = iter.next();
48  
49              if (object instanceof Element) {
50                  testParentRelationship((Element) object);
51              }
52  
53              testXPathNode(parent, (Node) object);
54          }
55      }
56  
57      protected void testParentRelationship(Element element) {
58          testParentRelationship(element, element.attributes());
59          testParentRelationship(element, element.content());
60      }
61  
62      protected void testXPathNode(Element parent, Node node) {
63          if (node.supportsParent()) {
64              log("Node: " + node);
65              log("Parent: " + parent);
66              log("getParent(): " + node.getParent());
67  
68              assertTrue("getParent() returns parent for: " + node, node
69                      .getParent() == parent);
70          } else {
71              // lets create an XPath node
72              Node xpathNode = node.asXPathResult(parent);
73              assertTrue("XPath Node supports parent for: " + xpathNode,
74                      xpathNode.supportsParent());
75              assertTrue("getParent() returns parent for: " + xpathNode,
76                      xpathNode.getParent() == parent);
77          }
78      }
79  }
80  
81  /*
82   * Redistribution and use of this software and associated documentation
83   * ("Software"), with or without modification, are permitted provided that the
84   * following conditions are met:
85   * 
86   * 1. Redistributions of source code must retain copyright statements and
87   * notices. Redistributions must also contain a copy of this document.
88   * 
89   * 2. Redistributions in binary form must reproduce the above copyright notice,
90   * this list of conditions and the following disclaimer in the documentation
91   * and/or other materials provided with the distribution.
92   * 
93   * 3. The name "DOM4J" must not be used to endorse or promote products derived
94   * from this Software without prior written permission of MetaStuff, Ltd. For
95   * written permission, please contact dom4j-info@metastuff.com.
96   * 
97   * 4. Products derived from this Software may not be called "DOM4J" nor may
98   * "DOM4J" appear in their names without prior written permission of MetaStuff,
99   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
100  * 
101  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
102  * 
103  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
104  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
105  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
106  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
107  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
108  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
109  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
110  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
111  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
112  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
113  * POSSIBILITY OF SUCH DAMAGE.
114  * 
115  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
116  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/tree/0000755000175000017500000000000012133227266017504 5ustar ebourgebourgdom4j-1.6.1/docs/xref-test/org/dom4j/tree/DefaultDocumentTest.html0000644000175000017500000003363510242117634024323 0ustar ebourgebourg DefaultDocumentTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.ByteArrayOutputStream;
13  
14  import org.dom4j.AbstractTestCase;
15  import org.dom4j.Document;
16  import org.dom4j.DocumentFactory;
17  import org.dom4j.DocumentHelper;
18  import org.dom4j.Element;
19  import org.dom4j.IllegalAddException;
20  import org.dom4j.io.OutputFormat;
21  import org.dom4j.io.XMLWriter;
22  
23  /***
24   * Some tests on DefaultDocument.
25   * 
26   * @author <a href="mailto:maartenc@users.sourceforge.net">Maarten Coene </a>
27   */
28  public class DefaultDocumentTest extends AbstractTestCase {
29      public static void main(String[] args) {
30          TestRunner.run(DefaultDocumentTest.class);
31      }
32  
33      // Test case(s)
34      // -------------------------------------------------------------------------
35      public void testDoubleRootElement() {
36          Document document = DocumentFactory.getInstance().createDocument();
37          document.addElement("root");
38  
39          Element root = DocumentFactory.getInstance().createElement(
40                  "anotherRoot");
41  
42          try {
43              document.add(root);
44              fail();
45          } catch (IllegalAddException e) {
46              String msg = e.getMessage();
47              assertTrue(msg.indexOf(root.toString()) != -1);
48          }
49      }
50  
51      public void testBug799656() throws Exception {
52          Document document = DocumentFactory.getInstance().createDocument();
53          Element el = document.addElement("root");
54          el.setText("text with an \u00FC in it"); // u00FC is umlaut
55  
56          System.out.println(document.asXML());
57  
58          DocumentHelper.parseText(document.asXML());
59      }
60  
61      public void testAsXMLWithEncoding() throws Exception {
62          DefaultDocument document = new DefaultDocument();
63          document.addElement("root");
64          document.setXMLEncoding("ISO-8859-1");
65  
66          Document doc = DocumentHelper.parseText("<?xml version='1.0' "
67                  + "encoding='ISO-8859-1'?><root/>");
68  
69          String xml1 = document.asXML();
70          String xml2 = doc.asXML();
71  
72          assertTrue(xml1.indexOf("ISO-8859-1") != -1);
73          assertTrue(xml2.indexOf("ISO-8859-1") != -1);
74      }
75  
76      public void testBug1156909() throws Exception {
77          Document doc = DocumentHelper.parseText("<?xml version='1.0' "
78                  + "encoding='ISO-8859-1'?><root/>");
79  
80          assertEquals("XMLEncoding not correct", "ISO-8859-1", doc
81                  .getXMLEncoding());
82      }
83  
84      public void testAsXMLWithEncodingAndContent() throws Exception {
85          DefaultDocument document = new DefaultDocument();
86          document.setXMLEncoding("UTF-16");
87          Element root = document.addElement("root");
88          root.setText("text with an \u00FC in it"); // u00FC is umlaut
89  
90          String xml = document.asXML();
91          assertTrue(xml.indexOf("UTF-16") != -1);
92          assertTrue(xml.indexOf('\u00FC') != -1);
93      }
94  
95      public void testEncoding() throws Exception {
96          Document document = DocumentFactory.getInstance().createDocument(
97                  "koi8-r");
98          Element el = document.addElement("root");
99          el.setText("text with an \u00FC in it"); // u00FC is umlaut
100 
101         System.out.println(document.asXML());
102 
103         ByteArrayOutputStream out = new ByteArrayOutputStream();
104         OutputFormat of = OutputFormat.createPrettyPrint();
105         of.setEncoding("koi8-r");
106 
107         XMLWriter writer = new XMLWriter(out, of);
108         writer.write(document);
109 
110         String result = out.toString("koi8-r");
111         System.out.println(result);
112 
113         Document doc2 = DocumentHelper.parseText(result);
114         // System.out.println(doc2.asXML());
115 
116     }
117 }
118 
119 /*
120  * Redistribution and use of this software and associated documentation
121  * ("Software"), with or without modification, are permitted provided that the
122  * following conditions are met:
123  * 
124  * 1. Redistributions of source code must retain copyright statements and
125  * notices. Redistributions must also contain a copy of this document.
126  * 
127  * 2. Redistributions in binary form must reproduce the above copyright notice,
128  * this list of conditions and the following disclaimer in the documentation
129  * and/or other materials provided with the distribution.
130  * 
131  * 3. The name "DOM4J" must not be used to endorse or promote products derived
132  * from this Software without prior written permission of MetaStuff, Ltd. For
133  * written permission, please contact dom4j-info@metastuff.com.
134  * 
135  * 4. Products derived from this Software may not be called "DOM4J" nor may
136  * "DOM4J" appear in their names without prior written permission of MetaStuff,
137  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
138  * 
139  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
140  * 
141  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
142  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
143  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
144  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
145  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
146  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
147  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
148  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
149  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
150  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
151  * POSSIBILITY OF SUCH DAMAGE.
152  * 
153  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
154  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/tree/package-summary.html0000644000175000017500000000477410242117710023463 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.tree

Class Summary
CDataTest
DefaultDocumentTest
DefaultElementTest
NamespaceCacheTest
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref-test/org/dom4j/tree/package-frame.html0000644000175000017500000000207310242117603023047 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.tree

org.dom4j.tree

Classes

  • CDataTest
  • DefaultDocumentTest
  • DefaultElementTest
  • NamespaceCacheTest
dom4j-1.6.1/docs/xref-test/org/dom4j/tree/NamespaceCacheTest.html0000644000175000017500000003166210242117745024061 0ustar ebourgebourg NamespaceCacheTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.AbstractTestCase;
13  import org.dom4j.Namespace;
14  
15  /***
16   * A test harness to test the performance of the NamespaceCache
17   * 
18   * @author <a href="mailto:bfinnell@users.sourceforge.net">Brett Finnell </a>
19   */
20  public class NamespaceCacheTest extends AbstractTestCase {
21      private static final int THREADCOUNT = 50;
22  
23      private static final int ITERATIONCOUNT = 10000;
24  
25      public static void main(String[] args) {
26          TestRunner.run(NamespaceCacheTest.class);
27      }
28  
29      // Test case(s)
30      // -------------------------------------------------------------------------
31      public void testGetSameNamespaceSingleThread() {
32          long start = System.currentTimeMillis();
33          SameNSTest test = new SameNSTest();
34          test.run();
35  
36          long end = System.currentTimeMillis();
37          System.out.println("Same NS Single took " + (end - start) + " ms");
38      }
39  
40      public void testGetSameNamespaceMultiThread() throws Exception {
41          long start = System.currentTimeMillis();
42          runMultiThreadedTest(new SameNSTest());
43  
44          long end = System.currentTimeMillis();
45          System.out.println("Different NS Single took " + (end - start) + " ms");
46      }
47  
48      public void testGetNewNamespaceSingleThread() {
49          long start = System.currentTimeMillis();
50          DifferentNSTest test = new DifferentNSTest();
51          test.run();
52  
53          long end = System.currentTimeMillis();
54          System.out.println("Same NS Multi took " + (end - start) + " ms");
55      }
56  
57      public void testGetNewNamespaceMultiThread() throws Exception {
58          long start = System.currentTimeMillis();
59          runMultiThreadedTest(new DifferentNSTest());
60  
61          long end = System.currentTimeMillis();
62          System.out.println("Different NS Multi took " + (end - start) + " ms");
63      }
64  
65      private void runMultiThreadedTest(Runnable test) throws Exception {
66          // Make the threads
67          Thread[] threads = new Thread[THREADCOUNT];
68  
69          for (int i = 0; i < THREADCOUNT; i++) {
70              threads[i] = new Thread(new SameNSTest());
71          }
72  
73          // Start the threads
74          for (int j = 0; j < THREADCOUNT; j++) {
75              threads[j].start();
76          }
77  
78          // Join with the threads
79          for (int k = 0; k < THREADCOUNT; k++) {
80              threads[k].join();
81          }
82      }
83  
84      private class SameNSTest implements Runnable {
85          public void run() {
86              NamespaceCache cache = new NamespaceCache();
87  
88              for (int i = 0; i < ITERATIONCOUNT; i++) {
89                  Namespace ns = cache.get("prefix", "uri");
90              }
91          }
92      }
93  
94      private class DifferentNSTest implements Runnable {
95          public void run() {
96              NamespaceCache cache = new NamespaceCache();
97  
98              for (int i = 0; i < ITERATIONCOUNT; i++) {
99                  Namespace ns = cache.get("prefix", Integer.toString(i));
100             }
101         }
102     }
103 }
104 
105 /*
106  * Redistribution and use of this software and associated documentation
107  * ("Software"), with or without modification, are permitted provided that the
108  * following conditions are met:
109  * 
110  * 1. Redistributions of source code must retain copyright statements and
111  * notices. Redistributions must also contain a copy of this document.
112  * 
113  * 2. Redistributions in binary form must reproduce the above copyright notice,
114  * this list of conditions and the following disclaimer in the documentation
115  * and/or other materials provided with the distribution.
116  * 
117  * 3. The name "DOM4J" must not be used to endorse or promote products derived
118  * from this Software without prior written permission of MetaStuff, Ltd. For
119  * written permission, please contact dom4j-info@metastuff.com.
120  * 
121  * 4. Products derived from this Software may not be called "DOM4J" nor may
122  * "DOM4J" appear in their names without prior written permission of MetaStuff,
123  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
124  * 
125  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
126  * 
127  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
128  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
129  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
130  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
131  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
132  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
133  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
134  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
135  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
136  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
137  * POSSIBILITY OF SUCH DAMAGE.
138  * 
139  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
140  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/tree/DefaultElementTest.html0000644000175000017500000003714510242117706024136 0ustar ebourgebourg DefaultElementTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import junit.textui.TestRunner;
11  import org.dom4j.AbstractTestCase;
12  import org.dom4j.Document;
13  import org.dom4j.DocumentFactory;
14  import org.dom4j.DocumentHelper;
15  import org.dom4j.Element;
16  import org.dom4j.Node;
17  
18  import java.util.List;
19  
20  /***
21   * JUnit tests for <code>DefaultElement</code>.
22   * 
23   * @author Maarten Coene
24   */
25  public class DefaultElementTest extends AbstractTestCase {
26      public static void main(String[] args) {
27          TestRunner.run(DefaultElementTest.class);
28      }
29  
30      // Test case(s)
31      // -------------------------------------------------------------------------
32      public void testParentAfterSetContent() throws Exception {
33              Document doc = DocumentHelper.parseText("<root>" + "<a>a</a>"
34                  + "<b>b</b>" + "<x>x</x>" + "<d>d</d>" + "</root>");
35              Node x = doc.selectSingleNode("/root/x");
36              List content = doc.getRootElement().content();
37              int position = content.indexOf(x);
38              Element c = DocumentHelper.createElement("c");
39              c.setText("c");
40              content.add(position, c);
41              assertNotNull(c.getParent());
42              doc.getRootElement().setContent(content);
43              assertNotNull("Parent is null of setting content", c.getParent());
44          }
45  
46      public void testGetStringValue() throws Exception {
47          Document doc = getDocument("xml/test/test_text.xml");
48          Element message = doc.getRootElement();
49          
50          String text = message.getStringValue();
51          assertEquals("String value incorrect", "This should work", text.trim());
52          
53          String xpathText = (String) doc
54                  .selectObject("normalize-space(/message)");
55          assertEquals("xpath value incorrect", "This should work", xpathText);
56      }
57      
58      public void testBug894878() {
59          Element foo = DocumentFactory.getInstance().createElement("foo");
60          foo.addText("bla").addAttribute("foo", "bar");
61          assertEquals("<foo foo=\"bar\">bla</foo>", foo.asXML());
62  
63          foo = DocumentFactory.getInstance().createElement("foo");
64          foo.addAttribute("foo", "bar").addText("bla");
65          assertEquals("<foo foo=\"bar\">bla</foo>", foo.asXML());
66      }
67  
68      public void testGetNamespacesForURI() throws Exception {
69          String xml = "<schema targetNamespace='http://SharedTest.org/xsd' "
70                  + "        xmlns='http://www.w3.org/2001/XMLSchema' "
71                  + "        xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"
72                  + "    <complexType name='AllStruct'>" + "        <all>"
73                  + "            <element name='arString' type='xsd:string'/>"
74                  + "            <element name='varInt' type='xsd:int'/>"
75                  + "        </all>" + "    </complexType>" + "</schema>";
76          Document doc = DocumentHelper.parseText(xml);
77          Element schema = doc.getRootElement();
78          List namespaces = schema
79                  .getNamespacesForURI("http://www.w3.org/2001/XMLSchema");
80  
81          assertNotNull(namespaces);
82          assertEquals(2, namespaces.size());
83      }
84  
85      public void testDeclaredNamespaces() throws Exception {
86          String xml = "<a xmlns:ns1=\"uri1\">" + "    <ns1:b/>"
87                  + "    <ns2:c xmlns:ns2=\"uri2\"/>" + "</a>";
88          Document doc = DocumentHelper.parseText(xml);
89  
90          Element a = doc.getRootElement();
91          List ns = a.declaredNamespaces();
92          assertEquals(1, ns.size());
93          assertSame(a.getNamespaceForPrefix("ns1"), ns.get(0));
94  
95          Element b = a.element("b");
96          ns = b.declaredNamespaces();
97          assertEquals(0, ns.size());
98  
99          Element c = a.element("c");
100         ns = c.declaredNamespaces();
101         assertEquals(1, ns.size());
102         assertSame(c.getNamespaceForPrefix("ns2"), ns.get(0));
103     }
104 
105     public void testAdditionalNamespaces() throws Exception {
106         String xml = "<a xmlns:ns1=\"uri1\">" + "    <ns1:b/>"
107                 + "    <ns2:c xmlns:ns2=\"uri2\"/>" + "</a>";
108         Document doc = DocumentHelper.parseText(xml);
109 
110         Element a = doc.getRootElement();
111         List ns = a.additionalNamespaces();
112         assertEquals(1, ns.size());
113         assertSame(a.getNamespaceForPrefix("ns1"), ns.get(0));
114 
115         Element b = a.element("b");
116         ns = b.additionalNamespaces();
117         assertEquals(0, ns.size());
118 
119         Element c = a.element("c");
120         ns = c.additionalNamespaces();
121         assertEquals(0, ns.size());
122     }
123 }
124 
125 /*
126  * Redistribution and use of this software and associated documentation
127  * ("Software"), with or without modification, are permitted provided that the
128  * following conditions are met:
129  * 
130  * 1. Redistributions of source code must retain copyright statements and
131  * notices. Redistributions must also contain a copy of this document.
132  * 
133  * 2. Redistributions in binary form must reproduce the above copyright notice,
134  * this list of conditions and the following disclaimer in the documentation
135  * and/or other materials provided with the distribution.
136  * 
137  * 3. The name "DOM4J" must not be used to endorse or promote products derived
138  * from this Software without prior written permission of MetaStuff, Ltd. For
139  * written permission, please contact dom4j-info@metastuff.com.
140  * 
141  * 4. Products derived from this Software may not be called "DOM4J" nor may
142  * "DOM4J" appear in their names without prior written permission of MetaStuff,
143  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
144  * 
145  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
146  * 
147  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
148  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
149  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
150  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
151  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
152  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
153  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
154  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
155  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
156  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
157  * POSSIBILITY OF SUCH DAMAGE.
158  * 
159  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
160  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/tree/CDataTest.html0000644000175000017500000001671410242117726022215 0ustar ebourgebourg CDataTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.AbstractTestCase;
13  
14  /***
15   * DOCUMENT ME!
16   * 
17   * @author Maarten Coene
18   */
19  public class CDataTest extends AbstractTestCase {
20      public static void main(String[] args) {
21          TestRunner.run(CDataTest.class);
22      }
23  
24      public void testNullTest() {
25          DefaultCDATA cdata = new DefaultCDATA(null);
26          assertEquals("CData not correct", "<![CDATA[]]>", cdata.asXML());
27      }
28  
29      public void testNormal() {
30          DefaultCDATA cdata = new DefaultCDATA("sample");
31          assertEquals("CData not correct", "<![CDATA[sample]]>", cdata.asXML());
32      }
33      
34      public void testLongCData() throws Exception {
35          getDocument("xml/test/longCDATA.xml");
36      }
37  }
38  
39  /*
40   * Redistribution and use of this software and associated documentation
41   * ("Software"), with or without modification, are permitted provided that the
42   * following conditions are met:
43   * 
44   * 1. Redistributions of source code must retain copyright statements and
45   * notices. Redistributions must also contain a copy of this document.
46   * 
47   * 2. Redistributions in binary form must reproduce the above copyright notice,
48   * this list of conditions and the following disclaimer in the documentation
49   * and/or other materials provided with the distribution.
50   * 
51   * 3. The name "DOM4J" must not be used to endorse or promote products derived
52   * from this Software without prior written permission of MetaStuff, Ltd. For
53   * written permission, please contact dom4j-info@metastuff.com.
54   * 
55   * 4. Products derived from this Software may not be called "DOM4J" nor may
56   * "DOM4J" appear in their names without prior written permission of MetaStuff,
57   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
58   * 
59   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
60   * 
61   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
62   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
63   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
64   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
65   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
66   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
67   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
68   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
69   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
70   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
71   * POSSIBILITY OF SUCH DAMAGE.
72   * 
73   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
74   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/IndexedElementTest.html0000644000175000017500000002415110242117626023165 0ustar ebourgebourg IndexedElementTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.List;
13  
14  import org.dom4j.util.IndexedDocumentFactory;
15  
16  /***
17   * A test harness for the IndexedElement implementation
18   * 
19   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
20   * @version $Revision: 1.3 $
21   */
22  public class IndexedElementTest extends AbstractTestCase {
23      public static void main(String[] args) {
24          TestRunner.run(IndexedElementTest.class);
25      }
26  
27      // Test case(s)
28      // -------------------------------------------------------------------------
29      public void testXPaths() throws Exception {
30          testXPath("//author");
31      }
32  
33      // Implementation methods
34      // -------------------------------------------------------------------------
35      protected void testXPath(String xpath) {
36          List list = document.selectNodes(xpath);
37  
38          log("Searched path: " + xpath);
39          log("Found        : " + list.size() + " result(s)");
40  
41          log("Results");
42  
43          if (list == null) {
44              log("null");
45          } else {
46              log("[");
47  
48              for (int i = 0, size = list.size(); i < size; i++) {
49                  Object object = list.get(i);
50                  String text = "null";
51  
52                  if (object instanceof Node) {
53                      Node node = (Node) object;
54                      text = node.asXML();
55                  } else if (object != null) {
56                      text = object.toString();
57                  }
58  
59                  log("    " + text);
60              }
61  
62              log("]");
63          }
64  
65          log("...........................................");
66  
67          assertTrue("Found some results", list.size() > 0);
68      }
69  
70      protected Document createDocument() {
71          return IndexedDocumentFactory.getInstance().createDocument();
72      }
73  }
74  
75  /*
76   * Redistribution and use of this software and associated documentation
77   * ("Software"), with or without modification, are permitted provided that the
78   * following conditions are met:
79   * 
80   * 1. Redistributions of source code must retain copyright statements and
81   * notices. Redistributions must also contain a copy of this document.
82   * 
83   * 2. Redistributions in binary form must reproduce the above copyright notice,
84   * this list of conditions and the following disclaimer in the documentation
85   * and/or other materials provided with the distribution.
86   * 
87   * 3. The name "DOM4J" must not be used to endorse or promote products derived
88   * from this Software without prior written permission of MetaStuff, Ltd. For
89   * written permission, please contact dom4j-info@metastuff.com.
90   * 
91   * 4. Products derived from this Software may not be called "DOM4J" nor may
92   * "DOM4J" appear in their names without prior written permission of MetaStuff,
93   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
94   * 
95   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
96   * 
97   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
98   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
99   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
100  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
101  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
102  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
103  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
104  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
105  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
106  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
107  * POSSIBILITY OF SUCH DAMAGE.
108  * 
109  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
110  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/swing/0000755000175000017500000000000012133227266017674 5ustar ebourgebourgdom4j-1.6.1/docs/xref-test/org/dom4j/swing/package-summary.html0000644000175000017500000000375710242117707023661 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.swing

Class Summary
TableModelTest
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref-test/org/dom4j/swing/TableModelTest.html0000644000175000017500000003136010242117723023430 0ustar ebourgebourg TableModelTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.swing;
9   
10  import junit.textui.TestRunner;
11  
12  import javax.swing.table.TableModel;
13  
14  import org.dom4j.AbstractTestCase;
15  import org.dom4j.Document;
16  
17  /***
18   * Tests the Swing TableModel using a dom4j document.
19   * 
20   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
21   * @version $Revision: 1.4 $
22   */
23  public class TableModelTest extends AbstractTestCase {
24      public static void main(String[] args) {
25          TestRunner.run(TableModelTest.class);
26      }
27  
28      public void testServletTable() throws Exception {
29          Document document = getDocument("/xml/web.xml");
30  
31          XMLTableDefinition tableDefinition = new XMLTableDefinition();
32          tableDefinition.setRowExpression("/web-app/servlet");
33          tableDefinition.addStringColumn("Name", "servlet-name");
34          tableDefinition.addStringColumn("Class", "servlet-class");
35  
36          String mapping = "../servlet-mapping[servlet-name=$Name]/url-pattern";
37          tableDefinition.addStringColumn("Mapping", mapping);
38  
39          XMLTableModel tableModel = new XMLTableModel(tableDefinition, document);
40  
41          // now lets test the values come out
42          assertEquals("correct row count", tableModel.getRowCount(), 2);
43          assertEquals("correct column count", tableModel.getColumnCount(), 3);
44  
45          assertColumnNameEquals(tableModel, 0, "Name");
46          assertColumnNameEquals(tableModel, 1, "Class");
47          assertColumnNameEquals(tableModel, 2, "Mapping");
48  
49          assertCellEquals(tableModel, 0, 0, "snoop");
50          assertCellEquals(tableModel, 1, 0, "file");
51          assertCellEquals(tableModel, 0, 1, "SnoopServlet");
52          assertCellEquals(tableModel, 1, 1, "ViewFile");
53          assertCellEquals(tableModel, 0, 2, "/foo/snoop");
54          assertCellEquals(tableModel, 1, 2, "");
55      }
56  
57      public void testServletTableViaXMLDescription() throws Exception {
58          Document definition = getDocument("/xml/swing/tableForWeb.xml");
59          Document document = getDocument("/xml/web.xml");
60  
61          XMLTableModel tableModel = new XMLTableModel(definition, document);
62  
63          // now lets test the values come out
64          assertEquals("correct row count", tableModel.getRowCount(), 2);
65          assertEquals("correct column count", tableModel.getColumnCount(), 3);
66  
67          assertColumnNameEquals(tableModel, 0, "Name");
68          assertColumnNameEquals(tableModel, 1, "Class");
69          assertColumnNameEquals(tableModel, 2, "Mapping");
70  
71          assertCellEquals(tableModel, 0, 0, "snoop");
72          assertCellEquals(tableModel, 1, 0, "file");
73          assertCellEquals(tableModel, 0, 1, "SnoopServlet");
74          assertCellEquals(tableModel, 1, 1, "ViewFile");
75          assertCellEquals(tableModel, 0, 2, "/foo/snoop");
76          assertCellEquals(tableModel, 1, 2, "");
77      }
78  
79      protected void assertColumnNameEquals(TableModel tableModel,
80              int columnIndex, String name) {
81          assertEquals("Column name correct for index: " + columnIndex, name,
82                  tableModel.getColumnName(columnIndex));
83      }
84  
85      protected void assertCellEquals(TableModel tableModel, int rowIndex,
86              int columnIndex, Object value) {
87          assertEquals("Cell value at row: " + rowIndex + " col: " + columnIndex,
88                  value, tableModel.getValueAt(rowIndex, columnIndex));
89      }
90  }
91  
92  /*
93   * Redistribution and use of this software and associated documentation
94   * ("Software"), with or without modification, are permitted provided that the
95   * following conditions are met:
96   * 
97   * 1. Redistributions of source code must retain copyright statements and
98   * notices. Redistributions must also contain a copy of this document.
99   * 
100  * 2. Redistributions in binary form must reproduce the above copyright notice,
101  * this list of conditions and the following disclaimer in the documentation
102  * and/or other materials provided with the distribution.
103  * 
104  * 3. The name "DOM4J" must not be used to endorse or promote products derived
105  * from this Software without prior written permission of MetaStuff, Ltd. For
106  * written permission, please contact dom4j-info@metastuff.com.
107  * 
108  * 4. Products derived from this Software may not be called "DOM4J" nor may
109  * "DOM4J" appear in their names without prior written permission of MetaStuff,
110  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
111  * 
112  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
113  * 
114  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
115  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
116  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
117  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
118  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
119  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
120  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
121  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
122  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
123  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
124  * POSSIBILITY OF SUCH DAMAGE.
125  * 
126  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
127  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/swing/package-frame.html0000644000175000017500000000130210242117744023237 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.swing

org.dom4j.swing

Classes

  • TableModelTest
dom4j-1.6.1/docs/xref-test/org/dom4j/ParseTextTest.html0000644000175000017500000002174510242117736022222 0ustar ebourgebourg ParseTextTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  /***
13   * Tests the {@link DocumentHelper#parseText(String)}method.
14   * 
15   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
16   * @version $Revision: 1.3 $
17   */
18  public class ParseTextTest extends AbstractTestCase {
19      protected String xmlText = 
20          "<root><author name='James'><location>Paris</location></author></root>";
21  
22      public static void main(String[] args) {
23          TestRunner.run(ParseTextTest.class);
24      }
25  
26      // Test case(s)
27      // -------------------------------------------------------------------------
28      public void testDocument() throws Exception {
29          assertTrue("Document is not null", document != null);
30  
31          Element root = document.getRootElement();
32  
33          assertTrue("Root element is not null", root != null);
34  
35          Element author = root.element("author");
36  
37          assertTrue("Author element is not null", author != null);
38  
39          String name = author.attributeValue("name");
40  
41          assertEquals("Name attribute matches", name, "James");
42  
43          String location = document.valueOf("/root/author/location");
44  
45          assertEquals("Location element matches", location, "Paris");
46      }
47  
48      // Implementation methods
49      // -------------------------------------------------------------------------
50      protected void setUp() throws Exception {
51          super.setUp();
52          document = DocumentHelper.parseText(xmlText);
53      }
54  }
55  
56  /*
57   * Redistribution and use of this software and associated documentation
58   * ("Software"), with or without modification, are permitted provided that the
59   * following conditions are met:
60   * 
61   * 1. Redistributions of source code must retain copyright statements and
62   * notices. Redistributions must also contain a copy of this document.
63   * 
64   * 2. Redistributions in binary form must reproduce the above copyright notice,
65   * this list of conditions and the following disclaimer in the documentation
66   * and/or other materials provided with the distribution.
67   * 
68   * 3. The name "DOM4J" must not be used to endorse or promote products derived
69   * from this Software without prior written permission of MetaStuff, Ltd. For
70   * written permission, please contact dom4j-info@metastuff.com.
71   * 
72   * 4. Products derived from this Software may not be called "DOM4J" nor may
73   * "DOM4J" appear in their names without prior written permission of MetaStuff,
74   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
75   * 
76   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
77   * 
78   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
79   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
81   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
82   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
83   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
84   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
85   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
86   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
87   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
88   * POSSIBILITY OF SUCH DAMAGE.
89   * 
90   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
91   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/package-summary.html0000644000175000017500000002214410242117725022521 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j

Class Summary
AbstractTestCase
AddAttributeTest
AddNodeTest
AttributeDetachTest
BackedListTest
CloneTest
ContentTest
CopyTest
DetachTest
DocTypeTest
ElementByIDTest
EmbeddedHandlerTest
GetQNamesTest
GetXMLEncodingTest
HTMLWriterTest
IndexedElementTest
IsTextOnlyTest
IteratorTest
LineFeedTest
MakeElementTest
MergeTextTest
NamespaceTest
NamespacesTest
NodeTypeNameTest
NormalizeTest
NullAttributesTest
ParentTest
ParseTextTest
ProcessingInstructionTest
RoundTripTest
SAXContentHandlerTest
SerializeTest
SetContentTest
SetTextTest
ThreadingTest
UserDataTest
ValidationTest
XMLResultTest
XMLSpaceAttributeTest
XMLWriterTest
XPathBugTest
XPathExamplesTest
XPathTest
XSLTTest
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref-test/org/dom4j/UserDataTest.html0000644000175000017500000003421210242117763022004 0ustar ebourgebourg UserDataTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.io.SAXReader;
13  import org.dom4j.util.UserDataAttribute;
14  import org.dom4j.util.UserDataDocumentFactory;
15  import org.dom4j.util.UserDataElement;
16  
17  /***
18   * Tests the UserDataDocumentFactory
19   * 
20   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
21   * @version $Revision: 1.4 $
22   */
23  public class UserDataTest extends AbstractTestCase {
24      /*** Input XML file to read */
25      private static final String INPUT_XML_FILE = "/xml/web.xml";
26  
27      private Object userData = new Double(1.23456);
28  
29      public static void main(String[] args) {
30          TestRunner.run(UserDataTest.class);
31      }
32  
33      // Test case(s)
34      // -------------------------------------------------------------------------
35      public void testSetData() throws Exception {
36          Element root = getRootElement();
37  
38          assertTrue("Element instanceof UserDataElement",
39                  root instanceof UserDataElement);
40  
41          root.setData(userData);
42  
43          assertTrue("Stored user data!", root.getData() == userData);
44  
45          log("root: " + root);
46  
47          assertUserData(root, userData);
48  
49          Element cloned = (Element) root.clone();
50          assertTrue("Cloned new instance", cloned != root);
51          assertUserData(cloned, userData);
52  
53          cloned = root.createCopy();
54          assertTrue("Cloned new instance", cloned != root);
55          assertUserData(cloned, userData);
56      }
57  
58      public void testCloneAttribute() throws Exception {
59          Element root = getRootElement();
60          root.addAttribute("name", "value");
61  
62          Attribute attribute = root.attribute("name");
63          assertTrue(attribute instanceof UserDataAttribute);
64  
65          Element cloned = (Element) root.clone();
66          Attribute clonedAttribute = cloned.attribute("name");
67          assertTrue(clonedAttribute instanceof UserDataAttribute);
68      }
69  
70      public void testNewAdditions() throws Exception {
71          Element root = getRootElement();
72  
73          Element newElement = root.addElement("foo1234");
74          assertTrue("New Element is a UserDataElement",
75                  newElement instanceof UserDataElement);
76  
77          root.addAttribute("bar456", "123");
78  
79          Attribute newAttribute = root.attribute("bar456");
80  
81          assertTrue("New Attribute is a UserDataAttribute",
82                  newAttribute instanceof UserDataAttribute);
83      }
84  
85      public void testNewDocument() throws Exception {
86          DocumentFactory factory = UserDataDocumentFactory.getInstance();
87          Document document = factory.createDocument();
88  
89          Element root = document.addElement("root");
90          assertTrue("Root Element is a UserDataElement",
91                  root instanceof UserDataElement);
92  
93          Element newElement = root.addElement("foo1234");
94          assertTrue("New Element is a UserDataElement",
95                  newElement instanceof UserDataElement);
96  
97          root.addAttribute("bar456", "123");
98  
99          Attribute newAttribute = root.attribute("bar456");
100 
101         assertTrue("New Attribute is a UserDataAttribute",
102                 newAttribute instanceof UserDataAttribute);
103     }
104 
105     // Implementation methods
106     // -------------------------------------------------------------------------
107     protected void assertUserData(Element root, Object data) throws Exception {
108         Object result = root.getData();
109 
110         assertTrue("No user data!", result != null);
111         assertTrue("Stored user data correctly", data.equals(result));
112     }
113 
114     protected void setUp() throws Exception {
115         super.setUp();
116 
117         SAXReader reader = new SAXReader();
118         reader.setDocumentFactory(UserDataDocumentFactory.getInstance());
119         document = getDocument(INPUT_XML_FILE, reader);
120     }
121 }
122 
123 /*
124  * Redistribution and use of this software and associated documentation
125  * ("Software"), with or without modification, are permitted provided that the
126  * following conditions are met:
127  * 
128  * 1. Redistributions of source code must retain copyright statements and
129  * notices. Redistributions must also contain a copy of this document.
130  * 
131  * 2. Redistributions in binary form must reproduce the above copyright notice,
132  * this list of conditions and the following disclaimer in the documentation
133  * and/or other materials provided with the distribution.
134  * 
135  * 3. The name "DOM4J" must not be used to endorse or promote products derived
136  * from this Software without prior written permission of MetaStuff, Ltd. For
137  * written permission, please contact dom4j-info@metastuff.com.
138  * 
139  * 4. Products derived from this Software may not be called "DOM4J" nor may
140  * "DOM4J" appear in their names without prior written permission of MetaStuff,
141  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
142  * 
143  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
144  * 
145  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
146  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
147  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
148  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
149  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
150  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
151  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
152  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
153  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
154  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
155  * POSSIBILITY OF SUCH DAMAGE.
156  * 
157  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
158  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/AddAttributeTest.html0000644000175000017500000002146410242117712022647 0ustar ebourgebourg AddAttributeTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  /***
13   * A test harness to test the addAttribute() methods on attributes
14   * 
15   * @author <a href="mailto:maartenc@users.sourceforge.net">Maarten Coene </a>
16   */
17  public class AddAttributeTest extends AbstractTestCase {
18      public static void main(String[] args) {
19          TestRunner.run(AddAttributeTest.class);
20      }
21  
22      // Test case(s)
23      // -------------------------------------------------------------------------
24      public void testAddAttributeNormalValue() throws Exception {
25          String testAttributeName = "testAtt";
26          String testAttributeValue = "testValue";
27  
28          Node authorNode = document.selectSingleNode("//root/author[1]");
29  
30          assertTrue(authorNode instanceof Element);
31  
32          Element authorEl = (Element) authorNode;
33          authorEl.addAttribute(testAttributeName, testAttributeValue);
34  
35          assertEquals(3, authorEl.attributeCount());
36          assertEquals(testAttributeValue, authorEl
37                  .attributeValue(testAttributeName));
38      }
39  
40      public void testAddAttributeNullValue() throws Exception {
41          String testAttributeName = "location";
42          String testAttributeValue = null;
43  
44          Node authorNode = document.selectSingleNode("//root/author[1]");
45  
46          assertTrue(authorNode instanceof Element);
47  
48          Element authorEl = (Element) authorNode;
49          authorEl.addAttribute(testAttributeName, testAttributeValue);
50  
51          assertEquals(1, authorEl.attributeCount());
52          assertNull(authorEl.attributeValue(testAttributeName));
53      }
54  }
55  
56  /*
57   * Redistribution and use of this software and associated documentation
58   * ("Software"), with or without modification, are permitted provided that the
59   * following conditions are met:
60   * 
61   * 1. Redistributions of source code must retain copyright statements and
62   * notices. Redistributions must also contain a copy of this document.
63   * 
64   * 2. Redistributions in binary form must reproduce the above copyright notice,
65   * this list of conditions and the following disclaimer in the documentation
66   * and/or other materials provided with the distribution.
67   * 
68   * 3. The name "DOM4J" must not be used to endorse or promote products derived
69   * from this Software without prior written permission of MetaStuff, Ltd. For
70   * written permission, please contact dom4j-info@metastuff.com.
71   * 
72   * 4. Products derived from this Software may not be called "DOM4J" nor may
73   * "DOM4J" appear in their names without prior written permission of MetaStuff,
74   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
75   * 
76   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
77   * 
78   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
79   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
81   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
82   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
83   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
84   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
85   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
86   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
87   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
88   * POSSIBILITY OF SUCH DAMAGE.
89   * 
90   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
91   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/XMLResultTest.html0000644000175000017500000002445610242117715022141 0ustar ebourgebourg XMLResultTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.StringWriter;
13  
14  import javax.xml.transform.Result;
15  import javax.xml.transform.Source;
16  import javax.xml.transform.Transformer;
17  import javax.xml.transform.TransformerFactory;
18  
19  import org.dom4j.io.DocumentSource;
20  import org.dom4j.io.OutputFormat;
21  import org.dom4j.io.XMLResult;
22  import org.dom4j.io.XMLWriter;
23  
24  /***
25   * Test harness for the XMLResult which acts as a JAXP Result
26   * 
27   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
28   * @version $Revision: 1.3 $
29   */
30  public class XMLResultTest extends AbstractTestCase {
31      protected static final boolean VERBOSE = false;
32  
33      public static void main(String[] args) {
34          TestRunner.run(XMLResultTest.class);
35      }
36  
37      // Test case(s)
38      // -------------------------------------------------------------------------
39      public void testWriter() throws Exception {
40          // load a default transformer
41          TransformerFactory factory = TransformerFactory.newInstance();
42          Transformer transformer = factory.newTransformer();
43  
44          // use dom4j document as the source
45          Source source = new DocumentSource(document);
46  
47          // use pretty print format and a buffer for the result
48          OutputFormat format = OutputFormat.createCompactFormat();
49          StringWriter buffer = new StringWriter();
50          Result result = new XMLResult(buffer, format);
51  
52          // now lets transform
53          transformer.transform(source, result);
54  
55          String text = buffer.toString();
56  
57          if (VERBOSE) {
58              log("Using JAXP and XMLResult the document is:- ");
59              log(text);
60          }
61  
62          StringWriter out = new StringWriter();
63  
64          XMLWriter writer = new XMLWriter(out, format);
65          writer.write(document);
66  
67          String text2 = out.toString();
68  
69          if (VERBOSE) {
70              log("Using XMLWriter the text is:-");
71              log(text2);
72          }
73  
74          assertEquals("The text output should be identical", text2, text);
75      }
76  }
77  
78  /*
79   * Redistribution and use of this software and associated documentation
80   * ("Software"), with or without modification, are permitted provided that the
81   * following conditions are met:
82   * 
83   * 1. Redistributions of source code must retain copyright statements and
84   * notices. Redistributions must also contain a copy of this document.
85   * 
86   * 2. Redistributions in binary form must reproduce the above copyright notice,
87   * this list of conditions and the following disclaimer in the documentation
88   * and/or other materials provided with the distribution.
89   * 
90   * 3. The name "DOM4J" must not be used to endorse or promote products derived
91   * from this Software without prior written permission of MetaStuff, Ltd. For
92   * written permission, please contact dom4j-info@metastuff.com.
93   * 
94   * 4. Products derived from this Software may not be called "DOM4J" nor may
95   * "DOM4J" appear in their names without prior written permission of MetaStuff,
96   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
97   * 
98   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
99   * 
100  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
101  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
102  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
103  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
104  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
105  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
106  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
107  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
108  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
109  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
110  * POSSIBILITY OF SUCH DAMAGE.
111  * 
112  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
113  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/dom/0000755000175000017500000000000012133227266017324 5ustar ebourgebourgdom4j-1.6.1/docs/xref-test/org/dom4j/dom/package-summary.html0000644000175000017500000000373710242117736023311 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.dom

Class Summary
DOMTest
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref-test/org/dom4j/dom/DOMTest.html0000644000175000017500000005145710242117707021502 0ustar ebourgebourg DOMTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dom;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.StringReader;
13  
14  import org.dom4j.AbstractTestCase;
15  import org.dom4j.io.DOMWriter;
16  import org.dom4j.io.SAXReader;
17  
18  import org.w3c.dom.DOMException;
19  import org.w3c.dom.NamedNodeMap;
20  import org.w3c.dom.Node;
21  import org.w3c.dom.NodeList;
22  
23  /***
24   * A test harness to test the native DOM implementation of dom4j
25   * 
26   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
27   * @version $Revision: 1.4 $
28   */
29  public class DOMTest extends AbstractTestCase {
30      /*** Elements. */
31      private long elements;
32  
33      /*** Attributes. */
34      private long attributes;
35  
36      /*** Characters. */
37      private long characters;
38  
39      public static void main(String[] args) {
40          TestRunner.run(DOMTest.class);
41      }
42  
43      // Test case(s)
44      // -------------------------------------------------------------------------
45      public void testCount() throws Exception {
46          DOMWriter domWriter = new DOMWriter();
47  
48          long start = System.currentTimeMillis();
49          org.w3c.dom.Document domDocument = domWriter.write(document);
50          long end = System.currentTimeMillis();
51  
52          System.out.println("Converting to a W3C Document took: "
53                  + (end - start) + " milliseconds");
54  
55          traverse(domDocument);
56  
57          log("elements: " + elements + " attributes: " + attributes
58                  + " characters: " + characters);
59      }
60  
61      public void testNamespace() throws Exception {
62          String xml = "<prefix:root xmlns:prefix=\"myuri\" />";
63          SAXReader xmlReader = new SAXReader(DOMDocumentFactory.getInstance());
64          DOMDocument d = (DOMDocument) xmlReader.read(new StringReader(xml));
65  
66          assertEquals("namespace prefix not correct", "prefix", d
67                  .getRootElement().getNamespace().getPrefix());
68          assertEquals("namespace uri not correct", "myuri", d.getRootElement()
69                  .getNamespace().getURI());
70  
71          System.out.println(d.asXML());
72      }
73  
74      /***
75       * Tests the bug found by Soumanjoy
76       * 
77       * @throws Exception
78       *             DOCUMENT ME!
79       */
80      public void testClassCastBug() throws Exception {
81          DOMDocument oDocument = new DOMDocument("Root");
82          org.w3c.dom.Element oParent = oDocument.createElement("Parent");
83  
84          // <-- Fails here when the code is broken.
85          oParent.setAttribute("name", "N01");
86          oParent.setAttribute("id", "ID01");
87  
88          oDocument.appendChild(oParent); // <-- Fails here, Error message is
89          // below
90      }
91  
92      public void testReplaceChild() throws Exception {
93          DOMDocument document = new DOMDocument("Root");
94          org.w3c.dom.Element parent = document.createElement("Parent");
95          org.w3c.dom.Element first = document.createElement("FirstChild");
96          org.w3c.dom.Element second = document.createElement("SecondChild");
97          org.w3c.dom.Element third = document.createElement("ThirdChild");
98  
99          document.appendChild(parent);
100         parent.appendChild(first);
101         parent.appendChild(second);
102         parent.appendChild(third);
103 
104         org.w3c.dom.Element newFirst = document.createElement("NewFirst");
105         org.w3c.dom.Element oldFirst = (org.w3c.dom.Element) parent
106                 .replaceChild(newFirst, first);
107 
108         /* check the return value of replaceChild */
109         assertEquals(oldFirst, first);
110 
111         /* make sure the old node has been replaced */
112         NodeList children = parent.getChildNodes();
113         Node firstChild = children.item(0);
114         assertEquals(Node.ELEMENT_NODE, firstChild.getNodeType());
115         assertEquals(newFirst, firstChild);
116 
117         /* try to replace a node that doesn't exist */
118         org.w3c.dom.Element badNode = document.createElement("No Child");
119 
120         try {
121             parent.replaceChild(newFirst, badNode);
122             fail("DOMException not thrown");
123         } catch (DOMException e) {
124             assertEquals(DOMException.NOT_FOUND_ERR, e.code);
125         }
126     }
127 
128     // Implementation methods
129     // -------------------------------------------------------------------------
130     protected void setUp() throws Exception {
131         super.setUp();
132 
133         SAXReader reader = new SAXReader(DOMDocumentFactory.getInstance());
134         document = getDocument("/xml/contents.xml", reader);
135     }
136 
137     /***
138      * Traverses the specified node, recursively.
139      * 
140      * @param node
141      *            DOCUMENT ME!
142      */
143     protected void traverse(Node node) {
144         // is there anything to do?
145         if (node == null) {
146             return;
147         }
148 
149         int type = node.getNodeType();
150 
151         switch (type) {
152             case Node.DOCUMENT_NODE: {
153                 elements = 0;
154                 attributes = 0;
155                 characters = 0;
156                 traverse(((org.w3c.dom.Document) node).getDocumentElement());
157 
158                 break;
159             }
160 
161             case Node.ELEMENT_NODE: {
162                 elements++;
163 
164                 NamedNodeMap attrs = node.getAttributes();
165 
166                 if (attrs != null) {
167                     attributes += attrs.getLength();
168                 }
169 
170                 NodeList children = node.getChildNodes();
171 
172                 if (children != null) {
173                     int len = children.getLength();
174 
175                     for (int i = 0; i < len; i++) {
176                         traverse(children.item(i));
177                     }
178                 }
179 
180                 break;
181             }
182 
183             case Node.ENTITY_REFERENCE_NODE: {
184                 NodeList children = node.getChildNodes();
185 
186                 if (children != null) {
187                     int len = children.getLength();
188 
189                     for (int i = 0; i < len; i++) {
190                         traverse(children.item(i));
191                     }
192                 }
193 
194                 break;
195             }
196 
197             case Node.CDATA_SECTION_NODE: {
198                 characters += node.getNodeValue().length();
199 
200                 break;
201             }
202 
203             case Node.TEXT_NODE: {
204                 characters += node.getNodeValue().length();
205 
206                 break;
207             }
208 
209             default:
210                 break;
211         }
212     }
213 }
214 
215 /*
216  * Redistribution and use of this software and associated documentation
217  * ("Software"), with or without modification, are permitted provided that the
218  * following conditions are met:
219  * 
220  * 1. Redistributions of source code must retain copyright statements and
221  * notices. Redistributions must also contain a copy of this document.
222  * 
223  * 2. Redistributions in binary form must reproduce the above copyright notice,
224  * this list of conditions and the following disclaimer in the documentation
225  * and/or other materials provided with the distribution.
226  * 
227  * 3. The name "DOM4J" must not be used to endorse or promote products derived
228  * from this Software without prior written permission of MetaStuff, Ltd. For
229  * written permission, please contact dom4j-info@metastuff.com.
230  * 
231  * 4. Products derived from this Software may not be called "DOM4J" nor may
232  * "DOM4J" appear in their names without prior written permission of MetaStuff,
233  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
234  * 
235  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
236  * 
237  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
238  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
239  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
240  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
241  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
242  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
243  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
244  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
245  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
246  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
247  * POSSIBILITY OF SUCH DAMAGE.
248  * 
249  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
250  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/dom/package-frame.html0000644000175000017500000000126010242117710022663 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.dom

org.dom4j.dom

Classes

  • DOMTest
dom4j-1.6.1/docs/xref-test/org/dom4j/rule/0000755000175000017500000000000012133227266017514 5ustar ebourgebourgdom4j-1.6.1/docs/xref-test/org/dom4j/rule/PriorityTest.html0000644000175000017500000002134710242117730023063 0ustar ebourgebourg PriorityTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.rule;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.AbstractTestCase;
13  import org.dom4j.DocumentFactory;
14  
15  /***
16   * Tests the priority behaviour of Pattern.
17   * 
18   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
19   * @version $Revision: 1.3 $
20   */
21  public class PriorityTest extends AbstractTestCase {
22      public static void main(String[] args) {
23          TestRunner.run(PriorityTest.class);
24      }
25  
26      public void testNameNode() throws Exception {
27          testPriority("foo", 0);
28      }
29  
30      public void testFilter() throws Exception {
31          testPriority("foo[@id='123']", 0.5);
32      }
33  
34      public void testURI() throws Exception {
35          testPriority("foo:*", -0.25);
36      }
37  
38      public void testAnyNode() throws Exception {
39          testPriority("*", -0.5);
40      }
41  
42      protected void testPriority(String expr, double priority) throws Exception {
43          System.out.println("parsing: " + expr);
44  
45          Pattern pattern = DocumentFactory.getInstance().createPattern(expr);
46          double d = pattern.getPriority();
47  
48          System.out.println("expr: " + expr + " has priority: " + d);
49          System.out.println("pattern: " + pattern);
50  
51          assertEquals("expr: " + expr, new Double(priority), new Double(d));
52      }
53  }
54  
55  /*
56   * Redistribution and use of this software and associated documentation
57   * ("Software"), with or without modification, are permitted provided that the
58   * following conditions are met:
59   * 
60   * 1. Redistributions of source code must retain copyright statements and
61   * notices. Redistributions must also contain a copy of this document.
62   * 
63   * 2. Redistributions in binary form must reproduce the above copyright notice,
64   * this list of conditions and the following disclaimer in the documentation
65   * and/or other materials provided with the distribution.
66   * 
67   * 3. The name "DOM4J" must not be used to endorse or promote products derived
68   * from this Software without prior written permission of MetaStuff, Ltd. For
69   * written permission, please contact dom4j-info@metastuff.com.
70   * 
71   * 4. Products derived from this Software may not be called "DOM4J" nor may
72   * "DOM4J" appear in their names without prior written permission of MetaStuff,
73   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
74   * 
75   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
76   * 
77   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
78   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
79   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
80   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
81   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
82   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
83   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
84   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
85   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
86   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
87   * POSSIBILITY OF SUCH DAMAGE.
88   * 
89   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
90   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/rule/RuleTest.html0000644000175000017500000003274410242117760022157 0ustar ebourgebourg RuleTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.rule;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.ArrayList;
13  import java.util.Collections;
14  
15  import org.dom4j.AbstractTestCase;
16  import org.dom4j.CDATA;
17  import org.dom4j.Document;
18  import org.dom4j.DocumentFactory;
19  
20  /***
21   * Tests the ordering of Rules
22   * 
23   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
24   * @version $Revision: 1.3 $
25   */
26  public class RuleTest extends AbstractTestCase {
27      protected DocumentFactory factory = new DocumentFactory();
28  
29      public static void main(String[] args) {
30          TestRunner.run(RuleTest.class);
31      }
32  
33      public void testOrder() throws Exception {
34          testGreater("foo", "*");
35      }
36  
37      protected void testGreater(String expr1, String expr2) throws Exception {
38          System.out.println("parsing: " + expr1 + " and " + expr2);
39  
40          Rule r1 = createRule(expr1);
41          Rule r2 = createRule(expr2);
42  
43          System.out.println("rule1: " + r1 + " rule2: " + r2);
44  
45          int value = r1.compareTo(r2);
46  
47          System.out.println("Comparison: " + value);
48  
49          assertTrue("r1 > r2", value > 0);
50  
51          ArrayList list = new ArrayList();
52          list.add(r1);
53          list.add(r2);
54  
55          Collections.sort(list);
56  
57          assertTrue("r2 should be first", list.get(0) == r2);
58          assertTrue("r1 should be next", list.get(1) == r1);
59  
60          list = new ArrayList();
61          list.add(r2);
62          list.add(r1);
63  
64          Collections.sort(list);
65  
66          assertTrue("r2 should be first", list.get(0) == r2);
67          assertTrue("r1 should be next", list.get(1) == r1);
68  
69          /*
70           * TreeSet set = new TreeSet(); set.add( r1 ); set.add( r2 );
71           * 
72           * assertTrue( "r2 should be first", set.first() == r2 ); assertTrue(
73           * "r1 should be next", set.last() == r1 );
74           * 
75           * Object[] array = set.toArray();
76           * 
77           * assertTrue( "r2 should be first", array[0] == r2 ); assertTrue( "r1
78           * should be next", array[1] == r1 );
79           * 
80           * set = new TreeSet(); set.add( r2 ); set.add( r1 );
81           * 
82           * assertTrue( "r2 should be first", set.first() == r2 ); assertTrue(
83           * "r1 should be next", set.last() == r1 );
84           * 
85           * array = set.toArray();
86           * 
87           * assertTrue( "r2 should be first", array[0] == r2 ); assertTrue( "r1
88           * should be next", array[1] == r1 );
89           */
90      }
91  
92      public void testDocument() {
93          Rule rule = createRule("/");
94          Document document = factory.createDocument();
95          document.addElement("foo");
96  
97          assertTrue("/ matches document", rule.matches(document));
98          assertTrue("/ does not match root element", !rule.matches(document
99                  .getRootElement()));
100     }
101 
102     public void testTextMatchesCDATA() {
103         CDATA cdata = factory.createCDATA("<>&");
104         Rule rule = createRule("text()");
105 
106         assertTrue("text() matches CDATA", rule.matches(cdata));
107     }
108 
109     protected Rule createRule(String expr) {
110         Pattern pattern = factory.createPattern(expr);
111 
112         return new Rule(pattern);
113     }
114 }
115 
116 /*
117  * Redistribution and use of this software and associated documentation
118  * ("Software"), with or without modification, are permitted provided that the
119  * following conditions are met:
120  * 
121  * 1. Redistributions of source code must retain copyright statements and
122  * notices. Redistributions must also contain a copy of this document.
123  * 
124  * 2. Redistributions in binary form must reproduce the above copyright notice,
125  * this list of conditions and the following disclaimer in the documentation
126  * and/or other materials provided with the distribution.
127  * 
128  * 3. The name "DOM4J" must not be used to endorse or promote products derived
129  * from this Software without prior written permission of MetaStuff, Ltd. For
130  * written permission, please contact dom4j-info@metastuff.com.
131  * 
132  * 4. Products derived from this Software may not be called "DOM4J" nor may
133  * "DOM4J" appear in their names without prior written permission of MetaStuff,
134  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
135  * 
136  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
137  * 
138  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
139  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
140  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
141  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
142  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
143  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
144  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
145  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
146  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
147  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
148  * POSSIBILITY OF SUCH DAMAGE.
149  * 
150  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
151  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/rule/package-summary.html0000644000175000017500000000446210242117564023474 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.rule

Class Summary
PriorityTest
RuleTest
StylesheetTest
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref-test/org/dom4j/rule/package-frame.html0000644000175000017500000000164210242117612023060 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.rule

org.dom4j.rule

Classes

  • PriorityTest
  • RuleTest
  • StylesheetTest
dom4j-1.6.1/docs/xref-test/org/dom4j/rule/StylesheetTest.html0000644000175000017500000003643510242117736023405 0ustar ebourgebourg StylesheetTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.rule;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.AbstractTestCase;
13  import org.dom4j.Document;
14  import org.dom4j.DocumentHelper;
15  import org.dom4j.Node;
16  import org.dom4j.xpath.DefaultXPath;
17  
18  /***
19   * A test harness to test the use of the Stylesheet and the XSLT rule engine.
20   * 
21   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
22   * @version $Revision: 1.4 $
23   */
24  public class StylesheetTest extends AbstractTestCase {
25      protected String[] templates = {
26              "/",
27              "*",
28              "root",
29              "author",
30              "@name",
31              "root/author",
32              "author[@location='UK']",
33              "root/author[@location='UK']",
34              "root//author[@location='UK']"};
35  
36      protected String[] templates2 = {"/", "title", "para", "*"};
37  
38      protected Stylesheet stylesheet;
39  
40      public static void main(String[] args) {
41          TestRunner.run(StylesheetTest.class);
42      }
43  
44      // Test case(s)
45      // -------------------------------------------------------------------------
46      public void testRules() throws Exception {
47          for (int i = 0, size = templates.length; i < size; i++) {
48              addTemplate(templates[i]);
49          }
50  
51          log("");
52          log("........................................");
53          log("");
54          log("Running stylesheet");
55  
56          stylesheet.run(document);
57  
58          log("Finished");
59      }
60  
61      public void testLittleDoc() throws Exception {
62          for (int i = 0, size = templates2.length; i < size; i++) {
63              addTemplate(templates2[i]);
64          }
65          Document doc = getDocument("/xml/test/littledoc.xml");
66  
67          stylesheet = new Stylesheet();
68          stylesheet.setValueOfAction(new Action() {
69              public void run(Node node) {
70                  log("Default ValueOf action on node: " + node);
71                  log("........................................");
72              }
73          });
74  
75          stylesheet.run(doc);
76      }
77  
78      public void testFireRuleForNode() throws Exception {
79          final StringBuffer b = new StringBuffer();
80  
81          final Stylesheet s = new Stylesheet();
82          Pattern pattern = DocumentHelper.createPattern("url");
83          Action action = new Action() {
84              public void run(Node node) throws Exception {
85                  b.append("url");
86                  s.applyTemplates(node);
87              }
88          };
89  
90          Rule r = new Rule(pattern, action);
91          s.addRule(r);
92  
93          s.applyTemplates(document, new DefaultXPath("root/author/url"));
94  
95          assertEquals("Check url is processed twice", "urlurl", b.toString());
96      }
97  
98      // Implementation methods
99      // -------------------------------------------------------------------------
100     protected void setUp() throws Exception {
101         super.setUp();
102 
103         stylesheet = new Stylesheet();
104         stylesheet.setValueOfAction(new Action() {
105             public void run(Node node) {
106                 log("Default ValueOf action on node: " + node);
107                 log("........................................");
108             }
109         });
110     }
111 
112     protected void addTemplate(final String match) {
113         log("Adding template match: " + match);
114 
115         Pattern pattern = DocumentHelper.createPattern(match);
116 
117         log("Pattern: " + pattern);
118         log("........................................");
119 
120         Action action = new Action() {
121             public void run(Node node) throws Exception {
122                 log("Matched pattern: " + match);
123                 log("Node: " + node.asXML());
124                 log("........................................");
125 
126                 // apply any child templates
127                 stylesheet.applyTemplates(node);
128             }
129         };
130 
131         Rule rule = new Rule(pattern, action);
132         stylesheet.addRule(rule);
133     }
134 }
135 
136 /*
137  * Redistribution and use of this software and associated documentation
138  * ("Software"), with or without modification, are permitted provided that the
139  * following conditions are met:
140  * 
141  * 1. Redistributions of source code must retain copyright statements and
142  * notices. Redistributions must also contain a copy of this document.
143  * 
144  * 2. Redistributions in binary form must reproduce the above copyright notice,
145  * this list of conditions and the following disclaimer in the documentation
146  * and/or other materials provided with the distribution.
147  * 
148  * 3. The name "DOM4J" must not be used to endorse or promote products derived
149  * from this Software without prior written permission of MetaStuff, Ltd. For
150  * written permission, please contact dom4j-info@metastuff.com.
151  * 
152  * 4. Products derived from this Software may not be called "DOM4J" nor may
153  * "DOM4J" appear in their names without prior written permission of MetaStuff,
154  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
155  * 
156  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
157  * 
158  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
159  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
160  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
161  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
162  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
163  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
164  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
165  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
166  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
167  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
168  * POSSIBILITY OF SUCH DAMAGE.
169  * 
170  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
171  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/SerializeTest.html0000644000175000017500000003355210242117745022231 0ustar ebourgebourg SerializeTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.ByteArrayInputStream;
13  import java.io.ByteArrayOutputStream;
14  import java.io.ObjectInputStream;
15  import java.io.ObjectOutputStream;
16  import java.util.HashMap;
17  import java.util.Map;
18  
19  import org.dom4j.io.SAXReader;
20  
21  /***
22   * Tests that a dom4j document is Serializable
23   * 
24   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
25   * @version $Revision: 1.4 $
26   */
27  public class SerializeTest extends AbstractTestCase {
28      public static void main(String[] args) {
29          TestRunner.run(SerializeTest.class);
30      }
31  
32      // Test case(s)
33      // -------------------------------------------------------------------------
34      public void testSerializePeriodicTable() throws Exception {
35          testSerialize("/xml/periodic_table.xml");
36      }
37  
38      public void testSerializeMuchAdo() throws Exception {
39          testSerialize("/xml/much_ado.xml");
40      }
41  
42      public void testSerializeTestSchema() throws Exception {
43          testSerialize("/xml/test/schema/personal.xsd");
44      }
45  
46      public void testSerializeXPath() throws Exception {
47          Map uris = new HashMap();
48          uris.put("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/");
49          uris.put("m", "urn:xmethodsBabelFish");
50  
51          DocumentFactory factory = new DocumentFactory();
52          factory.setXPathNamespaceURIs(uris);
53  
54          // now parse a document using my factory
55          SAXReader reader = new SAXReader();
56          reader.setDocumentFactory(factory);
57  
58          Document doc = getDocument("/xml/soap.xml", reader);
59  
60          // now lets use the prefixes
61          String expr = "/SOAP-ENV:Envelope/SOAP-ENV:Body/m:BabelFish";
62          Node element = doc.selectSingleNode(expr);
63          assertTrue("Found valid element", element != null);
64  
65          XPath xpath = factory
66                  .createXPath("/SOAP-ENV:Envelope/SOAP-ENV:Body/m:BabelFish");
67          element = xpath.selectSingleNode(doc);
68          assertTrue("Found valid element", element != null);
69  
70          // now serialize
71          ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
72          ObjectOutputStream out = new ObjectOutputStream(bytesOut);
73          out.writeObject(xpath);
74          out.close();
75  
76          byte[] data = bytesOut.toByteArray();
77  
78          ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(
79                  data));
80          XPath xpath2 = (XPath) in.readObject();
81          in.close();
82  
83          element = xpath2.selectSingleNode(doc);
84          assertTrue("Found valid element", element != null);
85      }
86  
87      // Implementation methods
88      // -------------------------------------------------------------------------
89      protected void testSerialize(String xmlFile) throws Exception {
90          Document document = getDocument(xmlFile);
91          String text = document.asXML();
92  
93          ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
94          ObjectOutputStream out = new ObjectOutputStream(bytesOut);
95          out.writeObject(document);
96          out.close();
97  
98          byte[] data = bytesOut.toByteArray();
99  
100         ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(
101                 data));
102         Document doc2 = (Document) in.readObject();
103         in.close();
104 
105         String text2 = doc2.asXML();
106 
107         assertEquals("Documents text are equal", text, text2);
108 
109         assertTrue("Read back document after serialization", (doc2 != null)
110                 && doc2 instanceof Document);
111 
112         assertDocumentsEqual(document, (Document) doc2);
113 
114         // now lets try add something to the document...
115         doc2.getRootElement().addElement("new");
116     }
117 }
118 
119 /*
120  * Redistribution and use of this software and associated documentation
121  * ("Software"), with or without modification, are permitted provided that the
122  * following conditions are met:
123  * 
124  * 1. Redistributions of source code must retain copyright statements and
125  * notices. Redistributions must also contain a copy of this document.
126  * 
127  * 2. Redistributions in binary form must reproduce the above copyright notice,
128  * this list of conditions and the following disclaimer in the documentation
129  * and/or other materials provided with the distribution.
130  * 
131  * 3. The name "DOM4J" must not be used to endorse or promote products derived
132  * from this Software without prior written permission of MetaStuff, Ltd. For
133  * written permission, please contact dom4j-info@metastuff.com.
134  * 
135  * 4. Products derived from this Software may not be called "DOM4J" nor may
136  * "DOM4J" appear in their names without prior written permission of MetaStuff,
137  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
138  * 
139  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
140  * 
141  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
142  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
143  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
144  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
145  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
146  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
147  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
148  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
149  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
150  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
151  * POSSIBILITY OF SUCH DAMAGE.
152  * 
153  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
154  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/DocTypeTest.html0000644000175000017500000002216210242117705021640 0ustar ebourgebourg DocTypeTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.List;
13  
14  import org.dom4j.dtd.ElementDecl;
15  import org.dom4j.io.SAXReader;
16  
17  /***
18   * Tests the DocType functionality
19   * 
20   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
21   * @version $Revision: 1.4 $
22   */
23  public class DocTypeTest extends AbstractTestCase {
24      /*** Input XML file to read */
25      protected static final String INPUT_XML_FILE = "/xml/dtd/internal.xml";
26  
27      public static void main(String[] args) {
28          TestRunner.run(DocTypeTest.class);
29      }
30  
31      // Test case(s)
32      // -------------------------------------------------------------------------
33      public void testDocType() throws Exception {
34          SAXReader reader = new SAXReader();
35          reader.setIncludeInternalDTDDeclarations(true);
36  
37          Document document = getDocument(INPUT_XML_FILE, reader);
38  
39          DocumentType docType = document.getDocType();
40          assertTrue("Has DOCTYPE", docType != null);
41  
42          List declarations = docType.getInternalDeclarations();
43          assertTrue("DOCTYPE has declarations", (declarations != null)
44                  && !declarations.isEmpty());
45  
46          ElementDecl decl = (ElementDecl) declarations.get(0);
47  
48          assertEquals("name is correct", "greeting", decl.getName());
49          assertEquals("model is correct", "(#PCDATA)", decl.getModel());
50  
51          String expected = "<!ELEMENT " + decl.getName() + " " + decl.getModel()
52                  + ">";
53          assertEquals("toString() is correct", expected, decl.toString());
54      }
55  }
56  
57  /*
58   * Redistribution and use of this software and associated documentation
59   * ("Software"), with or without modification, are permitted provided that the
60   * following conditions are met:
61   * 
62   * 1. Redistributions of source code must retain copyright statements and
63   * notices. Redistributions must also contain a copy of this document.
64   * 
65   * 2. Redistributions in binary form must reproduce the above copyright notice,
66   * this list of conditions and the following disclaimer in the documentation
67   * and/or other materials provided with the distribution.
68   * 
69   * 3. The name "DOM4J" must not be used to endorse or promote products derived
70   * from this Software without prior written permission of MetaStuff, Ltd. For
71   * written permission, please contact dom4j-info@metastuff.com.
72   * 
73   * 4. Products derived from this Software may not be called "DOM4J" nor may
74   * "DOM4J" appear in their names without prior written permission of MetaStuff,
75   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
76   * 
77   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
78   * 
79   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
80   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
81   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
82   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
83   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
84   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
85   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
86   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
87   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
88   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
89   * POSSIBILITY OF SUCH DAMAGE.
90   * 
91   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
92   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/package-frame.html0000644000175000017500000001340210242117741022111 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j

org.dom4j

Classes

  • AbstractTestCase
  • AddAttributeTest
  • AddNodeTest
  • AttributeDetachTest
  • BackedListTest
  • CloneTest
  • ContentTest
  • CopyTest
  • DetachTest
  • DocTypeTest
  • ElementByIDTest
  • EmbeddedHandlerTest
  • GetQNamesTest
  • GetXMLEncodingTest
  • HTMLWriterTest
  • IndexedElementTest
  • IsTextOnlyTest
  • IteratorTest
  • LineFeedTest
  • MakeElementTest
  • MergeTextTest
  • NamespaceTest
  • NamespacesTest
  • NodeTypeNameTest
  • NormalizeTest
  • NullAttributesTest
  • ParentTest
  • ParseTextTest
  • ProcessingInstructionTest
  • RoundTripTest
  • SAXContentHandlerTest
  • SerializeTest
  • SetContentTest
  • SetTextTest
  • ThreadingTest
  • UserDataTest
  • ValidationTest
  • XMLResultTest
  • XMLSpaceAttributeTest
  • XMLWriterTest
  • XPathBugTest
  • XPathExamplesTest
  • XPathTest
  • XSLTTest
dom4j-1.6.1/docs/xref-test/org/dom4j/SAXContentHandlerTest.html0000644000175000017500000002462610242117704023563 0ustar ebourgebourg SAXContentHandlerTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.List;
13  
14  import javax.xml.parsers.SAXParser;
15  import javax.xml.parsers.SAXParserFactory;
16  
17  import org.dom4j.io.SAXContentHandler;
18  
19  import org.xml.sax.XMLReader;
20  
21  public class SAXContentHandlerTest extends AbstractTestCase {
22      private XMLReader xmlReader;
23  
24      protected String[] testDocuments = {"/xml/test/test_schema.xml",
25              "/xml/test/encode.xml", "/xml/fibo.xml",
26              "/xml/test/schema/personal-prefix.xsd", "/xml/test/soap2.xml"};
27  
28      public static void main(String[] args) {
29          TestRunner.run(SAXContentHandlerTest.class);
30      }
31  
32      protected void setUp() throws Exception {
33          super.setUp();
34  
35          SAXParserFactory spf = SAXParserFactory.newInstance();
36          spf.setNamespaceAware(true);
37  
38          SAXParser parser = spf.newSAXParser();
39          xmlReader = parser.getXMLReader();
40      }
41  
42      public void testSAXContentHandler() throws Exception {
43          SAXContentHandler contentHandler = new SAXContentHandler();
44          xmlReader.setContentHandler(contentHandler);
45          xmlReader.setDTDHandler(contentHandler);
46          xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler",
47                  contentHandler);
48  
49          for (int i = 0, size = testDocuments.length; i < size; i++) {
50              Document docFromSAXReader = getDocument(testDocuments[i]);
51  
52              xmlReader.parse(getFile(testDocuments[i]).toString());
53  
54              Document docFromSAXContentHandler = contentHandler.getDocument();
55  
56              docFromSAXContentHandler.setName(docFromSAXReader.getName());
57  
58              assertDocumentsEqual(docFromSAXReader, docFromSAXContentHandler);
59              assertEquals(docFromSAXReader.asXML(), docFromSAXContentHandler
60                      .asXML());
61          }
62      }
63  
64      public void testBug926713() throws Exception {
65          Document doc = getDocument("/xml/test/cdata.xml");
66          Element foo = doc.getRootElement();
67          Element bar = foo.element("bar");
68          List content = bar.content();
69          assertEquals(3, content.size());
70          assertEquals(Node.TEXT_NODE, ((Node) content.get(0)).getNodeType());
71          assertEquals(Node.CDATA_SECTION_NODE, ((Node) content.get(1))
72                  .getNodeType());
73          assertEquals(Node.TEXT_NODE, ((Node) content.get(2)).getNodeType());
74      }
75  }
76  
77  /*
78   * Redistribution and use of this software and associated documentation
79   * ("Software"), with or without modification, are permitted provided that the
80   * following conditions are met:
81   * 
82   * 1. Redistributions of source code must retain copyright statements and
83   * notices. Redistributions must also contain a copy of this document.
84   * 
85   * 2. Redistributions in binary form must reproduce the above copyright notice,
86   * this list of conditions and the following disclaimer in the documentation
87   * and/or other materials provided with the distribution.
88   * 
89   * 3. The name "DOM4J" must not be used to endorse or promote products derived
90   * from this Software without prior written permission of MetaStuff, Ltd. For
91   * written permission, please contact dom4j-info@metastuff.com.
92   * 
93   * 4. Products derived from this Software may not be called "DOM4J" nor may
94   * "DOM4J" appear in their names without prior written permission of MetaStuff,
95   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
96   * 
97   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
98   * 
99   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
100  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
101  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
102  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
103  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
104  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
105  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
106  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
107  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
108  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
109  * POSSIBILITY OF SUCH DAMAGE.
110  * 
111  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
112  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/GetXMLEncodingTest.html0000644000175000017500000002302410242117573023041 0ustar ebourgebourg GetXMLEncodingTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.ByteArrayInputStream;
13  import java.io.StringReader;
14  
15  import org.dom4j.io.SAXReader;
16  
17  import org.xml.sax.InputSource;
18  
19  /***
20   * DOCUMENT ME!
21   * 
22   * @author Maarten Coene
23   * @version $Revision: 1.4 $
24   */
25  public class GetXMLEncodingTest extends AbstractTestCase {
26      public static void main(String[] args) {
27          TestRunner.run(GetXMLEncodingTest.class);
28      }
29  
30      // Test case(s)
31      // -------------------------------------------------------------------------
32      public void testXMLEncodingFromString() throws Exception {
33          String xmlEnc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root/>";
34  
35          SAXReader reader = new SAXReader();
36          InputSource source = new InputSource(new ByteArrayInputStream(xmlEnc
37                  .getBytes("UTF-8")));
38          Document doc = reader.read(source);
39          assertEquals("UTF-8", doc.getXMLEncoding());
40  
41          doc = reader.read(new StringReader(xmlEnc));
42          assertNull(doc.getXMLEncoding());
43      }
44  
45      public void testXMLEncodingFromURL() throws Exception {
46          Document doc = getDocument("/xml/test/encode.xml");
47          assertEquals("UTF-8", doc.getXMLEncoding());
48  
49          doc = getDocument("/xml/russArticle.xml");
50          assertEquals("koi8-r", doc.getXMLEncoding());
51      }
52  
53      public void testXMLEncodingFromStringWithHelper() throws Exception {
54          String xmlEnc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root/>";
55          String xmlNoEnc = "<root/>";
56  
57          Document doc = DocumentHelper.parseText(xmlEnc);
58          assertEquals("UTF-8", doc.getXMLEncoding());
59  
60          doc = DocumentHelper.parseText(xmlNoEnc);
61          assertNull(doc.getXMLEncoding());
62      }
63  }
64  
65  /*
66   * Redistribution and use of this software and associated documentation
67   * ("Software"), with or without modification, are permitted provided that the
68   * following conditions are met:
69   * 
70   * 1. Redistributions of source code must retain copyright statements and
71   * notices. Redistributions must also contain a copy of this document.
72   * 
73   * 2. Redistributions in binary form must reproduce the above copyright notice,
74   * this list of conditions and the following disclaimer in the documentation
75   * and/or other materials provided with the distribution.
76   * 
77   * 3. The name "DOM4J" must not be used to endorse or promote products derived
78   * from this Software without prior written permission of MetaStuff, Ltd. For
79   * written permission, please contact dom4j-info@metastuff.com.
80   * 
81   * 4. Products derived from this Software may not be called "DOM4J" nor may
82   * "DOM4J" appear in their names without prior written permission of MetaStuff,
83   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
84   * 
85   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
86   * 
87   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
88   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
89   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
90   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
91   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
92   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
93   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
94   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
95   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
96   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
97   * POSSIBILITY OF SUCH DAMAGE.
98   * 
99   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
100  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/io/0000755000175000017500000000000012133227266017154 5ustar ebourgebourgdom4j-1.6.1/docs/xref-test/org/dom4j/io/DTDTest.html0000644000175000017500000013707710242117741021327 0ustar ebourgebourg DTDTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import junit.framework.AssertionFailedError;
11  
12  import junit.textui.TestRunner;
13  
14  import java.io.FileInputStream;
15  import java.io.IOException;
16  import java.io.InputStream;
17  import java.util.ArrayList;
18  import java.util.Iterator;
19  import java.util.List;
20  
21  import org.dom4j.AbstractTestCase;
22  import org.dom4j.Document;
23  import org.dom4j.DocumentType;
24  import org.dom4j.dtd.AttributeDecl;
25  import org.dom4j.dtd.ElementDecl;
26  import org.dom4j.dtd.ExternalEntityDecl;
27  import org.dom4j.dtd.InternalEntityDecl;
28  import org.dom4j.tree.DefaultDocumentType;
29  
30  import org.xml.sax.EntityResolver;
31  import org.xml.sax.InputSource;
32  import org.xml.sax.SAXException;
33  
34  /***
35   * Tests the DocType functionality.
36   * 
37   * <p>
38   * Incorporated additional test cases for optional processing of the internal
39   * and external DTD subsets. The "external" and "mixed" tests both <strong>fail
40   * </strong> due to a reported bug. See http://tinyurl.com/4dzyq
41   * </p>
42   * 
43   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
44   * @version $Revision: 1.4 $
45   */
46  public class DTDTest extends AbstractTestCase {
47      /***
48       * Input XML file to read <code>xml/dtd/internal.xml</code>- document
49       * using internal DTD subset, but no external DTD subset.
50       */
51      private static final String XML_INTERNAL_FILE = "xml/dtd/internal.xml";
52  
53      /***
54       * Input XML file to read <code>xml/dtd/external.xml</code>- document
55       * using external DTD subset, but no internal DTD subset. The external
56       * entity should be locatable by either PUBLIC or SYSTEM identifier. The
57       * testing harness should use an appropriate EntityResolver to locate the
58       * external entity as a local resource (no internet access).
59       */
60      private static final String XML_EXTERNAL_FILE = "xml/dtd/external.xml";
61  
62      /***
63       * Input XML file to read <code>xml/dtd/mixed.xml</code>- document using
64       * both an internal and an external DTD subset. The external entity should
65       * be locatable by either PUBLIC or SYSTEM identifier. The testing harness
66       * should use an appropriate EntityResolver to locate the external entity as
67       * a local resource (no internet access).
68       */
69      private static final String XML_MIXED = "xml/dtd/mixed.xml";
70  
71      /***
72       * Input XML file to for {@linkEntityResolver}
73       * <code>xml/dtd/sample.dtd</code>- the external entity providing the
74       * external DTD subset for test cases that need one. The SYSTEM identifier
75       * for this external entity is given by {@link#DTD_SYSTEM_ID}.
76       */
77      private static final String DTD_FILE = "xml/dtd/sample.dtd";
78  
79      /***
80       * The PUBLIC identifier, which is <code>-//dom4j//DTD sample</code>, for
81       * the external entity providing DTD for tests.
82       */
83      protected static final String DTD_PUBLICID = "-//dom4j//DTD sample";
84  
85      /***
86       * The SYSTEM identifier, which is <code>sample.dtd</code>, for the
87       * external entity providing DTD for tests.
88       */
89      protected static final String DTD_SYSTEM_ID = "sample.dtd";
90  
91      public static void main(String[] args) {
92          TestRunner.run(DTDTest.class);
93      }
94  
95      // Test case(s)
96      // -------------------------------------------------------------------------
97  
98      /***
99       * Test verifies correct identification of the internal DTD subset and
100      * correct non-presence of the external DTD subset.
101      * 
102      * @throws Exception
103      *             DOCUMENT ME!
104      */
105     public void testInternalDTDSubset() throws Exception {
106         /*
107          * Setup the expected DocumentType.
108          * 
109          * @todo dom4j should expose a DefaultDocumentType constructor that
110          * accepts only the elementName property. This is used when only an
111          * internal DTD subset is being provided via the <!DOCTYPE foo [...]>
112          * syntax, in which case there is neither a SYSTEM nor PUBLIC
113          * identifier.
114          */
115         DocumentType expected = new DefaultDocumentType();
116 
117         expected.setElementName("greeting");
118 
119         expected.setInternalDeclarations(getInternalDeclarations());
120 
121         /*
122          * Parse the test XML document and compare the expected and actual
123          * DOCTYPEs.
124          */
125         try {
126             assertSameDocumentType(expected, readDocument(
127                     XML_INTERNAL_FILE, true, false).getDocType());
128         } catch (AssertionFailedError ex) {
129             throw ex;
130         } catch (Throwable t) {
131             fail("Not expecting: " + t);
132         }
133     }
134 
135     /***
136      * Test verifies correct identification of the external DTD subset and
137      * correct non-presence of the internal DTD subset.
138      */
139     public void testExternalDTDSubset() {
140         /*
141          * Setup the expected DocumentType.
142          */
143         DocumentType expected = new DefaultDocumentType("another-greeting",
144                 null, DTD_SYSTEM_ID);
145 
146         expected.setExternalDeclarations(getExternalDeclarations());
147 
148         /*
149          * Parse the test XML document and compare the expected and actual
150          * DOCTYPEs.
151          */
152         try {
153             assertSameDocumentType(expected, readDocument(
154                     XML_EXTERNAL_FILE, false, true).getDocType());
155         } catch (AssertionFailedError ex) {
156             throw ex;
157         } catch (Throwable t) {
158             fail("Not expecting: " + t);
159         }
160     }
161 
162     /***
163      * Test verifies correct identification of the internal and external DTD
164      * subsets.
165      */
166     public void testMixedDTDSubset() {
167         /*
168          * Setup the expected DocumentType.
169          */
170         DocumentType expected = new DefaultDocumentType("another-greeting",
171                 null, DTD_SYSTEM_ID);
172 
173         expected.setInternalDeclarations(getInternalDeclarations());
174 
175         expected.setExternalDeclarations(getExternalDeclarations());
176 
177         /*
178          * Parse the test XML document and compare the expected and actual
179          * DOCTYPEs.
180          */
181         try {
182             assertSameDocumentType(expected, readDocument(XML_MIXED,
183                     true, true).getDocType());
184         } catch (AssertionFailedError ex) {
185             throw ex;
186         } catch (Throwable t) {
187             fail("Not expecting: " + t);
188         }
189     }
190 
191     // Implementation methods
192     // -------------------------------------------------------------------------
193 
194     /***
195      * Test helper method returns a {@link List}of DTD declarations that
196      * represents the expected internal DTD subset (for the tests that use an
197      * internal DTD subset).
198      * 
199      * <p>
200      * Note: The declarations returned by this method MUST agree those actually
201      * declared in {@link #XML_INTERNAL_FILE}and {@link
202      * #XML_MIXED}.
203      * </p>
204      * 
205      * <p>
206      * </p>
207      * 
208      * @return DOCUMENT ME!
209      */
210     protected List getInternalDeclarations() {
211         List decls = new ArrayList();
212 
213         decls.add(new ElementDecl("greeting", "(#PCDATA)"));
214 
215         decls.add(new AttributeDecl("greeting", "foo", "ID", "#IMPLIED", null));
216 
217         decls.add(new InternalEntityDecl("%boolean", "( true | false )"));
218 
219         return decls;
220     }
221 
222     /***
223      * Test helper method returns a {@link List}of DTD declarations that
224      * represents the expected external DTD subset (for the tests that use an
225      * external DTD subset).
226      * 
227      * @return DOCUMENT ME!
228      */
229     protected List getExternalDeclarations() {
230         List decls = new ArrayList();
231 
232         decls.add(new ElementDecl("another-greeting", "(#PCDATA)"));
233 
234         return decls;
235     }
236 
237     /***
238      * Test helper method compares the expected and actual {@link DocumentType}
239      * objects, including their internal and external DTD subsets.
240      * 
241      * <p>
242      * </p>
243      * 
244      * @param expected
245      *            DOCUMENT ME!
246      * @param actual
247      *            DOCUMENT ME!
248      */
249     protected void assertSameDocumentType(DocumentType expected,
250             DocumentType actual) {
251         /*
252          * Nothing expected?
253          */
254         if (expected == null) {
255             if (actual == null) {
256                 return; // Nothing found.
257             } else {
258                 fail("Not expecting DOCTYPE.");
259             }
260         } else {
261             /*
262              * Something expected.
263              */
264             if (actual == null) {
265                 fail("Expecting DOCTYPE");
266             }
267 
268             log("Expected DocumentType:\n" + expected.toString());
269 
270             log("Actual DocumentType:\n" + actual.toString());
271 
272             // Check the internal DTD subset.
273             assertSameDTDSubset("Internal", expected.getInternalDeclarations(),
274                     actual.getInternalDeclarations());
275 
276             // Check the external DTD subset.
277             assertSameDTDSubset("External", expected.getExternalDeclarations(),
278                     actual.getExternalDeclarations());
279         }
280     }
281 
282     /***
283      * Test helper method compares an expected set of DTD declarations with an
284      * actual set of DTD declarations. This method should be invoked seperately
285      * for the internal DTD subset and the external DTD subset. The declarations
286      * must occur in their logical ordering. See <a
287      * href="http://tinyurl.com/5jhd8">Lexical Handler </a> for conformance
288      * criteria.
289      * 
290      * @param txt
291      *            DOCUMENT ME!
292      * @param expected
293      *            DOCUMENT ME!
294      * @param actual
295      *            DOCUMENT ME!
296      * 
297      * @throws AssertionError
298      *             DOCUMENT ME!
299      */
300     protected void assertSameDTDSubset(String txt, List expected, List actual) {
301         /*
302          * Nothing expected?
303          */
304         if (expected == null) {
305             if (actual == null) {
306                 return; // Nothing found.
307             } else {
308                 fail("Not expecting " + txt + " DTD subset.");
309             }
310         } else {
311             /*
312              * Something expected.
313              */
314             if (actual == null) {
315                 fail("Expecting " + txt + " DTD subset.");
316             }
317 
318             /*
319              * Correct #of declarations found?
320              */
321             assertEquals(txt + " DTD subset has correct #of declarations"
322                     + ": expected=[" + expected.toString() + "]" + ", actual=["
323                     + actual.toString() + "]", expected.size(), actual.size());
324 
325             /*
326              * Check order, type, and values of each declaration. Serialization
327              * tests are done separately.
328              */
329             Iterator itr1 = expected.iterator();
330 
331             Iterator itr2 = actual.iterator();
332 
333             while (itr1.hasNext()) {
334                 Object obj1 = itr1.next();
335 
336                 Object obj2 = itr2.next();
337 
338                 assertEquals(txt + " DTD subset: Same type of declaration",
339                         obj1.getClass().getName(), obj2.getClass().getName());
340 
341                 if (obj1 instanceof AttributeDecl) {
342                     assertSameDecl((AttributeDecl) obj1, (AttributeDecl) obj2);
343                 } else if (obj1 instanceof ElementDecl) {
344                     assertSameDecl((ElementDecl) obj1, (ElementDecl) obj2);
345                 } else if (obj1 instanceof InternalEntityDecl) {
346                     assertSameDecl((InternalEntityDecl) obj1,
347                             (InternalEntityDecl) obj2);
348                 } else if (obj1 instanceof ExternalEntityDecl) {
349                     assertSameDecl((ExternalEntityDecl) obj1,
350                             (ExternalEntityDecl) obj2);
351                 } else {
352                     throw new AssertionError("Unexpected declaration type: "
353                             + obj1.getClass());
354                 }
355             }
356         }
357     }
358 
359     /***
360      * Test helper method compares an expected and an actual {@link
361      * AttributeDecl}.
362      * 
363      * @param expected
364      *            DOCUMENT ME!
365      * @param actual
366      *            DOCUMENT ME!
367      */
368     public void assertSameDecl(AttributeDecl expected, AttributeDecl actual) {
369         assertEquals("attributeName is correct", expected.getAttributeName(),
370                 actual.getAttributeName());
371 
372         assertEquals("elementName is correct", expected.getElementName(),
373                 actual.getElementName());
374 
375         assertEquals("type is correct", expected.getType(), actual.getType());
376 
377         assertEquals("value is not correct", expected.getValue(), actual
378                 .getValue());
379 
380         assertEquals("valueDefault is correct", expected.getValueDefault(),
381                 actual.getValueDefault());
382 
383         assertEquals("toString() is correct", expected.toString(), actual
384                 .toString());
385     }
386 
387     /***
388      * Test helper method compares an expected and an actual {@link
389      * ElementDecl}.
390      * 
391      * @param expected
392      *            DOCUMENT ME!
393      * @param actual
394      *            DOCUMENT ME!
395      */
396     protected void assertSameDecl(ElementDecl expected, ElementDecl actual) {
397         assertEquals("name is correct", expected.getName(), actual.getName());
398 
399         assertEquals("model is not correct", expected.getModel(), actual
400                 .getModel());
401 
402         assertEquals("toString() is correct", expected.toString(), actual
403                 .toString());
404     }
405 
406     /***
407      * Test helper method compares an expected and an actual {@link
408      * InternalEntityDecl}.
409      * 
410      * @param expected
411      *            DOCUMENT ME!
412      * @param actual
413      *            DOCUMENT ME!
414      */
415     protected void assertSameDecl(InternalEntityDecl expected,
416             InternalEntityDecl actual) {
417         assertEquals("name is correct", expected.getName(), actual.getName());
418 
419         assertEquals("value is not correct", expected.getValue(), actual
420                 .getValue());
421 
422         assertEquals("toString() is correct", expected.toString(), actual
423                 .toString());
424     }
425 
426     /***
427      * Test helper method compares an expected and an actual {@link
428      * ExternalEntityDecl}.
429      * 
430      * @param expected
431      *            DOCUMENT ME!
432      * @param actual
433      *            DOCUMENT ME!
434      */
435     protected void assertSameDecl(ExternalEntityDecl expected,
436             ExternalEntityDecl actual) {
437         assertEquals("name is correct", expected.getName(), actual.getName());
438 
439         assertEquals("publicID is correct", expected.getPublicID(), actual
440                 .getPublicID());
441 
442         assertEquals("systemID is correct", expected.getSystemID(), actual
443                 .getSystemID());
444 
445         assertEquals("toString() is correct", expected.toString(), actual
446                 .toString());
447     }
448 
449     /***
450      * Helper method reads a local resource and parses it as an XML document.
451      * The internal and external DTD subsets are optionally retained by the
452      * parser and exposed via the {@link DocumentType}object on the returned
453      * {@link Document}. The parser is configured with an {@link
454      * EntityResolver}that knows how to find the local resource identified by
455      * {@link #DTD_FILE}whose SYSTEM identifier is given by {@link
456      * #DTD_SYSTEM_ID}.
457      * 
458      * @param resourceName
459      *            DOCUMENT ME!
460      * @param includeInternal
461      *            DOCUMENT ME!
462      * @param includeExternal
463      *            DOCUMENT ME!
464      * 
465      * @return DOCUMENT ME!
466      * 
467      * @throws Exception
468      *             DOCUMENT ME!
469      */
470     protected Document readDocument(String resourceName,
471             boolean includeInternal, boolean includeExternal) throws Exception {
472         SAXReader reader = new SAXReader();
473 
474         reader.setIncludeInternalDTDDeclarations(includeInternal);
475 
476         reader.setIncludeExternalDTDDeclarations(includeExternal);
477 
478         reader.setEntityResolver(new MyEntityResolver(DTD_FILE,
479                 DTD_PUBLICID, DTD_SYSTEM_ID));
480 
481         return getDocument(resourceName, reader);
482     }
483 
484     /***
485      * Provides a resolver for the local test DTD resource.
486      */
487     protected static class MyEntityResolver implements EntityResolver {
488         private String resourceName;
489 
490         private String pubId;
491 
492         private String sysId;
493 
494         public MyEntityResolver(String localResourceName, String publicId,
495                 String systemId) {
496             resourceName = localResourceName;
497 
498             sysId = systemId;
499         }
500 
501         public InputSource resolveEntity(String publicId, String systemId)
502                 throws SAXException, IOException {
503             if (pubId != null) {
504                 if (pubId.equals(publicId)) {
505                     return new InputSource(getInputStream(resourceName));
506                 }
507             }
508 
509             if (sysId.equals(systemId)) {
510                 return new InputSource(getInputStream(resourceName));
511             } else {
512                 return null;
513             }
514         }
515 
516         /***
517          * Returns an {@link InputStream}that will read from the indicated
518          * local resource.
519          * 
520          * @param localResourceName
521          *            DOCUMENT ME!
522          * 
523          * @return DOCUMENT ME!
524          * 
525          * @throws IOException
526          *             DOCUMENT ME!
527          */
528         protected InputStream getInputStream(String localResourceName)
529                 throws IOException {
530             InputStream is = new FileInputStream(localResourceName);
531 
532             return is;
533         }
534     }
535 }
536 
537 /*
538  * Redistribution and use of this software and associated documentation
539  * ("Software"), with or without modification, are permitted provided that the
540  * following conditions are met:
541  * 
542  * 1. Redistributions of source code must retain copyright statements and
543  * notices. Redistributions must also contain a copy of this document.
544  * 
545  * 2. Redistributions in binary form must reproduce the above copyright notice,
546  * this list of conditions and the following disclaimer in the documentation
547  * and/or other materials provided with the distribution.
548  * 
549  * 3. The name "DOM4J" must not be used to endorse or promote products derived
550  * from this Software without prior written permission of MetaStuff, Ltd. For
551  * written permission, please contact dom4j-info@metastuff.com.
552  * 
553  * 4. Products derived from this Software may not be called "DOM4J" nor may
554  * "DOM4J" appear in their names without prior written permission of MetaStuff,
555  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
556  * 
557  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
558  * 
559  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
560  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
561  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
562  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
563  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
564  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
565  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
566  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
567  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
568  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
569  * POSSIBILITY OF SUCH DAMAGE.
570  * 
571  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
572  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/io/XPP3ReaderTest.html0000644000175000017500000002264410242117736022566 0ustar ebourgebourg XPP3ReaderTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.ByteArrayOutputStream;
13  import java.io.File;
14  import java.io.StringWriter;
15  
16  import org.dom4j.AbstractTestCase;
17  import org.dom4j.Document;
18  import org.dom4j.Element;
19  
20  /***
21   * Test class for the XPP3Reader. This is based on the TestSaxReader class.
22   * 
23   * @author <a href="mailto:pelle@neubia.com">Pelle Braendgaard </a>
24   * @author <a href="mailto:maartenc@sourceforge.net">Maarten Coene </a>
25   */
26  public class XPP3ReaderTest extends AbstractTestCase {
27      public static void main(String[] args) {
28          TestRunner.run(XPP3ReaderTest.class);
29      }
30  
31      // Test case(s)
32      // -------------------------------------------------------------------------
33      public void testRussian() throws Exception {
34          File file = getFile("/xml/russArticle.xml");
35          XPP3Reader xmlReader = new XPP3Reader();
36          Document doc = xmlReader.read(file);
37          Element el = doc.getRootElement();
38  
39          StringWriter writer = new StringWriter();
40          XMLWriter xmlWriter = new XMLWriter(writer);
41          OutputFormat format = OutputFormat.createPrettyPrint();
42          format.setEncoding("koi8-r");
43          xmlWriter.write(doc);
44          log(writer.toString());
45      }
46  
47      public void testRussian2() throws Exception {
48          File file = getFile("/xml/russArticle.xml");
49          XPP3Reader xmlReader = new XPP3Reader();
50          Document doc = xmlReader.read(file);
51          XMLWriter xmlWriter = new XMLWriter(new OutputFormat("", false,
52                  "koi8-r"));
53          ByteArrayOutputStream out = new ByteArrayOutputStream();
54          xmlWriter.setOutputStream(out);
55          xmlWriter.write(doc);
56          xmlWriter.flush();
57          xmlWriter.close();
58          log(out.toString());
59      }
60  }
61  
62  /*
63   * Redistribution and use of this software and associated documentation
64   * ("Software"), with or without modification, are permitted provided that the
65   * following conditions are met:
66   * 
67   * 1. Redistributions of source code must retain copyright statements and
68   * notices. Redistributions must also contain a copy of this document.
69   * 
70   * 2. Redistributions in binary form must reproduce the above copyright notice,
71   * this list of conditions and the following disclaimer in the documentation
72   * and/or other materials provided with the distribution.
73   * 
74   * 3. The name "DOM4J" must not be used to endorse or promote products derived
75   * from this Software without prior written permission of MetaStuff, Ltd. For
76   * written permission, please contact dom4j-info@metastuff.com.
77   * 
78   * 4. Products derived from this Software may not be called "DOM4J" nor may
79   * "DOM4J" appear in their names without prior written permission of MetaStuff,
80   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
81   * 
82   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
83   * 
84   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
85   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
86   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
87   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
88   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
89   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
90   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
91   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
92   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
93   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
94   * POSSIBILITY OF SUCH DAMAGE.
95   * 
96   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
97   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/io/package-summary.html0000644000175000017500000000647410242117717023141 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.io

Class Summary
DOMReaderTest
DOMWriterTest
DTDTest
DispatchHandlerTest
DocumentSourceTest
SAXReaderTest
StaxTest
WriteUnmergedTextTest
XPP3ReaderTest
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref-test/org/dom4j/io/SAXReaderTest.html0000644000175000017500000003276510242117713022467 0ustar ebourgebourg SAXReaderTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.ByteArrayOutputStream;
13  import java.io.File;
14  import java.io.StringReader;
15  import java.io.StringWriter;
16  import java.util.List;
17  
18  import org.dom4j.AbstractTestCase;
19  import org.dom4j.Document;
20  import org.dom4j.DocumentHelper;
21  import org.dom4j.Element;
22  
23  /***
24   * A test harness to test the content API in DOM4J
25   * 
26   * @author <a href="mailto:maartenc@sourceforge.net">Maarten Coene </a>
27   */
28  public class SAXReaderTest extends AbstractTestCase {
29      public static void main(String[] args) {
30          TestRunner.run(SAXReaderTest.class);
31      }
32  
33      // Test case(s)
34      // -------------------------------------------------------------------------
35  
36      /***
37       * Test bug reported by Christian Oetterli http://tinyurl.com/6po8v
38       * 
39       * @throws Exception
40       *             DOCUMENT ME!
41       */
42      public void testReadFile() throws Exception {
43          File file = getFile("/xml/#.xml");
44          new SAXReader().read(file);
45      }
46      
47      public void testEncoding() throws Exception {
48          String xml = "<?xml version='1.0' encoding='ISO-8859-1'?><root/>";
49          SAXReader reader = new SAXReader();
50          reader.setEncoding("ISO-8859-1");
51          Document doc = reader.read(new StringReader(xml));
52          
53          assertEquals("encoding incorrect", "ISO-8859-1", doc.getXMLEncoding());
54      }
55  
56      public void testRussian() throws Exception {
57          Document doc = getDocument("/xml/russArticle.xml");
58  
59          assertEquals("encoding not correct", "koi8-r", doc.getXMLEncoding());
60  
61          Element el = doc.getRootElement();
62  
63          StringWriter writer = new StringWriter();
64          XMLWriter xmlWriter = new XMLWriter(writer);
65          OutputFormat format = OutputFormat.createPrettyPrint();
66          format.setEncoding("koi8-r");
67          xmlWriter.write(doc);
68          log(writer.toString());
69      }
70  
71      public void testRussian2() throws Exception {
72          Document doc = getDocument("/xml/russArticle.xml");
73          XMLWriter xmlWriter = new XMLWriter(new OutputFormat("", false,
74                  "koi8-r"));
75          ByteArrayOutputStream out = new ByteArrayOutputStream();
76          xmlWriter.setOutputStream(out);
77          xmlWriter.write(doc);
78          xmlWriter.flush();
79          xmlWriter.close();
80          log(out.toString());
81      }
82  
83      public void testBug833765() throws Exception {
84          SAXReader reader = new SAXReader();
85          reader.setIncludeExternalDTDDeclarations(true);
86          getDocument("/xml/dtd/external.xml", reader);
87      }
88  
89      public void testBug527062() throws Exception {
90          Document doc = getDocument("/xml/test/test.xml");
91          List l = doc.selectNodes("//broked/junk");
92  
93          for (int i = 0; i < l.size(); i++) {
94              System.out.println("Found node: "
95                      + ((Element) l.get(i)).getStringValue());
96          }
97  
98          assertEquals("hi there", ((Element) l.get(0)).getStringValue());
99          assertEquals("hello world", ((Element) l.get(1)).getStringValue());
100     }
101 
102     public void testEscapedComment() throws Exception {
103         String txt = "<eg>&lt;!-- &lt;head> &amp; &lt;body> --&gt;</eg>";
104         Document doc = DocumentHelper.parseText(txt);
105         Element eg = doc.getRootElement();
106         System.out.println(doc.asXML());
107         assertEquals("<!-- <head> & <body> -->", eg.getText());
108     }
109 }
110 
111 /*
112  * Redistribution and use of this software and associated documentation
113  * ("Software"), with or without modification, are permitted provided that the
114  * following conditions are met:
115  * 
116  * 1. Redistributions of source code must retain copyright statements and
117  * notices. Redistributions must also contain a copy of this document.
118  * 
119  * 2. Redistributions in binary form must reproduce the above copyright notice,
120  * this list of conditions and the following disclaimer in the documentation
121  * and/or other materials provided with the distribution.
122  * 
123  * 3. The name "DOM4J" must not be used to endorse or promote products derived
124  * from this Software without prior written permission of MetaStuff, Ltd. For
125  * written permission, please contact dom4j-info@metastuff.com.
126  * 
127  * 4. Products derived from this Software may not be called "DOM4J" nor may
128  * "DOM4J" appear in their names without prior written permission of MetaStuff,
129  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
130  * 
131  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
132  * 
133  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
134  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
135  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
136  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
137  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
138  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
139  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
140  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
141  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
142  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
143  * POSSIBILITY OF SUCH DAMAGE.
144  * 
145  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
146  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/io/package-frame.html0000644000175000017500000000320410242117757022526 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.io

org.dom4j.io

Classes

  • DOMReaderTest
  • DOMWriterTest
  • DTDTest
  • DispatchHandlerTest
  • DocumentSourceTest
  • SAXReaderTest
  • StaxTest
  • WriteUnmergedTextTest
  • XPP3ReaderTest
dom4j-1.6.1/docs/xref-test/org/dom4j/io/StaxTest.html0000644000175000017500000002442010242117724021617 0ustar ebourgebourg StaxTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.File;
13  import java.io.FileReader;
14  import java.io.StringWriter;
15  
16  import javax.xml.stream.XMLInputFactory;
17  
18  import org.dom4j.AbstractTestCase;
19  import org.dom4j.Document;
20  
21  /***
22   * Tests STAX->DOM4J functionality.
23   * 
24   * @author <a href="mailto:maartenc@sourceforge.net">Maarten Coene </a>
25   * @author Christian Niles
26   */
27  public class StaxTest extends AbstractTestCase {
28      public static void main(String[] args) {
29          TestRunner.run(StaxTest.class);
30      }
31  
32      // Test case(s)
33      // -------------------------------------------------------------------------
34  
35      /***
36       * Tests that the encoding specified in the XML declaration is exposed in
37       * the Document read via StAX, and also that it gets output when writing.
38       */
39      public void testEncoding() {
40          /*
41           * only execute if a reference implementation is available
42           */
43          try {
44              XMLInputFactory.newInstance();
45          } catch (javax.xml.stream.FactoryConfigurationError e) {
46              // no implementation found, stop the test.
47              return;
48          }
49  
50          try {
51              File file = getFile("/xml/russArticle.xml");
52              STAXEventReader xmlReader = new STAXEventReader();
53              Document doc = xmlReader.readDocument(new FileReader(file));
54  
55              assertEquals("russArticle.xml encoding wasn't correct", "koi8-r",
56                      doc.getXMLEncoding());
57  
58              StringWriter writer = new StringWriter();
59              STAXEventWriter xmlWriter = new STAXEventWriter(writer);
60              xmlWriter.writeDocument(doc);
61  
62              String output = writer.toString();
63              String xmlDecl = output.substring(0, output.indexOf("?>") + 2);
64              String expected = "<?xml version=\'1.0\' encoding=\'koi8-r\'?>";
65              assertEquals("Unexpected xml declaration", expected, xmlDecl);
66              System.out.println(output);
67          } catch (Exception e) {
68              e.printStackTrace();
69              fail(e.getMessage());
70          }
71      }
72  }
73  
74  /*
75   * Redistribution and use of this software and associated documentation
76   * ("Software"), with or without modification, are permitted provided that the
77   * following conditions are met:
78   * 
79   * 1. Redistributions of source code must retain copyright statements and
80   * notices. Redistributions must also contain a copy of this document.
81   * 
82   * 2. Redistributions in binary form must reproduce the above copyright notice,
83   * this list of conditions and the following disclaimer in the documentation
84   * and/or other materials provided with the distribution.
85   * 
86   * 3. The name "DOM4J" must not be used to endorse or promote products derived
87   * from this Software without prior written permission of MetaStuff, Ltd. For
88   * written permission, please contact dom4j-info@metastuff.com.
89   * 
90   * 4. Products derived from this Software may not be called "DOM4J" nor may
91   * "DOM4J" appear in their names without prior written permission of MetaStuff,
92   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
93   * 
94   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
95   * 
96   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
97   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
98   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
99   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
100  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
101  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
102  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
103  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
104  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
105  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
106  * POSSIBILITY OF SUCH DAMAGE.
107  * 
108  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
109  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/io/DocumentSourceTest.html0000644000175000017500000002074110242117725023642 0ustar ebourgebourg DocumentSourceTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.StringWriter;
13  
14  import javax.xml.transform.Transformer;
15  import javax.xml.transform.TransformerFactory;
16  import javax.xml.transform.stream.StreamResult;
17  
18  import org.dom4j.AbstractTestCase;
19  import org.dom4j.Document;
20  import org.dom4j.DocumentHelper;
21  
22  /***
23   * DOCUMENT ME!
24   * 
25   * @author <a href="mailto:maartenc@sourceforge.net">Maarten Coene </a>
26   */
27  public class DocumentSourceTest extends AbstractTestCase {
28      public static void main(String[] args) {
29          TestRunner.run(DocumentSourceTest.class);
30      }
31  
32      // Test case(s)
33      // -------------------------------------------------------------------------
34      public void testBug555549() throws Exception {
35          // simulate <cr><lf>
36          String xml = "<field id='Description' type='textarea'>line1"
37                  + (char) 13 + (char) 10 + "line2</field>";
38          Document doc = DocumentHelper.parseText(xml);
39          TransformerFactory tf = TransformerFactory.newInstance();
40          Transformer txml = tf.newTransformer();
41          StringWriter writer = new StringWriter();
42          txml.transform(new DocumentSource(doc), new StreamResult(writer));
43  
44          System.out.println(writer.toString());
45          assertTrue(writer.toString().indexOf("&#13") == -1);
46      }
47  }
48  
49  /*
50   * Redistribution and use of this software and associated documentation
51   * ("Software"), with or without modification, are permitted provided that the
52   * following conditions are met:
53   * 
54   * 1. Redistributions of source code must retain copyright statements and
55   * notices. Redistributions must also contain a copy of this document.
56   * 
57   * 2. Redistributions in binary form must reproduce the above copyright notice,
58   * this list of conditions and the following disclaimer in the documentation
59   * and/or other materials provided with the distribution.
60   * 
61   * 3. The name "DOM4J" must not be used to endorse or promote products derived
62   * from this Software without prior written permission of MetaStuff, Ltd. For
63   * written permission, please contact dom4j-info@metastuff.com.
64   * 
65   * 4. Products derived from this Software may not be called "DOM4J" nor may
66   * "DOM4J" appear in their names without prior written permission of MetaStuff,
67   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
68   * 
69   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
70   * 
71   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
72   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
73   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
74   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
75   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
76   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
77   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
78   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
79   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
80   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
81   * POSSIBILITY OF SUCH DAMAGE.
82   * 
83   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
84   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/io/DispatchHandlerTest.html0000644000175000017500000002050210242117716023733 0ustar ebourgebourg DispatchHandlerTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.AbstractTestCase;
13  import org.dom4j.ElementHandler;
14  
15  /***
16   * DOCUMENT ME!
17   * 
18   * @author Maarten Coene
19   */
20  public class DispatchHandlerTest extends AbstractTestCase {
21      public static void main(String[] args) {
22          TestRunner.run(DispatchHandlerTest.class);
23      }
24  
25      public void testBug611445() throws Exception {
26          MyHandler handler = new MyHandler();
27  
28          SAXReader reader = new SAXReader();
29          reader.addHandler("/products/product/colour", handler);
30          reader.read(getFile("/xml/test/sample.xml"));
31  
32          assertEquals(3, handler.getCount());
33  
34          reader.read(getFile("/xml/test/sample.xml"));
35          assertEquals(6, handler.getCount());
36      }
37  
38      private static class MyHandler implements ElementHandler {
39          private int count = 0;
40  
41          public void onEnd(org.dom4j.ElementPath elementPath) {
42          }
43  
44          public void onStart(org.dom4j.ElementPath elementPath) {
45              count++;
46          }
47  
48          int getCount() {
49              return count;
50          }
51      }
52  }
53  
54  /*
55   * Redistribution and use of this software and associated documentation
56   * ("Software"), with or without modification, are permitted provided that the
57   * following conditions are met:
58   * 
59   * 1. Redistributions of source code must retain copyright statements and
60   * notices. Redistributions must also contain a copy of this document.
61   * 
62   * 2. Redistributions in binary form must reproduce the above copyright notice,
63   * this list of conditions and the following disclaimer in the documentation
64   * and/or other materials provided with the distribution.
65   * 
66   * 3. The name "DOM4J" must not be used to endorse or promote products derived
67   * from this Software without prior written permission of MetaStuff, Ltd. For
68   * written permission, please contact dom4j-info@metastuff.com.
69   * 
70   * 4. Products derived from this Software may not be called "DOM4J" nor may
71   * "DOM4J" appear in their names without prior written permission of MetaStuff,
72   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
73   * 
74   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
75   * 
76   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
77   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
78   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
79   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
80   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
81   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
82   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
83   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
84   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
85   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
86   * POSSIBILITY OF SUCH DAMAGE.
87   * 
88   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
89   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/io/WriteUnmergedTextTest.html0000644000175000017500000004237410242117703024333 0ustar ebourgebourg WriteUnmergedTextTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.StringReader;
13  import java.io.StringWriter;
14  
15  import org.dom4j.AbstractTestCase;
16  import org.dom4j.Document;
17  
18  /***
19   * A simple test harness to check that the XML Writer works
20   * 
21   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
22   * @version $Revision: 1.3 $
23   */
24  public class WriteUnmergedTextTest extends AbstractTestCase {
25      protected static final boolean VERBOSE = true;
26  
27      private String inputText = "<?xml version = \"1.0\"?>"
28              + "<TestEscapedEntities><TEXT>Test using &lt; "
29              + "&amp; &gt;</TEXT></TestEscapedEntities>";
30  
31      public static void main(String[] args) {
32          TestRunner.run(WriteUnmergedTextTest.class);
33      }
34  
35      // Test case(s)
36      // -------------------------------------------------------------------------
37      public String readwriteText(OutputFormat outFormat,
38              boolean mergeAdjacentText) throws Exception {
39          StringWriter out = new StringWriter();
40          StringReader in = new StringReader(inputText);
41          SAXReader reader = new SAXReader();
42  
43          // reader.setValidation(true);
44          reader.setMergeAdjacentText(mergeAdjacentText);
45  
46          Document document = reader.read(in);
47  
48          XMLWriter writer = (outFormat == null) ? new XMLWriter(out)
49                  : new XMLWriter(out, outFormat);
50          writer.write(document);
51          writer.close();
52  
53          String outText = out.toString();
54  
55          return outText;
56      }
57  
58      public void testWithoutFormatNonMerged() throws Exception {
59          String outText = readwriteText(null, false);
60  
61          if (VERBOSE) {
62              log("Text output is [");
63              log(outText);
64              log("]. Done");
65          }
66  
67          // should contain &amp; and &lt;
68          assertTrue("Output text contains \"&amp;\"", outText
69                  .lastIndexOf("&amp;") >= 0);
70          assertTrue("Output text contains \"&lt;\"",
71                  outText.lastIndexOf("&lt;") >= 0);
72      }
73  
74      public void testWithCompactFormatNonMerged() throws Exception {
75          String outText = readwriteText(OutputFormat.createCompactFormat(),
76                  false);
77  
78          if (VERBOSE) {
79              log("Text output is [");
80              log(outText);
81              log("]. Done");
82          }
83  
84          // should contain &amp; and &lt;
85          assertTrue("Output text contains \"&amp;\"", outText
86                  .lastIndexOf("&amp;") >= 0);
87          assertTrue("Output text contains \"&lt;\"",
88                  outText.lastIndexOf("&lt;") >= 0);
89      }
90  
91      public void testWithPrettyPrintFormatNonMerged() throws Exception {
92          String outText = readwriteText(OutputFormat.createPrettyPrint(), false);
93  
94          if (VERBOSE) {
95              log("Text output is [");
96              log(outText);
97              log("]. Done");
98          }
99  
100         // should contain &amp; and &lt;
101         assertTrue("Output text contains \"&amp;\"", outText
102                 .lastIndexOf("&amp;") >= 0);
103         assertTrue("Output text contains \"&lt;\"",
104                 outText.lastIndexOf("&lt;") >= 0);
105     }
106 
107     public void testWithoutFormatMerged() throws Exception {
108         String outText = readwriteText(null, true);
109 
110         if (VERBOSE) {
111             log("Text output is [");
112             log(outText);
113             log("]. Done");
114         }
115 
116         // should contain &amp; and &lt;
117         assertTrue("Output text contains \"&amp;\"", outText
118                 .lastIndexOf("&amp;") >= 0);
119         assertTrue("Output text contains \"&lt;\"",
120                 outText.lastIndexOf("&lt;") >= 0);
121     }
122 
123     public void testWithCompactFormatMerged() throws Exception {
124         String out = readwriteText(OutputFormat.createCompactFormat(), true);
125 
126         if (VERBOSE) {
127             log("Text output is [");
128             log(out);
129             log("]. Done");
130         }
131 
132         // should contain &amp; and &lt;
133         assertTrue("Output text contains \"&amp;\"", out
134                 .lastIndexOf("&amp;") >= 0);
135         assertTrue("Output text contains \"&lt;\"",
136                 out.lastIndexOf("&lt;") >= 0);
137     }
138 
139     public void testWithPrettyPrintFormatMerged() throws Exception {
140         String outText = readwriteText(OutputFormat.createPrettyPrint(), true);
141 
142         if (VERBOSE) {
143             log("Text output is [");
144             log(outText);
145             log("]. Done");
146         }
147 
148         // should contain &amp; and &lt;
149         assertTrue("Output text contains \"&amp;\"", outText
150                 .lastIndexOf("&amp;") >= 0);
151         assertTrue("Output text contains \"&lt;\"",
152                 outText.lastIndexOf("&lt;") >= 0);
153     }
154 }
155 
156 /*
157  * Redistribution and use of this software and associated documentation
158  * ("Software"), with or without modification, are permitted provided that the
159  * following conditions are met:
160  * 
161  * 1. Redistributions of source code must retain copyright statements and
162  * notices. Redistributions must also contain a copy of this document.
163  * 
164  * 2. Redistributions in binary form must reproduce the above copyright notice,
165  * this list of conditions and the following disclaimer in the documentation
166  * and/or other materials provided with the distribution.
167  * 
168  * 3. The name "DOM4J" must not be used to endorse or promote products derived
169  * from this Software without prior written permission of MetaStuff, Ltd. For
170  * written permission, please contact dom4j-info@metastuff.com.
171  * 
172  * 4. Products derived from this Software may not be called "DOM4J" nor may
173  * "DOM4J" appear in their names without prior written permission of MetaStuff,
174  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
175  * 
176  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
177  * 
178  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
179  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
180  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
181  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
182  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
183  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
184  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
185  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
186  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
187  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
188  * POSSIBILITY OF SUCH DAMAGE.
189  * 
190  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
191  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/io/DOMReaderTest.html0000644000175000017500000002151310242117662022443 0ustar ebourgebourg DOMReaderTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.ByteArrayInputStream;
13  import java.util.List;
14  
15  import javax.xml.parsers.DocumentBuilder;
16  import javax.xml.parsers.DocumentBuilderFactory;
17  
18  import org.dom4j.AbstractTestCase;
19  
20  /***
21   * DOCUMENT ME!
22   * 
23   * @author Maarten
24   */
25  public class DOMReaderTest extends AbstractTestCase {
26      public static void main(String[] args) {
27          TestRunner.run(DOMReaderTest.class);
28      }
29  
30      public void testBug972737() throws Exception {
31          String xml = "<schema targetNamespace='http://SharedTest.org/xsd' "
32                  + "        xmlns='http://www.w3.org/2001/XMLSchema' "
33                  + "        xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"
34                  + "    <complexType name='AllStruct'>" + "        <all>"
35                  + "            <element name='arString' type='xsd:string'/>"
36                  + "            <element name='varInt' type='xsd:int'/>"
37                  + "        </all>" + "    </complexType>" + "</schema>";
38  
39          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
40          DocumentBuilder builder = factory.newDocumentBuilder();
41          org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(xml
42                  .getBytes()));
43  
44          DOMReader reader = new DOMReader();
45          org.dom4j.Document dom4jDoc = reader.read(doc);
46  
47          List namespaces = dom4jDoc.getRootElement().declaredNamespaces();
48          assertEquals(2, namespaces.size());
49  
50          System.out.println(dom4jDoc.asXML());
51      }
52  }
53  
54  /*
55   * Redistribution and use of this software and associated documentation
56   * ("Software"), with or without modification, are permitted provided that the
57   * following conditions are met:
58   * 
59   * 1. Redistributions of source code must retain copyright statements and
60   * notices. Redistributions must also contain a copy of this document.
61   * 
62   * 2. Redistributions in binary form must reproduce the above copyright notice,
63   * this list of conditions and the following disclaimer in the documentation
64   * and/or other materials provided with the distribution.
65   * 
66   * 3. The name "DOM4J" must not be used to endorse or promote products derived
67   * from this Software without prior written permission of MetaStuff, Ltd. For
68   * written permission, please contact dom4j-info@metastuff.com.
69   * 
70   * 4. Products derived from this Software may not be called "DOM4J" nor may
71   * "DOM4J" appear in their names without prior written permission of MetaStuff,
72   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
73   * 
74   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
75   * 
76   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
77   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
78   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
79   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
80   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
81   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
82   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
83   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
84   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
85   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
86   * POSSIBILITY OF SUCH DAMAGE.
87   * 
88   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
89   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/io/DOMWriterTest.html0000644000175000017500000002436610242117724022525 0ustar ebourgebourg DOMWriterTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.StringWriter;
13  
14  import org.dom4j.AbstractTestCase;
15  
16  import org.w3c.dom.NamedNodeMap;
17  
18  /***
19   * DOCUMENT ME!
20   * 
21   * @author Maarten
22   */
23  public class DOMWriterTest extends AbstractTestCase {
24      public static void main(String[] args) {
25          TestRunner.run(DOMWriterTest.class);
26      }
27  
28      public void testNamespaceBug() throws Exception {
29          org.dom4j.Document doc = getDocument("/xml/namespaces.xml");
30          DOMWriter writer = new DOMWriter(org.dom4j.dom.DOMDocument.class);
31          org.w3c.dom.Document result = writer.write(doc);
32  
33          NamedNodeMap atts = result.getDocumentElement().getAttributes();
34          assertEquals(4, atts.getLength());
35  
36          XMLWriter wr = new XMLWriter();
37          wr.setOutputStream(System.out);
38          wr.write((org.dom4j.Document) result);
39      }
40  
41      public void testBug905745() throws Exception {
42          org.dom4j.Document doc = getDocument("/xml/namespaces.xml");
43          DOMWriter writer = new DOMWriter();
44          org.w3c.dom.Document result = writer.write(doc);
45  
46          NamedNodeMap atts = result.getDocumentElement().getAttributes();
47          org.w3c.dom.Node versionAttr = atts.getNamedItem("version");
48          assertNotNull(versionAttr);
49          assertNotNull(versionAttr.getLocalName());
50          assertEquals("version", versionAttr.getLocalName());
51          assertEquals("version", versionAttr.getNodeName());
52      }
53  
54      public void testBug926752() throws Exception {
55          org.dom4j.Document doc = getDocument("/xml/test/defaultNamespace.xml");
56          DOMWriter writer = new DOMWriter(org.dom4j.dom.DOMDocument.class);
57          org.w3c.dom.Document result = writer.write(doc);
58  
59          NamedNodeMap atts = result.getDocumentElement().getAttributes();
60          assertEquals(1, atts.getLength());
61  
62          OutputFormat format = OutputFormat.createCompactFormat();
63          format.setSuppressDeclaration(true);
64  
65          XMLWriter wr = new XMLWriter(format);
66          StringWriter strWriter = new StringWriter();
67          wr.setWriter(strWriter);
68          wr.write((org.dom4j.Document) result);
69          assertEquals("<a xmlns=\"dummyNamespace\"><b><c>Hello</c></b></a>",
70                  strWriter.toString());
71      }
72  }
73  
74  /*
75   * Redistribution and use of this software and associated documentation
76   * ("Software"), with or without modification, are permitted provided that the
77   * following conditions are met:
78   * 
79   * 1. Redistributions of source code must retain copyright statements and
80   * notices. Redistributions must also contain a copy of this document.
81   * 
82   * 2. Redistributions in binary form must reproduce the above copyright notice,
83   * this list of conditions and the following disclaimer in the documentation
84   * and/or other materials provided with the distribution.
85   * 
86   * 3. The name "DOM4J" must not be used to endorse or promote products derived
87   * from this Software without prior written permission of MetaStuff, Ltd. For
88   * written permission, please contact dom4j-info@metastuff.com.
89   * 
90   * 4. Products derived from this Software may not be called "DOM4J" nor may
91   * "DOM4J" appear in their names without prior written permission of MetaStuff,
92   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
93   * 
94   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
95   * 
96   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
97   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
98   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
99   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
100  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
101  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
102  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
103  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
104  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
105  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
106  * POSSIBILITY OF SUCH DAMAGE.
107  * 
108  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
109  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/ValidationTest.html0000644000175000017500000001664410242117745022377 0ustar ebourgebourg ValidationTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.io.SAXReader;
13  
14  /***
15   * A test harness for validation when using SAXReader
16   * 
17   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
18   * @version $Revision: 1.3 $
19   */
20  public class ValidationTest extends AbstractTestCase {
21      public static void main(String[] args) {
22          TestRunner.run(ValidationTest.class);
23      }
24  
25      // Test case(s)
26      // -------------------------------------------------------------------------
27      public void testValidation() throws Exception {
28          try {
29              SAXReader reader = new SAXReader(true);
30              reader.read("test");
31              fail();
32          } catch (DocumentException e) {
33              // internal parser is non validating, so OK
34          }
35      }
36  }
37  
38  /*
39   * Redistribution and use of this software and associated documentation
40   * ("Software"), with or without modification, are permitted provided that the
41   * following conditions are met:
42   * 
43   * 1. Redistributions of source code must retain copyright statements and
44   * notices. Redistributions must also contain a copy of this document.
45   * 
46   * 2. Redistributions in binary form must reproduce the above copyright notice,
47   * this list of conditions and the following disclaimer in the documentation
48   * and/or other materials provided with the distribution.
49   * 
50   * 3. The name "DOM4J" must not be used to endorse or promote products derived
51   * from this Software without prior written permission of MetaStuff, Ltd. For
52   * written permission, please contact dom4j-info@metastuff.com.
53   * 
54   * 4. Products derived from this Software may not be called "DOM4J" nor may
55   * "DOM4J" appear in their names without prior written permission of MetaStuff,
56   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
57   * 
58   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
59   * 
60   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
61   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
62   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
64   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
65   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
66   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
67   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
68   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
69   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
70   * POSSIBILITY OF SUCH DAMAGE.
71   * 
72   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
73   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/MergeTextTest.html0000644000175000017500000002354110242117737022204 0ustar ebourgebourg MergeTextTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.Iterator;
13  
14  import org.dom4j.io.SAXReader;
15  
16  /***
17   * A test harness for SAXReader option setMergeAdjacentText(true)
18   * 
19   * @author <a href="mailto:slehmann@novell.com">Steen Lehmann </a>
20   * @version $Revision: 1.4 $
21   */
22  public class MergeTextTest extends AbstractTestCase {
23      /*** Input XML file to read */
24      private static final String INPUT_XML_FILE = "/xml/test/mergetext.xml";
25  
26      public static void main(String[] args) {
27          TestRunner.run(MergeTextTest.class);
28      }
29  
30      // Test case(s)
31      // -------------------------------------------------------------------------
32      public void testNoAdjacentText() throws Exception {
33          // After reading using SAXReader with mergeAdjacentText true,
34          // no two Text objects should be adjacent to each other in the
35          // document.
36          SAXReader reader = new SAXReader();
37          reader.setMergeAdjacentText(true);
38  
39          Document document = getDocument(INPUT_XML_FILE, reader);
40  
41          checkNoAdjacent(document.getRootElement());
42          log("No adjacent Text nodes in " + document.asXML());
43      }
44  
45      // Implementation methods
46      // -------------------------------------------------------------------------
47      private void checkNoAdjacent(Element parent) {
48          // Check that no two Text nodes are adjacent in the parent's content
49          Node prev = null;
50          Iterator iter = parent.nodeIterator();
51  
52          while (iter.hasNext()) {
53              Node n = (Node) iter.next();
54  
55              if (n instanceof Text && ((prev != null) && prev instanceof Text)) {
56                  fail("Node: " + n + " is text and so is its "
57                          + "preceding sibling: " + prev);
58              } else if (n instanceof Element) {
59                  checkNoAdjacent((Element) n);
60              }
61  
62              prev = n;
63          }
64      }
65  }
66  
67  /*
68   * Redistribution and use of this software and associated documentation
69   * ("Software"), with or without modification, are permitted provided that the
70   * following conditions are met:
71   * 
72   * 1. Redistributions of source code must retain copyright statements and
73   * notices. Redistributions must also contain a copy of this document.
74   * 
75   * 2. Redistributions in binary form must reproduce the above copyright notice,
76   * this list of conditions and the following disclaimer in the documentation
77   * and/or other materials provided with the distribution.
78   * 
79   * 3. The name "DOM4J" must not be used to endorse or promote products derived
80   * from this Software without prior written permission of MetaStuff, Ltd. For
81   * written permission, please contact dom4j-info@metastuff.com.
82   * 
83   * 4. Products derived from this Software may not be called "DOM4J" nor may
84   * "DOM4J" appear in their names without prior written permission of MetaStuff,
85   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
86   * 
87   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
88   * 
89   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
90   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
91   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
92   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
93   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
94   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
95   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
96   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
97   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
98   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
99   * POSSIBILITY OF SUCH DAMAGE.
100  * 
101  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
102  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/XMLWriterTest.html0000644000175000017500000014371310242117574022140 0ustar ebourgebourg XMLWriterTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.ByteArrayInputStream;
13  import java.io.ByteArrayOutputStream;
14  import java.io.StringReader;
15  import java.io.StringWriter;
16  
17  import org.dom4j.io.OutputFormat;
18  import org.dom4j.io.SAXReader;
19  import org.dom4j.io.XMLWriter;
20  import org.dom4j.tree.BaseElement;
21  import org.dom4j.tree.DefaultDocument;
22  
23  import org.xml.sax.ContentHandler;
24  import org.xml.sax.SAXException;
25  import org.xml.sax.helpers.AttributesImpl;
26  
27  /***
28   * A simple test harness to check that the XML Writer works
29   * 
30   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
31   * @version $Revision: 1.7.2.1 $
32   */
33  public class XMLWriterTest extends AbstractTestCase {
34      protected static final boolean VERBOSE = false;
35  
36      public static void main(String[] args) {
37          TestRunner.run(XMLWriterTest.class);
38      }
39  
40      // Test case(s)
41      // -------------------------------------------------------------------------
42      public void testBug1180791() throws Exception {
43          String xml = "<?xml version=\"1.0\"?><root><foo>bar</foo></root>";
44  
45          SAXReader reader = new SAXReader();
46          Document doc = reader.read(new StringReader(xml));
47          // of with newlines
48          OutputFormat format = new OutputFormat();
49          format.setNewlines(true);
50          //format.setTrimText(true);
51          // first time
52          StringWriter writer = new StringWriter();
53          XMLWriter xmlwriter = new XMLWriter(writer, format);
54          xmlwriter.write(doc);
55          System.out.println(writer.toString());
56  
57          // 2nd time
58          doc = reader.read(new StringReader(writer.toString()));
59          writer = new StringWriter();
60          xmlwriter = new XMLWriter(writer, format);
61          xmlwriter.write(doc);
62          System.out.println(writer.toString());
63      }
64  
65      public void testBug1119733() throws Exception {
66          Document doc = DocumentHelper
67                  .parseText("<root><code>foo</code> bar</root>");
68  
69          StringWriter out = new StringWriter();
70          XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
71          writer.write(doc);
72          writer.close();
73  
74          String xml = out.toString();
75  
76          System.out.println(xml);
77          assertEquals("whitespace problem", -1, xml.indexOf("</code>bar"));
78      }
79  
80      public void testBug1119733WithSAXEvents() throws Exception {
81          StringWriter out = new StringWriter();
82          XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
83          writer.startDocument();
84          writer.startElement(null, "root", "root", new AttributesImpl());
85          writer.startElement(null, "code", "code", new AttributesImpl());
86          writer.characters(new char[] { 'f', 'o', 'o' }, 0, 3);
87          writer.endElement(null, "code", "code");
88          writer.characters(new char[] { ' ', 'b', 'a', 'r' }, 0, 4);
89          writer.endElement(null, "root", "root");
90          writer.endDocument();
91          writer.close();
92  
93          String xml = out.toString();
94  
95          System.out.println(xml);
96          assertEquals("whitespace problem", -1, xml.indexOf("</code>bar"));
97      }
98  
99      public void testWriter() throws Exception {
100         Object object = document;
101         StringWriter out = new StringWriter();
102 
103         XMLWriter writer = new XMLWriter(out);
104         writer.write(object);
105         writer.close();
106 
107         String text = out.toString();
108 
109         if (VERBOSE) {
110             log("Text output is [");
111             log(text);
112             log("]. Done");
113         }
114 
115         assertTrue("Output text is bigger than 10 characters",
116                 text.length() > 10);
117     }
118 
119     public void testEncodingFormats() throws Exception {
120         testEncoding("UTF-8");
121         testEncoding("UTF-16");
122         testEncoding("ISO-8859-1");
123     }
124 
125     public void testWritingEmptyElement() throws Exception {
126         Document doc = DocumentFactory.getInstance().createDocument();
127         Element grandFather = doc.addElement("grandfather");
128         Element parent1 = grandFather.addElement("parent");
129         Element child1 = parent1.addElement("child1");
130         Element child2 = parent1.addElement("child2");
131         child2.setText("test");
132 
133         Element parent2 = grandFather.addElement("parent");
134         Element child3 = parent2.addElement("child3");
135         child3.setText("test");
136 
137         StringWriter buffer = new StringWriter();
138         OutputFormat format = OutputFormat.createPrettyPrint();
139         XMLWriter writer = new XMLWriter(buffer, format);
140         writer.write(doc);
141 
142         String xml = buffer.toString();
143 
144         System.out.println(xml);
145 
146         assertTrue("child2 not present",
147                 xml.indexOf("<child2>test</child2>") != -1);
148     }
149 
150     protected void testEncoding(String encoding) throws Exception {
151         ByteArrayOutputStream out = new ByteArrayOutputStream();
152 
153         OutputFormat format = OutputFormat.createPrettyPrint();
154         format.setEncoding(encoding);
155 
156         XMLWriter writer = new XMLWriter(out, format);
157         writer.write(document);
158         writer.close();
159 
160         log("Wrote to encoding: " + encoding);
161     }
162 
163     public void testWriterBug() throws Exception {
164         Element project = new BaseElement("project");
165         Document doc = new DefaultDocument(project);
166 
167         ByteArrayOutputStream out = new ByteArrayOutputStream();
168         XMLWriter writer = new XMLWriter(out, new OutputFormat("\t", true,
169                 "ISO-8859-1"));
170         writer.write(doc);
171 
172         ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
173         SAXReader reader = new SAXReader();
174         Document doc2 = reader.read(in);
175 
176         assertTrue("Generated document has a root element", doc2
177                 .getRootElement() != null);
178         assertEquals("Generated document has corrent named root element", doc2
179                 .getRootElement().getName(), "project");
180     }
181 
182     public void testNamespaceBug() throws Exception {
183         Document doc = DocumentHelper.createDocument();
184 
185         Element root = doc.addElement("root", "ns1");
186         Element child1 = root.addElement("joe", "ns2");
187         child1.addElement("zot", "ns1");
188 
189         StringWriter out = new StringWriter();
190         XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
191         writer.write(doc);
192 
193         String text = out.toString();
194 
195         // System.out.println( "Generated:" + text );
196         Document doc2 = DocumentHelper.parseText(text);
197         root = doc2.getRootElement();
198         assertEquals("root has incorrect namespace", "ns1", root
199                 .getNamespaceURI());
200 
201         Element joe = (Element) root.elementIterator().next();
202         assertEquals("joe has correct namespace", "ns2", joe.getNamespaceURI());
203 
204         Element zot = (Element) joe.elementIterator().next();
205         assertEquals("zot has correct namespace", "ns1", zot.getNamespaceURI());
206     }
207 
208     /***
209      * This test harness was supplied by Lari Hotari
210      * 
211      * @throws Exception DOCUMENT ME!
212      */
213     public void testContentHandler() throws Exception {
214         StringWriter out = new StringWriter();
215         OutputFormat format = OutputFormat.createPrettyPrint();
216         format.setEncoding("iso-8859-1");
217 
218         XMLWriter writer = new XMLWriter(out, format);
219         generateXML(writer);
220         writer.close();
221 
222         String text = out.toString();
223 
224         if (VERBOSE) {
225             log("Created XML");
226             log(text);
227         }
228 
229         // now lets parse the output and test it with XPath
230         Document doc = DocumentHelper.parseText(text);
231         String value = doc.valueOf("/processes[@name='arvojoo']");
232         assertEquals("Document contains the correct text", "jeejee", value);
233     }
234 
235     /***
236      * This test was provided by Manfred Lotz
237      * 
238      * @throws Exception DOCUMENT ME!
239      */
240     public void testWhitespaceBug() throws Exception {
241         String notes = "<notes> This is a      multiline\n\rentry</notes>";
242         Document doc = DocumentHelper.parseText(notes);
243 
244         OutputFormat format = new OutputFormat();
245         format.setEncoding("UTF-8");
246         format.setIndentSize(4);
247         format.setNewlines(true);
248         format.setTrimText(true);
249         format.setExpandEmptyElements(true);
250 
251         StringWriter buffer = new StringWriter();
252         XMLWriter writer = new XMLWriter(buffer, format);
253         writer.write(doc);
254 
255         String xml = buffer.toString();
256         log(xml);
257 
258         Document doc2 = DocumentHelper.parseText(xml);
259         String text = doc2.valueOf("/notes");
260         String expected = "This is a multiline entry";
261 
262         assertEquals("valueOf() returns the correct text padding", expected,
263                 text);
264 
265         assertEquals("getText() returns the correct text padding", expected,
266                 doc2.getRootElement().getText());
267     }
268 
269     /***
270      * This test was provided by Manfred Lotz
271      * 
272      * @throws Exception DOCUMENT ME!
273      */
274     public void testWhitespaceBug2() throws Exception {
275         Document doc = DocumentHelper.createDocument();
276         Element root = doc.addElement("root");
277         Element meaning = root.addElement("meaning");
278         meaning.addText("to li");
279         meaning.addText("ve");
280 
281         OutputFormat format = new OutputFormat();
282         format.setEncoding("UTF-8");
283         format.setIndentSize(4);
284         format.setNewlines(true);
285         format.setTrimText(true);
286         format.setExpandEmptyElements(true);
287 
288         StringWriter buffer = new StringWriter();
289         XMLWriter writer = new XMLWriter(buffer, format);
290         writer.write(doc);
291 
292         String xml = buffer.toString();
293         log(xml);
294 
295         Document doc2 = DocumentHelper.parseText(xml);
296         String text = doc2.valueOf("/root/meaning");
297         String expected = "to live";
298 
299         assertEquals("valueOf() returns the correct text padding", expected,
300                 text);
301 
302         assertEquals("getText() returns the correct text padding", expected,
303                 doc2.getRootElement().element("meaning").getText());
304     }
305 
306     public void testPadding() throws Exception {
307         Document doc = DocumentFactory.getInstance().createDocument();
308         Element root = doc.addElement("root");
309         root.addText("prefix    ");
310         root.addElement("b");
311         root.addText("      suffix");
312 
313         OutputFormat format = new OutputFormat("", false);
314         format.setOmitEncoding(true);
315         format.setSuppressDeclaration(true);
316         format.setExpandEmptyElements(true);
317         format.setPadText(true);
318         format.setTrimText(true);
319 
320         StringWriter buffer = new StringWriter();
321         XMLWriter writer = new XMLWriter(buffer, format);
322         writer.write(doc);
323 
324         String xml = buffer.toString();
325 
326         System.out.println("xml: " + xml);
327 
328         String expected = "<root>prefix <b></b> suffix</root>";
329         assertEquals(expected, xml);
330     }
331 
332     public void testPadding2() throws Exception {
333         Document doc = DocumentFactory.getInstance().createDocument();
334         Element root = doc.addElement("root");
335         root.addText("prefix");
336         root.addElement("b");
337         root.addText("suffix");
338 
339         OutputFormat format = new OutputFormat("", false);
340         format.setOmitEncoding(true);
341         format.setSuppressDeclaration(true);
342         format.setExpandEmptyElements(true);
343         format.setPadText(true);
344         format.setTrimText(true);
345 
346         StringWriter buffer = new StringWriter();
347         XMLWriter writer = new XMLWriter(buffer, format);
348         writer.write(doc);
349 
350         String xml = buffer.toString();
351 
352         System.out.println("xml: " + xml);
353 
354         String expected = "<root>prefix<b></b>suffix</root>";
355         assertEquals(expected, xml);
356     }
357 
358     /*
359      * This must be tested manually to see if the layout is correct.
360      */
361     public void testPrettyPrinting() throws Exception {
362         Document doc = DocumentFactory.getInstance().createDocument();
363         doc.addElement("summary").addAttribute("date", "6/7/8").addElement(
364                 "orderline").addText("puffins").addElement("ranjit")
365                 .addComment("Ranjit is a happy Puffin");
366 
367         XMLWriter writer = new XMLWriter(System.out, OutputFormat
368                 .createPrettyPrint());
369         writer.write(doc);
370 
371         doc = DocumentFactory.getInstance().createDocument();
372         doc.addElement("summary").addAttribute("date", "6/7/8").addElement(
373                 "orderline").addText("puffins").addElement("ranjit")
374                 .addComment("Ranjit is a happy Puffin").addComment(
375                         "another comment").addElement("anotherElement");
376         writer.write(doc);
377     }
378 
379     public void testAttributeQuotes() throws Exception {
380         Document doc = DocumentFactory.getInstance().createDocument();
381         doc.addElement("root").addAttribute("test", "text with ' in it");
382 
383         StringWriter out = new StringWriter();
384         XMLWriter writer = new XMLWriter(out, OutputFormat
385                 .createCompactFormat());
386         writer.write(doc);
387 
388         String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
389                 + "<root test=\"text with ' in it\"/>";
390         assertEquals(expected, out.toString());
391     }
392 
393     public void testBug868408() throws Exception {
394         Document doc = getDocument("/xml/web.xml");
395         Document doc2 = DocumentHelper.parseText(doc.asXML());
396         assertEquals(doc.asXML(), doc2.asXML());
397     }
398 
399     public void testBug923882() throws Exception {
400         Document doc = DocumentFactory.getInstance().createDocument();
401         Element root = doc.addElement("root");
402         root.addText("this is ");
403         root.addText(" sim");
404         root.addText("ple text ");
405         root.addElement("child");
406         root.addText(" contai");
407         root.addText("ning spaces and");
408         root.addText(" multiple textnodes");
409 
410         OutputFormat format = new OutputFormat();
411         format.setEncoding("UTF-8");
412         format.setIndentSize(4);
413         format.setNewlines(true);
414         format.setTrimText(true);
415         format.setExpandEmptyElements(true);
416 
417         StringWriter buffer = new StringWriter();
418         XMLWriter writer = new XMLWriter(buffer, format);
419         writer.write(doc);
420 
421         String xml = buffer.toString();
422         log(xml);
423 
424         int start = xml.indexOf("<root");
425         int end = xml.indexOf("/root>") + 6;
426         String eol = "\n"; // System.getProperty("line.separator");
427         String expected = "<root>this is simple text" + eol
428                 + "    <child></child>containing spaces and multiple textnodes"
429                 + eol + "</root>";
430         System.out.println("Expected:");
431         System.out.println(expected);
432         System.out.println("Obtained:");
433         System.out.println(xml.substring(start, end));
434         assertEquals(expected, xml.substring(start, end));
435     }
436 
437     public void testEscapeXML() throws Exception {
438         ByteArrayOutputStream os = new ByteArrayOutputStream();
439         OutputFormat format = new OutputFormat(null, false, "ISO-8859-2");
440         format.setSuppressDeclaration(true);
441 
442         XMLWriter writer = new XMLWriter(os, format);
443 
444         Document document = DocumentFactory.getInstance().createDocument();
445         Element root = document.addElement("root");
446         root.setText("bla &#c bla");
447 
448         writer.write(document);
449 
450         String result = os.toString();
451         System.out.println(result);
452 
453         Document doc2 = DocumentHelper.parseText(result);
454         doc2.normalize(); // merges adjacant Text nodes
455         System.out.println(doc2.getRootElement().getText());
456         assertNodesEqual(document, doc2);
457     }
458 
459     public void testWriteEntities() throws Exception {
460         String xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
461                 + "<!DOCTYPE xml [<!ENTITY copy \"&#169;\"> "
462                 + "<!ENTITY trade \"&#8482;\"> "
463                 + "<!ENTITY deg \"&#x00b0;\"> " + "<!ENTITY gt \"&#62;\"> "
464                 + "<!ENTITY sup2 \"&#x00b2;\"> "
465                 + "<!ENTITY frac14 \"&#x00bc;\"> "
466                 + "<!ENTITY quot \"&#34;\"> "
467                 + "<!ENTITY frac12 \"&#x00bd;\"> "
468                 + "<!ENTITY euro \"&#x20ac;\"> "
469                 + "<!ENTITY Omega \"&#937;\"> ]>\n" + "<root />";
470 
471         SAXReader reader = new SAXReader("org.apache.xerces.parsers.SAXParser");
472         reader.setIncludeInternalDTDDeclarations(true);
473 
474         Document doc = reader.read(new StringReader(xml));
475         StringWriter wr = new StringWriter();
476         XMLWriter writer = new XMLWriter(wr);
477         writer.write(doc);
478 
479         String xml2 = wr.toString();
480         System.out.println(xml2);
481 
482         Document doc2 = DocumentHelper.parseText(xml2);
483 
484         assertNodesEqual(doc, doc2);
485     }
486 
487     public void testEscapeChars() throws Exception {
488         Document document = DocumentFactory.getInstance().createDocument();
489         Element root = document.addElement("root");
490         root.setText("blahblah " + '\u008f');
491 
492         XMLWriter writer = new XMLWriter();
493         StringWriter strWriter = new StringWriter();
494         writer.setWriter(strWriter);
495         writer.setMaximumAllowedCharacter(127);
496         writer.write(document);
497 
498         String xml = strWriter.toString();
499     }
500 
501     public void testEscapeText() throws SAXException {
502         StringWriter writer = new StringWriter();
503         XMLWriter xmlWriter = new XMLWriter(writer);
504         xmlWriter.setEscapeText(false);
505 
506         String txt = "<test></test>";
507 
508         xmlWriter.startDocument();
509         xmlWriter.characters(txt.toCharArray(), 0, txt.length());
510         xmlWriter.endDocument();
511 
512         String output = writer.toString();
513         System.out.println(output);
514         assertTrue(output.indexOf("<test>") != -1);
515     }
516 
517     public void testNullCData() {
518         Element e = DocumentHelper.createElement("test");
519         e.add(DocumentHelper.createElement("another").addCDATA(null));
520 
521         Document doc = DocumentHelper.createDocument(e);
522 
523         assertEquals(-1, e.asXML().indexOf("null"));
524         assertEquals(-1, doc.asXML().indexOf("null"));
525 
526         System.out.println(e.asXML());
527         System.out.println(doc.asXML());
528     }
529 
530     protected void generateXML(ContentHandler handler) throws SAXException {
531         handler.startDocument();
532 
533         AttributesImpl attrs = new AttributesImpl();
534         attrs.clear();
535         attrs.addAttribute("", "", "name", "CDATA", "arvojoo");
536         handler.startElement("", "", "processes", attrs);
537 
538         String text = "jeejee";
539         char[] textch = text.toCharArray();
540         handler.characters(textch, 0, textch.length);
541         handler.endElement("", "", "processes");
542         handler.endDocument();
543     }
544 }
545 
546 /*
547  * Redistribution and use of this software and associated documentation
548  * ("Software"), with or without modification, are permitted provided that the
549  * following conditions are met:
550  * 
551  * 1. Redistributions of source code must retain copyright statements and
552  * notices. Redistributions must also contain a copy of this document.
553  * 
554  * 2. Redistributions in binary form must reproduce the above copyright notice,
555  * this list of conditions and the following disclaimer in the documentation
556  * and/or other materials provided with the distribution.
557  * 
558  * 3. The name "DOM4J" must not be used to endorse or promote products derived
559  * from this Software without prior written permission of MetaStuff, Ltd. For
560  * written permission, please contact dom4j-info@metastuff.com.
561  * 
562  * 4. Products derived from this Software may not be called "DOM4J" nor may
563  * "DOM4J" appear in their names without prior written permission of MetaStuff,
564  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
565  * 
566  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
567  * 
568  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
569  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
570  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
571  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
572  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
573  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
574  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
575  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
576  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
577  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
578  * POSSIBILITY OF SUCH DAMAGE.
579  * 
580  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
581  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/LineFeedTest.html0000644000175000017500000002524010242117701021740 0ustar ebourgebourg LineFeedTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.StringWriter;
13  
14  import org.dom4j.io.OutputFormat;
15  import org.dom4j.io.XMLWriter;
16  
17  public class LineFeedTest extends AbstractTestCase {
18      private static final String ATT_TEXT = "Hello&#xa;There&#xa;&lt;&gt;&amp;";
19  
20      private static final String TEXT = "Hello\nThere\n&lt;&gt;&amp;";
21  
22      private static final String EXPECTED_TEXT = "Hello\nThere\n<>&";
23  
24      private static final String EXPECTED_ATT_TEXT = "Hello There <>&";
25  
26      public static void main(String[] args) {
27          TestRunner.run(LineFeedTest.class);
28      }
29  
30      public void testElement() throws Exception {
31          Document doc = DocumentHelper.parseText("<elem>" + TEXT + "</elem>");
32          Element elem = doc.getRootElement();
33          assertEquals(EXPECTED_TEXT, elem.getText());
34      }
35  
36      public void testAttribute() throws Exception {
37          Document doc = DocumentHelper
38                  .parseText("<elem attr=\"" + TEXT + "\"/>");
39          Element elem = doc.getRootElement();
40  
41          // System.out.println(elem.attributeValue("attr"));
42          assertEquals(EXPECTED_ATT_TEXT, elem.attributeValue("attr"));
43  
44          doc = DocumentHelper.parseText("<elem attr=\"" + ATT_TEXT + "\"/>");
45          elem = doc.getRootElement();
46  
47          // System.out.println(elem.attributeValue("attr"));
48          assertEquals(EXPECTED_TEXT, elem.attributeValue("attr"));
49      }
50  
51      public void testCDATA() throws Exception {
52          Document doc = DocumentHelper.parseText("<elem><![CDATA["
53                  + EXPECTED_TEXT + "]]></elem>");
54          Element elem = doc.getRootElement();
55          assertEquals(EXPECTED_TEXT, elem.getText());
56      }
57  
58      public void testXmlWriter() throws Exception {
59          Element elem = DocumentHelper.createElement("elem");
60          Document doc = DocumentHelper.createDocument(elem);
61          elem.addCDATA(EXPECTED_TEXT);
62  
63          StringWriter sw = new StringWriter();
64          XMLWriter xWriter = new XMLWriter(sw, OutputFormat.createPrettyPrint());
65          xWriter.write(doc);
66          xWriter.close();
67  
68          String xmlString = sw.toString();
69          doc = DocumentHelper.parseText(xmlString);
70          elem = doc.getRootElement();
71          assertEquals(EXPECTED_TEXT, elem.getText());
72      }
73  }
74  
75  /*
76   * Redistribution and use of this software and associated documentation
77   * ("Software"), with or without modification, are permitted provided that the
78   * following conditions are met:
79   * 
80   * 1. Redistributions of source code must retain copyright statements and
81   * notices. Redistributions must also contain a copy of this document.
82   * 
83   * 2. Redistributions in binary form must reproduce the above copyright notice,
84   * this list of conditions and the following disclaimer in the documentation
85   * and/or other materials provided with the distribution.
86   * 
87   * 3. The name "DOM4J" must not be used to endorse or promote products derived
88   * from this Software without prior written permission of MetaStuff, Ltd. For
89   * written permission, please contact dom4j-info@metastuff.com.
90   * 
91   * 4. Products derived from this Software may not be called "DOM4J" nor may
92   * "DOM4J" appear in their names without prior written permission of MetaStuff,
93   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
94   * 
95   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
96   * 
97   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
98   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
99   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
100  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
101  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
102  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
103  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
104  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
105  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
106  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
107  * POSSIBILITY OF SUCH DAMAGE.
108  * 
109  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
110  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/XMLSpaceAttributeTest.html0000644000175000017500000006037210242117735023601 0ustar ebourgebourg XMLSpaceAttributeTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.IOException;
13  
14  /***
15   * A test harness to test the xml:space attribute for preserve. If it is
16   * preserve, then keep whitespace.
17   * 
18   * @author <a href="mailto:ddlucas@lse.com">David Lucas </a>
19   * @version $Revision: 1.4 $
20   */
21  public class XMLSpaceAttributeTest extends AbstractTestCase {
22      public static void main(String[] args) {
23          TestRunner.run(XMLSpaceAttributeTest.class);
24      }
25  
26      // Test case(s)
27      // -------------------------------------------------------------------------
28      public void testWithTextTrimOn() throws Exception {
29          String xmlString = "<top >"
30                  + "<row><col>   This is a test!</col></row>"
31                  + "<row><col xml:space=\'preserve\' >   This is a test!</col>"
32                  + "</row><row><col>   This is a test!</col></row>" + "</top>";
33          Document doc1 = DocumentHelper.parseText(xmlString);
34          Element c2 = (Element) doc1.selectSingleNode("/top/row[2]/col");
35          String expected = "   New Text TrimOn! ";
36          c2.setText(expected);
37  
38          String xml = rewriteToXmlString(doc1, true);
39  
40          Document doc2 = DocumentHelper.parseText(xml);
41          Element c4 = (Element) doc2.selectSingleNode("/top/row[2]/col");
42          String actual = c4.getText();
43  
44          assertEquals("compared element text expecting whitespace", expected,
45                  actual);
46  
47          expected = expected.trim();
48          actual = c4.getTextTrim();
49          assertEquals("compared element getTextTrim", expected, actual);
50  
51          expected = "This is a test!";
52  
53          Element c5 = (Element) doc2.selectSingleNode("/top/row[3]/col");
54          actual = c5.getText();
55          assertEquals("compared element text expecting trimmed whitespace",
56                  expected, actual);
57      }
58  
59      // -------------------------------------------------------------------------
60      public void testWithTextTrimOff() throws Exception {
61          String xmlString = "<top >"
62                  + "<row><col>   This is a test!</col></row>"
63                  + "<row><col xml:space=\'preserve\' >   This is a test!</col>"
64                  + "</row><row><col>   This is a test!</col></row>" + "</top>";
65          Document doc1 = DocumentHelper.parseText(xmlString);
66          Element c2 = (Element) doc1.selectSingleNode("/top/row[2]/col");
67          String expected = "   New Text TrimOff! ";
68          c2.setText(expected);
69  
70          String xml = rewriteToXmlString(doc1, false);
71  
72          Document doc2 = DocumentHelper.parseText(xml);
73          Element c4 = (Element) doc2.selectSingleNode("/top/row[2]/col");
74          String actual = c4.getText();
75  
76          assertEquals("compared element text expecting whitespace", expected,
77                  actual);
78      }
79  
80      // -------------------------------------------------------------------------
81      public void testWithTextTrimOnFollow() throws Exception {
82          String xmlString = "<top >"
83                  + "<row><col>   This is a test!</col></row>" + "<row>"
84                  + "<col xml:space=\'preserve\' >"
85                  + "<a><b>   This is embedded!</b></a>"
86                  + "<a><b>   This is space=preserve too!</b></a>" + "</col>"
87                  + "</row>" + "<row><col>   This is a test!</col></row>"
88                  + "</top>";
89          Document doc1 = DocumentHelper.parseText(xmlString);
90          Element c2 = (Element) doc1.selectSingleNode("/top/row[2]/col/a[1]/b");
91          String expected = "   New Text TrimOnFollow! ";
92          c2.setText(expected);
93  
94          String xml = rewriteToXmlString(doc1, true);
95  
96          Document doc2 = DocumentHelper.parseText(xml);
97  
98          Element c4 = (Element) doc2.selectSingleNode("/top/row[2]/col/a[1]/b");
99          String actual = c4.getText();
100 
101         assertEquals("compared element text expecting whitespace", expected,
102                 actual);
103 
104         Element c8 = (Element) doc2.selectSingleNode("/top/row[2]/col/a[2]/b");
105 
106         expected = "   This is space=preserve too!";
107         actual = c8.getText();
108         assertEquals("compared element text follow trimmed whitespace",
109                 expected, actual);
110 
111         expected = expected.trim();
112         actual = c8.getTextTrim();
113         assertEquals("compared element getTextTrim", expected, actual);
114 
115         Element c12 = (Element) doc2.selectSingleNode("/top/row[3]/col");
116 
117         expected = "This is a test!";
118         actual = c12.getText();
119         assertEquals("compared element text follow trimmed whitespace",
120                 expected, actual);
121     }
122 
123     // -------------------------------------------------------------------------
124     public void testWithTextTrimOnNested() throws Exception {
125         String xmlString = "<top >"
126                 + "<row><col>   This is a test!</col></row>" + "<row>"
127                 + "<col xml:space='preserve' >" + "<a>"
128                 + "<b>   This is embedded! </b>"
129                 + "<b xml:space='default' >   This should do global default! "
130                 + "</b><b>   This is embedded! </b>" + "</a>" + "</col>"
131                 + "</row>" + "<row><col>   This is a test!</col></row>"
132                 + "</top>";
133         Document doc1 = DocumentHelper.parseText(xmlString);
134         Element c2 = (Element) doc1.selectSingleNode("/top/row[2]/col/a[1]/b");
135         String expected = "   New Text TrimOnNested! ";
136         c2.setText(expected);
137 
138         String xml = rewriteToXmlString(doc1, true);
139 
140         Document doc2 = DocumentHelper.parseText(xml);
141 
142         Element c4 = (Element) doc2
143                 .selectSingleNode("/top/row[2]/col/a[1]/b[1]");
144         String actual = c4.getText();
145         assertEquals("compared element text expecting whitespace", expected,
146                 actual);
147 
148         Element c8 = (Element) doc2
149                 .selectSingleNode("/top/row[2]/col/a[1]/b[2]");
150         expected = "This should do global default!";
151         actual = c8.getText();
152         assertEquals("compared element text nested trimmed whitespace",
153                 expected, actual);
154 
155         Element c12 = (Element) doc2
156                 .selectSingleNode("/top/row[2]/col/a[1]/b[3]");
157         expected = "   This is embedded! ";
158         actual = c12.getText();
159         assertEquals("compared element text nested preserved whitespace",
160                 expected, actual);
161     }
162 
163     // Implementation methods
164     // -------------------------------------------------------------------------
165     private String rewriteToXmlString(Document doc, boolean trimOn)
166             throws IOException {
167         org.dom4j.io.OutputFormat of = org.dom4j.io.OutputFormat
168                 .createCompactFormat();
169         of.setIndent(true);
170         of.setNewlines(true);
171         of.setExpandEmptyElements(false);
172         of.setSuppressDeclaration(false);
173         of.setOmitEncoding(false);
174         of.setEncoding("UTF-8");
175         of.setTrimText(trimOn);
176 
177         java.io.ByteArrayOutputStream os = new java.io.ByteArrayOutputStream();
178         java.io.BufferedOutputStream bos = new java.io.BufferedOutputStream(os);
179         org.dom4j.io.XMLWriter xmlWriter = new org.dom4j.io.XMLWriter(of);
180 
181         xmlWriter.setOutputStream(bos);
182         xmlWriter.write(doc);
183         xmlWriter.close();
184 
185         String xml = os.toString();
186 
187         // System.out.println("***** xml out *****\n"+xml);
188         return xml;
189     }
190 
191     // -------------------------------------------------------------------------
192     public void testWithEscapeTextTrimOn() throws Exception {
193         String xmlString = "<top >"
194                 + "<row><col>   This is a test!</col></row>"
195                 + "<row><col xml:space=\'preserve\' >   This is a test!\r\n"
196                 + "With a new line, special character like &amp; , and\t tab."
197                 + "</col></row><row><col>   This is a test!\r\nWith a new line,"
198                 + " special character like &amp; , and\t tab.</col></row>"
199                 + "</top>";
200         Document doc1 = DocumentHelper.parseText(xmlString);
201         String xml = rewriteToXmlString(doc1, true);
202         Document doc2 = DocumentHelper.parseText(xml);
203 
204         Element c2 = (Element) doc2.selectSingleNode("/top/row[2]/col");
205         String expected = "   This is a test!\nWith a new line, special "
206                 + "character like & , and\t tab.";
207         String actual = c2.getText();
208         assertEquals("compared element text expecting whitespace", expected,
209                 actual);
210 
211         Element c4 = (Element) doc2.selectSingleNode("/top/row[3]/col");
212         expected = "This is a test! With a new line, special character "
213                 + "like & , and tab.";
214         actual = c4.getText();
215         assertEquals("compared element text expecting whitespace", expected,
216                 actual);
217     }
218 }
219 
220 /*
221  * Redistribution and use of this software and associated documentation
222  * ("Software"), with or without modification, are permitted provided that the
223  * following conditions are met:
224  * 
225  * 1. Redistributions of source code must retain copyright statements and
226  * notices. Redistributions must also contain a copy of this document.
227  * 
228  * 2. Redistributions in binary form must reproduce the above copyright notice,
229  * this list of conditions and the following disclaimer in the documentation
230  * and/or other materials provided with the distribution.
231  * 
232  * 3. The name "DOM4J" must not be used to endorse or promote products derived
233  * from this Software without prior written permission of MetaStuff, Ltd. For
234  * written permission, please contact dom4j-info@metastuff.com.
235  * 
236  * 4. Products derived from this Software may not be called "DOM4J" nor may
237  * "DOM4J" appear in their names without prior written permission of MetaStuff,
238  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
239  * 
240  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
241  * 
242  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
243  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
244  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
245  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
246  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
247  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
248  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
249  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
250  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
251  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
252  * POSSIBILITY OF SUCH DAMAGE.
253  * 
254  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
255  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/AddNodeTest.html0000644000175000017500000002404410242117724021571 0ustar ebourgebourg AddNodeTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  /***
13   * A test harness to test the addNode() methods on node
14   * 
15   * @author Philippe Ombredanne
16   */
17  public class AddNodeTest extends AbstractTestCase {
18      public static void main(String[] args) {
19          TestRunner.run(AddNodeTest.class);
20      }
21  
22      // Test case(s)
23      // -------------------------------------------------------------------------
24      public void testDom4jAddNodeClone() {
25          Document maindoc = DocumentHelper.createDocument();
26          Element docroot = maindoc.addElement("document");
27          Element header = docroot.addElement("header").addText("Some Text");
28  
29          Document subdoc = DocumentHelper.createDocument();
30          Element docroot2 = subdoc.addElement("document");
31  
32          docroot2.add((Element) maindoc.selectSingleNode("/document/header")
33                  .clone());
34          assertEquals(subdoc.asXML(), maindoc.asXML());
35      }
36  
37      public void testDom4jAddNodeCreateCopy() {
38          Document maindoc = DocumentHelper.createDocument();
39          Element docroot = maindoc.addElement("document");
40          Element header = docroot.addElement("header").addText("Some Text");
41  
42          Document subdoc = DocumentHelper.createDocument();
43          Element docroot2 = subdoc.addElement("document");
44  
45          docroot2.add(((Element) maindoc.selectSingleNode("/document/header"))
46                  .createCopy());
47          assertEquals(subdoc.asXML(), maindoc.asXML());
48      }
49  
50      public void testDom4jAddNodeBug() {
51          Document maindoc = DocumentHelper.createDocument();
52          Element docroot = maindoc.addElement("document");
53          Element header = docroot.addElement("header").addText("Some Text");
54  
55          Document subdoc = DocumentHelper.createDocument();
56          Element subroot = subdoc.addElement("document");
57  
58          try {
59              // add the header node from maindoc without clone... or createCopy
60              subroot.add((Element) maindoc.selectSingleNode("/document/header"));
61              fail();
62          } catch (IllegalAddException e) {
63              // the header already has a parent, this exception is normal
64          }
65      }
66  }
67  
68  /*
69   * Redistribution and use of this software and associated documentation
70   * ("Software"), with or without modification, are permitted provided that the
71   * following conditions are met:
72   * 
73   * 1. Redistributions of source code must retain copyright statements and
74   * notices. Redistributions must also contain a copy of this document.
75   * 
76   * 2. Redistributions in binary form must reproduce the above copyright notice,
77   * this list of conditions and the following disclaimer in the documentation
78   * and/or other materials provided with the distribution.
79   * 
80   * 3. The name "DOM4J" must not be used to endorse or promote products derived
81   * from this Software without prior written permission of MetaStuff, Ltd. For
82   * written permission, please contact dom4j-info@metastuff.com.
83   * 
84   * 4. Products derived from this Software may not be called "DOM4J" nor may
85   * "DOM4J" appear in their names without prior written permission of MetaStuff,
86   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
87   * 
88   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
89   * 
90   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
91   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
92   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
93   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
94   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
95   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
96   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
97   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
98   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
99   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
100  * POSSIBILITY OF SUCH DAMAGE.
101  * 
102  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
103  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/AbstractTestCase.html0000644000175000017500000006425310242117766022646 0ustar ebourgebourg AbstractTestCase xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.framework.TestCase;
11  
12  import java.io.File;
13  
14  import org.apache.xalan.processor.TransformerFactoryImpl;
15  import org.apache.xerces.jaxp.SAXParserFactoryImpl;
16  
17  import org.dom4j.io.SAXReader;
18  import org.dom4j.util.NodeComparator;
19  
20  /***
21   * An abstract base class for some DOM4J test cases
22   * 
23   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
24   * @version $Revision: 1.24 $
25   */
26  public class AbstractTestCase extends TestCase {
27      protected Document document;
28  
29      protected AbstractTestCase() {
30          super();
31      }
32  
33      protected AbstractTestCase(String name) {
34          super(name);
35      }
36  
37      protected void log(String text) {
38          System.out.println(text);
39      }
40  
41      protected Document getDocument() {
42          return document;
43      }
44  
45      protected Document getDocument(String path) throws Exception {
46          return getDocument(path, new SAXReader());
47      }
48  
49      protected Document getDocument(String path, SAXReader reader)
50              throws Exception {
51          return reader.read(getFile(path));
52      }
53  
54      protected File getFile(String path) {
55          return new File(System.getProperty("user.dir"), path);
56      }
57  
58      public void assertDocumentsEqual(Document doc1, Document doc2)
59              throws Exception {
60          try {
61              assertTrue("Doc1 not null", doc1 != null);
62              assertTrue("Doc2 not null", doc2 != null);
63  
64              doc1.normalize();
65              doc2.normalize();
66  
67              assertNodesEqual(doc1, doc2);
68  
69              NodeComparator comparator = new NodeComparator();
70              assertTrue("Documents are equal",
71                      comparator.compare(doc1, doc2) == 0);
72          } catch (Exception e) {
73              log("Failed during comparison of: " + doc1 + " and: " + doc2);
74              throw e;
75          }
76      }
77  
78      public void assertNodesEqual(Document n1, Document n2) {
79          // assertEquals( "Document names", n1.getName(), n2.getName() );
80          assertNodesEqual(n1.getDocType(), n2.getDocType());
81          assertNodesEqualContent(n1, n2);
82      }
83  
84      public void assertNodesEqual(Element n1, Element n2) {
85          assertNodesEqual(n1.getQName(), n2.getQName());
86  
87          int c1 = n1.attributeCount();
88          int c2 = n2.attributeCount();
89  
90          assertEquals("Elements have same number of attributes (" + c1 + ", "
91                  + c2 + " for: " + n1 + " and " + n2, c1, c2);
92  
93          for (int i = 0; i < c1; i++) {
94              Attribute a1 = n1.attribute(i);
95              Attribute a2 = n2.attribute(a1.getQName());
96              assertNodesEqual(a1, a2);
97          }
98  
99          assertNodesEqualContent(n1, n2);
100     }
101 
102     public void assertNodesEqual(Attribute n1, Attribute n2) {
103         assertNodesEqual(n1.getQName(), n2.getQName());
104 
105         assertEquals("Attribute values for: " + n1 + " and " + n2, n1
106                 .getValue(), n2.getValue());
107     }
108 
109     public void assertNodesEqual(QName n1, QName n2) {
110         assertEquals("URIs equal for: " + n1.getQualifiedName() + " and "
111                 + n2.getQualifiedName(), n1.getNamespaceURI(), n2
112                 .getNamespaceURI());
113         assertEquals("qualified names equal", n1.getQualifiedName(), n2
114                 .getQualifiedName());
115     }
116 
117     public void assertNodesEqual(CharacterData t1, CharacterData t2) {
118         assertEquals("Text equal for: " + t1 + " and " + t2, t1.getText(), t2
119                 .getText());
120     }
121 
122     public void assertNodesEqual(DocumentType o1, DocumentType o2) {
123         if (o1 != o2) {
124             if (o1 == null) {
125                 assertTrue("Missing DocType: " + o2, false);
126             } else if (o2 == null) {
127                 assertTrue("Missing DocType: " + o1, false);
128             } else {
129                 assertEquals("DocType name equal", o1.getName(), o2.getName());
130                 assertEquals("DocType publicID equal", o1.getPublicID(), o2
131                         .getPublicID());
132                 assertEquals("DocType systemID equal", o1.getSystemID(), o2
133                         .getSystemID());
134             }
135         }
136     }
137 
138     public void assertNodesEqual(Entity o1, Entity o2) {
139         assertEquals("Entity names equal", o1.getName(), o2.getName());
140         assertEquals("Entity values equal", o1.getText(), o2.getText());
141     }
142 
143     public void assertNodesEqual(ProcessingInstruction n1,
144             ProcessingInstruction n2) {
145         assertEquals("PI targets equal", n1.getTarget(), n2.getTarget());
146         assertEquals("PI text equal", n1.getText(), n2.getText());
147     }
148 
149     public void assertNodesEqual(Namespace n1, Namespace n2) {
150         assertEquals("Namespace prefixes not equal", n1.getPrefix(), n2
151                 .getPrefix());
152         assertEquals("Namespace URIs not equal", n1.getURI(), n2.getURI());
153     }
154 
155     public void assertNodesEqualContent(Branch b1, Branch b2) {
156         int c1 = b1.nodeCount();
157         int c2 = b2.nodeCount();
158 
159         if (c1 != c2) {
160             log("Content of: " + b1);
161             log("is: " + b1.content());
162             log("Content of: " + b2);
163             log("is: " + b2.content());
164         }
165 
166         assertEquals("Branches have same number of children (" + c1 + ", " + c2
167                 + " for: " + b1 + " and " + b2, c1, c2);
168 
169         for (int i = 0; i < c1; i++) {
170             Node n1 = b1.node(i);
171             Node n2 = b2.node(i);
172             assertNodesEqual(n1, n2);
173         }
174     }
175 
176     public void assertNodesEqual(Node n1, Node n2) {
177         int nodeType1 = n1.getNodeType();
178         int nodeType2 = n2.getNodeType();
179         assertTrue("Nodes are of same type: ", nodeType1 == nodeType2);
180 
181         switch (nodeType1) {
182             case Node.ELEMENT_NODE:
183                 assertNodesEqual((Element) n1, (Element) n2);
184 
185                 break;
186 
187             case Node.DOCUMENT_NODE:
188                 assertNodesEqual((Document) n1, (Document) n2);
189 
190                 break;
191 
192             case Node.ATTRIBUTE_NODE:
193                 assertNodesEqual((Attribute) n1, (Attribute) n2);
194 
195                 break;
196 
197             case Node.TEXT_NODE:
198                 assertNodesEqual((Text) n1, (Text) n2);
199 
200                 break;
201 
202             case Node.CDATA_SECTION_NODE:
203                 assertNodesEqual((CDATA) n1, (CDATA) n2);
204 
205                 break;
206 
207             case Node.ENTITY_REFERENCE_NODE:
208                 assertNodesEqual((Entity) n1, (Entity) n2);
209 
210                 break;
211 
212             case Node.PROCESSING_INSTRUCTION_NODE:
213                 assertNodesEqual((ProcessingInstruction) n1,
214                         (ProcessingInstruction) n2);
215 
216                 break;
217 
218             case Node.COMMENT_NODE:
219                 assertNodesEqual((Comment) n1, (Comment) n2);
220 
221                 break;
222 
223             case Node.DOCUMENT_TYPE_NODE:
224                 assertNodesEqual((DocumentType) n1, (DocumentType) n2);
225 
226                 break;
227 
228             case Node.NAMESPACE_NODE:
229                 assertNodesEqual((Namespace) n1, (Namespace) n2);
230 
231                 break;
232 
233             default:
234                 assertTrue("Invalid node types. node1: " + n1 + " and node2: "
235                         + n2, false);
236         }
237     }
238 
239     // Implementation methods
240     // -------------------------------------------------------------------------
241     protected void setUp() throws Exception {
242         System.setProperty("javax.xml.parsers.SAXParserFactory",
243                 SAXParserFactoryImpl.class.getName());
244         System.setProperty("javax.xml.transform.TransformerFactory",
245                 TransformerFactoryImpl.class.getName());
246         document = DocumentHelper.createDocument();
247 
248         Element root = document.addElement("root");
249 
250         Element author1 = root.addElement("author").addAttribute("name",
251                 "James").addAttribute("location", "UK").addText(
252                 "James Strachan");
253 
254         Element url1 = author1.addElement("url");
255         url1.addText("http://sourceforge.net/users/jstrachan/");
256 
257         Element author2 = root.addElement("author").addAttribute("name", "Bob")
258                 .addAttribute("location", "Canada").addText("Bob McWhirter");
259 
260         Element url2 = author2.addElement("url");
261         url2.addText("http://sourceforge.net/users/werken/");
262     }
263 
264     /***
265      * DOCUMENT ME!
266      * 
267      * @return the root element of the document
268      */
269     protected Element getRootElement() {
270         Element root = document.getRootElement();
271         assertTrue("Document has root element", root != null);
272 
273         return root;
274     }
275 }
276 
277 /*
278  * Redistribution and use of this software and associated documentation
279  * ("Software"), with or without modification, are permitted provided that the
280  * following conditions are met:
281  * 
282  * 1. Redistributions of source code must retain copyright statements and
283  * notices. Redistributions must also contain a copy of this document.
284  * 
285  * 2. Redistributions in binary form must reproduce the above copyright notice,
286  * this list of conditions and the following disclaimer in the documentation
287  * and/or other materials provided with the distribution.
288  * 
289  * 3. The name "DOM4J" must not be used to endorse or promote products derived
290  * from this Software without prior written permission of MetaStuff, Ltd. For
291  * written permission, please contact dom4j-info@metastuff.com.
292  * 
293  * 4. Products derived from this Software may not be called "DOM4J" nor may
294  * "DOM4J" appear in their names without prior written permission of MetaStuff,
295  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
296  * 
297  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
298  * 
299  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
300  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
301  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
302  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
303  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
304  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
305  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
306  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
307  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
308  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
309  * POSSIBILITY OF SUCH DAMAGE.
310  * 
311  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
312  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/XPathBugTest.html0000644000175000017500000003615510242117746021767 0ustar ebourgebourg XPathBugTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.List;
13  
14  /***
15   * A test harness to test XPath expression evaluation in DOM4J
16   * 
17   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
18   * @version $Revision: 1.4 $
19   */
20  public class XPathBugTest extends AbstractTestCase {
21      public static void main(String[] args) {
22          TestRunner.run(XPathBugTest.class);
23      }
24  
25      // Test case(s)
26      // -------------------------------------------------------------------------
27      public void testXPaths() throws Exception {
28          Document document = getDocument("/xml/rabo1ae.xml");
29          Element root = (Element) document
30                  .selectSingleNode("/m:Msg/m:Contents/m:Content");
31  
32          assertTrue("root is not null", root != null);
33  
34          Namespace ns = root.getNamespaceForPrefix("ab");
35  
36          assertTrue("Found namespace", ns != null);
37  
38          System.out.println("Found: " + ns.getURI());
39  
40          Element element = (Element) root
41                  .selectSingleNode("ab:RaboPayLoad[@id='1234123']");
42  
43          assertTrue("element is not null", element != null);
44  
45          String value = element.valueOf("ab:AccountingEntry/ab:RateType");
46  
47          assertEquals("RateType is correct", "CRRNT", value);
48      }
49  
50      /***
51       * A bug found by Rob Lebowitz
52       * 
53       * @throws Exception
54       *             DOCUMENT ME!
55       */
56      public void testRobLebowitz() throws Exception {
57          String text = "<ul>" + "    <ul>" + "        <li/>"
58                  + "            <ul>" + "                <li/>"
59                  + "            </ul>" + "        <li/>" + "    </ul>" + "</ul>";
60  
61          Document document = DocumentHelper.parseText(text);
62          List lists = document.selectNodes("//ul | //ol");
63  
64          int count = 0;
65  
66          for (int i = 0; i < lists.size(); i++) {
67              Element list = (Element) lists.get(i);
68              List nodes = list.selectNodes("ancestor::ul");
69  
70              if ((nodes != null) && (nodes.size() > 0)) {
71                  continue;
72              }
73  
74              nodes = list.selectNodes("ancestor::ol");
75  
76              if ((nodes != null) && (nodes.size() > 0)) {
77                  continue;
78              }
79          }
80      }
81  
82      /***
83       * A bug found by Stefan which results in IndexOutOfBoundsException for
84       * empty results
85       * 
86       * @throws Exception
87       *             DOCUMENT ME!
88       */
89      public void testStefan() throws Exception {
90          String text = "<foo>hello</foo>";
91          Document document = DocumentHelper.parseText(text);
92          XPath xpath = DocumentHelper.createXPath("/x");
93          Object value = xpath.evaluate(document);
94      }
95  
96      /***
97       * Test found by Mike Skells
98       * 
99       * @throws Exception
100      *             DOCUMENT ME!
101      */
102     public void testMikeSkells() throws Exception {
103         Document top = DocumentFactory.getInstance().createDocument();
104         Element root = top.addElement("root");
105         root.addElement("child1").addElement("child11");
106         root.addElement("child2").addElement("child21");
107         System.out.println(top.asXML());
108 
109         XPath test1 = top.createXPath("/root/child1/child11");
110         XPath test2 = top.createXPath("/root/child2/child21");
111         Node position1 = test1.selectSingleNode(root);
112         Node position2 = test2.selectSingleNode(root);
113 
114         System.out.println("test1= " + test1);
115         System.out.println("test2= " + test2);
116         System.out.println("Position1 Xpath = " + position1.getUniquePath());
117         System.out.println("Position2 Xpath = " + position2.getUniquePath());
118 
119         System.out.println("test2.matches(position1) : "
120                 + test2.matches(position1));
121 
122         assertTrue("test1.matches(position1)", test1.matches(position1));
123         assertTrue("test2.matches(position2)", test2.matches(position2));
124 
125         assertTrue("test2.matches(position1) should be false", !test2
126                 .matches(position1));
127     }
128 }
129 
130 /*
131  * Redistribution and use of this software and associated documentation
132  * ("Software"), with or without modification, are permitted provided that the
133  * following conditions are met:
134  * 
135  * 1. Redistributions of source code must retain copyright statements and
136  * notices. Redistributions must also contain a copy of this document.
137  * 
138  * 2. Redistributions in binary form must reproduce the above copyright notice,
139  * this list of conditions and the following disclaimer in the documentation
140  * and/or other materials provided with the distribution.
141  * 
142  * 3. The name "DOM4J" must not be used to endorse or promote products derived
143  * from this Software without prior written permission of MetaStuff, Ltd. For
144  * written permission, please contact dom4j-info@metastuff.com.
145  * 
146  * 4. Products derived from this Software may not be called "DOM4J" nor may
147  * "DOM4J" appear in their names without prior written permission of MetaStuff,
148  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
149  * 
150  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
151  * 
152  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
153  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
154  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
155  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
156  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
157  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
158  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
159  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
160  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
161  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
162  * POSSIBILITY OF SUCH DAMAGE.
163  * 
164  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
165  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/NamespaceTest.html0000644000175000017500000003701010242117724022164 0ustar ebourgebourg NamespaceTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.HashMap;
13  import java.util.Iterator;
14  import java.util.List;
15  import java.util.Map;
16  
17  import org.dom4j.io.SAXReader;
18  
19  /***
20   * A test harness to test the use of Namespaces.
21   * 
22   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
23   * @version $Revision: 1.4 $
24   */
25  public class NamespaceTest extends AbstractTestCase {
26      /*** Input XML file to read */
27      private static final String INPUT_XML_FILE = "/xml/namespaces.xml";
28  
29      /*** Namespace to use in tests */
30      private static final Namespace XSL_NAMESPACE = Namespace.get("xsl",
31              "http://www.w3.org/1999/XSL/Transform");
32  
33      private static final QName XSL_TEMPLATE = QName.get("template",
34              XSL_NAMESPACE);
35  
36      public static void main(String[] args) {
37          TestRunner.run(NamespaceTest.class);
38      }
39  
40      // Test case(s)
41      // -------------------------------------------------------------------------
42      public void debugShowNamespaces() throws Exception {
43          Element root = getRootElement();
44  
45          for (Iterator iter = root.elementIterator(); iter.hasNext();) {
46              Element element = (Element) iter.next();
47  
48              log("Found element:    " + element);
49              log("Namespace:        " + element.getNamespace());
50              log("Namespace prefix: " + element.getNamespacePrefix());
51              log("Namespace URI:    " + element.getNamespaceURI());
52          }
53      }
54  
55      public void testGetElement() throws Exception {
56          Element root = getRootElement();
57  
58          Element firstTemplate = root.element(XSL_TEMPLATE);
59          assertTrue(
60                  "Root element contains at least one <xsl:template/> element",
61                  firstTemplate != null);
62  
63          log("Found element: " + firstTemplate);
64      }
65  
66      public void testGetElements() throws Exception {
67          Element root = getRootElement();
68  
69          List list = root.elements(XSL_TEMPLATE);
70          assertTrue(
71                  "Root element contains at least one <xsl:template/> element",
72                  list.size() > 0);
73  
74          log("Found elements: " + list);
75      }
76  
77      public void testElementIterator() throws Exception {
78          Element root = getRootElement();
79          Iterator iter = root.elementIterator(XSL_TEMPLATE);
80          assertTrue(
81                  "Root element contains at least one <xsl:template/> element",
82                  iter.hasNext());
83  
84          do {
85              Element element = (Element) iter.next();
86              log("Found element: " + element);
87          } while (iter.hasNext());
88      }
89  
90      /***
91       * Tests the use of namespace URI Mapping associated with a DocumentFactory
92       * 
93       * @throws Exception
94       *             DOCUMENT ME!
95       */
96      public void testNamespaceUriMap() throws Exception {
97          // register namespace prefix->uri mappings with factory
98          Map uris = new HashMap();
99          uris.put("x", "fooNamespace");
100         uris.put("y", "barNamespace");
101 
102         DocumentFactory factory = new DocumentFactory();
103         factory.setXPathNamespaceURIs(uris);
104 
105         // parse or create a document
106         SAXReader reader = new SAXReader();
107         reader.setDocumentFactory(factory);
108 
109         Document doc = getDocument("/xml/test/nestedNamespaces.xml", reader);
110 
111         // evaluate XPath using registered namespace prefixes
112         // which do not appear in the document (though the URIs do!)
113         String value = doc.valueOf("/x:pizza/y:cheese/x:pepper");
114 
115         log("Found value: " + value);
116 
117         assertEquals("XPath used default namesapce URIS", "works", value);
118     }
119 
120     // Implementation methods
121     // -------------------------------------------------------------------------
122     protected void setUp() throws Exception {
123         super.setUp();
124         document = getDocument(INPUT_XML_FILE);
125     }
126 
127     /***
128      * DOCUMENT ME!
129      * 
130      * @return the root element of the document
131      */
132     protected Element getRootElement() {
133         Element root = document.getRootElement();
134         assertTrue("Document has root element", root != null);
135 
136         return root;
137     }
138 }
139 
140 /*
141  * Redistribution and use of this software and associated documentation
142  * ("Software"), with or without modification, are permitted provided that the
143  * following conditions are met:
144  * 
145  * 1. Redistributions of source code must retain copyright statements and
146  * notices. Redistributions must also contain a copy of this document.
147  * 
148  * 2. Redistributions in binary form must reproduce the above copyright notice,
149  * this list of conditions and the following disclaimer in the documentation
150  * and/or other materials provided with the distribution.
151  * 
152  * 3. The name "DOM4J" must not be used to endorse or promote products derived
153  * from this Software without prior written permission of MetaStuff, Ltd. For
154  * written permission, please contact dom4j-info@metastuff.com.
155  * 
156  * 4. Products derived from this Software may not be called "DOM4J" nor may
157  * "DOM4J" appear in their names without prior written permission of MetaStuff,
158  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
159  * 
160  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
161  * 
162  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
163  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
164  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
165  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
166  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
167  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
168  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
169  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
170  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
171  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
172  * POSSIBILITY OF SUCH DAMAGE.
173  * 
174  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
175  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/HTMLWriterTest.html0000644000175000017500000003763110242117553022242 0ustar ebourgebourg HTMLWriterTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.StringWriter;
13  
14  import org.dom4j.io.HTMLWriter;
15  import org.dom4j.io.OutputFormat;
16  
17  /***
18   * Test harness for the HTMLWriter
19   * 
20   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
21   * @version $Revision: 1.4 $
22   */
23  public class HTMLWriterTest extends AbstractTestCase {
24      public static void main(String[] args) {
25          TestRunner.run(HTMLWriterTest.class);
26      }
27  
28      // Test case(s)
29      // -------------------------------------------------------------------------
30      public void testWriter() throws Exception {
31          String xml = "<html> <body><![CDATA[First&nbsp;test]]></body> </html>";
32          Document document = DocumentHelper.parseText(xml);
33          StringWriter buffer = new StringWriter();
34          HTMLWriter writer = new HTMLWriter(buffer);
35          writer.write(document);
36  
37          String output = buffer.toString();
38  
39          String expects = "\n<html>\n  <body>First&nbsp;test</body>\n</html>\n";
40  
41          System.out.println("expects: " + expects);
42          System.out.println("output: " + output);
43  
44          assertEquals("Output is correct", expects, output);
45      }
46  
47      public void testBug923882() throws Exception {
48          Document doc = DocumentFactory.getInstance().createDocument();
49          Element root = doc.addElement("root");
50          root.addText("this is ");
51          root.addText(" sim");
52          root.addText("ple text ");
53          root.addElement("child");
54          root.addText(" contai");
55          root.addText("ning spaces and");
56          root.addText(" multiple textnodes");
57  
58          OutputFormat format = new OutputFormat();
59          format.setEncoding("UTF-8");
60          format.setIndentSize(4);
61          format.setNewlines(true);
62          format.setTrimText(true);
63          format.setExpandEmptyElements(true);
64  
65          StringWriter buffer = new StringWriter();
66          HTMLWriter writer = new HTMLWriter(buffer, format);
67          writer.write(doc);
68  
69          String xml = buffer.toString();
70          log(xml);
71  
72          int start = xml.indexOf("<root");
73          int end = xml.indexOf("/root>") + 6;
74          String eol = "\n"; // System.getProperty("line.separator");
75          String expected = "<root>this is simple text" + eol
76                  + "    <child></child>containing spaces and multiple textnodes"
77                  + eol + "</root>";
78          System.out.println("Expected:");
79          System.out.println(expected);
80          System.out.println("Obtained:");
81          System.out.println(xml.substring(start, end));
82          assertEquals(expected, xml.substring(start, end));
83      }
84  
85      public void testBug923882asWriter() throws Exception {
86          // use an the HTMLWriter sax-methods.
87          //
88          StringWriter buffer = new StringWriter();
89          HTMLWriter writer = new HTMLWriter(buffer, OutputFormat
90                  .createPrettyPrint());
91          writer.characters("wor".toCharArray(), 0, 3);
92          writer.characters("d-being-cut".toCharArray(), 0, 11);
93  
94          String expected = "word-being-cut";
95          assertEquals(expected, buffer.toString());
96  
97          buffer = new StringWriter();
98          writer = new HTMLWriter(buffer, OutputFormat.createPrettyPrint());
99          writer.characters("    wor".toCharArray(), 0, 7);
100         writer.characters("d being    ".toCharArray(), 0, 11);
101         writer.characters("  cut".toCharArray(), 0, 5);
102 
103         expected = "word being cut";
104         assertEquals(expected, buffer.toString());
105     }
106 
107     public void testBug923882asWriterWithEmptyCharArray() throws Exception {
108         // use an the HTMLWriter sax-methods.
109         //
110         StringWriter buffer = new StringWriter();
111         HTMLWriter writer = new HTMLWriter(buffer, OutputFormat
112                 .createPrettyPrint());
113         writer.characters("wor".toCharArray(), 0, 3);
114         writer.characters(new char[0], 0, 0);
115         writer.characters("d-being-cut".toCharArray(), 0, 11);
116 
117         String expected = "word-being-cut";
118         assertEquals(expected, buffer.toString());
119     }
120 
121     public void testBug619415() throws Exception {
122         Document doc = getDocument("/xml/test/dosLineFeeds.xml");
123 
124         StringWriter wr = new StringWriter();
125         HTMLWriter writer = new HTMLWriter(wr, new OutputFormat("", false));
126         writer.write(doc);
127 
128         String result = wr.toString();
129         System.out.println(result);
130 
131         assertTrue(result.indexOf("Mary had a little lamb.") > -1);
132         assertTrue(result.indexOf("Hello, this is a test.") > -1);
133     }
134 }
135 
136 /*
137  * Redistribution and use of this software and associated documentation
138  * ("Software"), with or without modification, are permitted provided that the
139  * following conditions are met:
140  * 
141  * 1. Redistributions of source code must retain copyright statements and
142  * notices. Redistributions must also contain a copy of this document.
143  * 
144  * 2. Redistributions in binary form must reproduce the above copyright notice,
145  * this list of conditions and the following disclaimer in the documentation
146  * and/or other materials provided with the distribution.
147  * 
148  * 3. The name "DOM4J" must not be used to endorse or promote products derived
149  * from this Software without prior written permission of MetaStuff, Ltd. For
150  * written permission, please contact dom4j-info@metastuff.com.
151  * 
152  * 4. Products derived from this Software may not be called "DOM4J" nor may
153  * "DOM4J" appear in their names without prior written permission of MetaStuff,
154  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
155  * 
156  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
157  * 
158  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
159  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
160  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
161  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
162  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
163  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
164  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
165  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
166  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
167  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
168  * POSSIBILITY OF SUCH DAMAGE.
169  * 
170  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
171  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/AttributeDetachTest.html0000644000175000017500000002242210242117573023347 0ustar ebourgebourg AttributeDetachTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.Iterator;
13  import java.util.List;
14  
15  /***
16   * A test harness to test the detach() method on attributes
17   * 
18   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
19   * @version $Revision: 1.3 $
20   */
21  public class AttributeDetachTest extends AbstractTestCase {
22      public static void main(String[] args) {
23          TestRunner.run(AttributeDetachTest.class);
24      }
25  
26      // Test case(s)
27      // -------------------------------------------------------------------------
28      public void testDetachAttribute() throws Exception {
29          List attributes = document.selectNodes("//@name");
30  
31          assertTrue("Found more than one attribute: ", attributes.size() > 0);
32  
33          for (Iterator iter = attributes.iterator(); iter.hasNext();) {
34              Attribute attribute = (Attribute) iter.next();
35              Element element = attribute.getParent();
36  
37              assertTrue("Attribute: " + attribute + " has parent: " + element,
38                      attribute.getParent() == element);
39  
40              QName qname = attribute.getQName();
41  
42              Attribute attribute2 = element.attribute(qname);
43  
44              String value = attribute.getValue();
45              String value2 = element.attributeValue(qname);
46  
47              assertEquals("Attribute and Element have same attrbute value",
48                      value, value2);
49  
50              attribute.detach();
51  
52              attribute2 = element.attribute(qname);
53              value2 = element.attributeValue(qname);
54  
55              assertTrue("Element now has no value: " + value2, value2 == null);
56              assertTrue("Element now has no attribute: " + attribute2,
57                      attribute2 == null);
58          }
59      }
60  }
61  
62  /*
63   * Redistribution and use of this software and associated documentation
64   * ("Software"), with or without modification, are permitted provided that the
65   * following conditions are met:
66   * 
67   * 1. Redistributions of source code must retain copyright statements and
68   * notices. Redistributions must also contain a copy of this document.
69   * 
70   * 2. Redistributions in binary form must reproduce the above copyright notice,
71   * this list of conditions and the following disclaimer in the documentation
72   * and/or other materials provided with the distribution.
73   * 
74   * 3. The name "DOM4J" must not be used to endorse or promote products derived
75   * from this Software without prior written permission of MetaStuff, Ltd. For
76   * written permission, please contact dom4j-info@metastuff.com.
77   * 
78   * 4. Products derived from this Software may not be called "DOM4J" nor may
79   * "DOM4J" appear in their names without prior written permission of MetaStuff,
80   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
81   * 
82   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
83   * 
84   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
85   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
86   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
87   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
88   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
89   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
90   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
91   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
92   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
93   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
94   * POSSIBILITY OF SUCH DAMAGE.
95   * 
96   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
97   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/RoundTripTest.html0000644000175000017500000004632710242117550022226 0ustar ebourgebourg RoundTripTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.StringReader;
13  import java.io.StringWriter;
14  
15  import javax.xml.transform.Transformer;
16  import javax.xml.transform.TransformerFactory;
17  import javax.xml.transform.stream.StreamResult;
18  import javax.xml.transform.stream.StreamSource;
19  
20  import org.dom4j.io.DOMReader;
21  import org.dom4j.io.DOMWriter;
22  import org.dom4j.io.DocumentResult;
23  import org.dom4j.io.DocumentSource;
24  import org.dom4j.io.SAXContentHandler;
25  import org.dom4j.io.SAXReader;
26  import org.dom4j.io.SAXWriter;
27  import org.dom4j.io.XMLWriter;
28  
29  /***
30   * A test harness to test the the round trips of Documents.
31   * 
32   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
33   * @version $Revision: 1.4 $
34   */
35  public class RoundTripTest extends AbstractTestCase {
36      protected String[] testDocuments = {"/xml/test/encode.xml",
37              "/xml/fibo.xml", "/xml/test/schema/personal-prefix.xsd",
38              "/xml/test/soap2.xml", "/xml/test/test_schema.xml"};
39  
40      public static void main(String[] args) {
41          TestRunner.run(RoundTripTest.class);
42      }
43  
44      // Test case(s)
45      // -------------------------------------------------------------------------
46      public void testTextRoundTrip() throws Exception {
47          for (int i = 0, size = testDocuments.length; i < size; i++) {
48              Document doc = getDocument(testDocuments[i]);
49              roundTripText(doc);
50          }
51      }
52  
53      public void testSAXRoundTrip() throws Exception {
54          for (int i = 0, size = testDocuments.length; i < size; i++) {
55              Document doc = getDocument(testDocuments[i]);
56              roundTripSAX(doc);
57          }
58      }
59  
60      public void testDOMRoundTrip() throws Exception {
61          for (int i = 0, size = testDocuments.length; i < size; i++) {
62              Document doc = getDocument(testDocuments[i]);
63              roundTripDOM(doc);
64          }
65      }
66  
67      public void testJAXPRoundTrip() throws Exception {
68          for (int i = 0, size = testDocuments.length; i < size; i++) {
69              Document doc = getDocument(testDocuments[i]);
70              roundTripJAXP(doc);
71          }
72      }
73  
74      public void testFullRoundTrip() throws Exception {
75          for (int i = 0, size = testDocuments.length; i < size; i++) {
76              Document doc = getDocument(testDocuments[i]);
77              roundTripFull(doc);
78          }
79      }
80  
81      public void testRoundTrip() throws Exception {
82          Document document = getDocument("/xml/xmlspec.xml");
83  
84          // Document doc1 = roundTripText( document );
85          Document doc1 = roundTripSAX(document);
86          Document doc2 = roundTripDOM(doc1);
87          Document doc3 = roundTripSAX(doc2);
88          Document doc4 = roundTripText(doc3);
89          Document doc5 = roundTripDOM(doc4);
90  
91          // Document doc5 = roundTripDOM( doc3 );
92          assertDocumentsEqual(document, doc5);
93      }
94  
95      // Implementation methods
96      // -------------------------------------------------------------------------
97      protected Document roundTripDOM(Document document) throws Exception {
98          // now lets make a DOM object
99          DOMWriter domWriter = new DOMWriter();
100         org.w3c.dom.Document domDocument = domWriter.write(document);
101 
102         // now lets read it back as a DOM4J object
103         DOMReader domReader = new DOMReader();
104         Document newDocument = domReader.read(domDocument);
105 
106         // lets ensure names are same
107         newDocument.setName(document.getName());
108 
109         assertDocumentsEqual(document, newDocument);
110 
111         return newDocument;
112     }
113 
114     protected Document roundTripJAXP(Document document) throws Exception {
115         // output the document to a text buffer via JAXP
116         TransformerFactory factory = TransformerFactory.newInstance();
117         Transformer transformer = factory.newTransformer();
118 
119         StringWriter buffer = new StringWriter();
120         StreamResult streamResult = new StreamResult(buffer);
121         DocumentSource documentSource = new DocumentSource(document);
122 
123         transformer.transform(documentSource, streamResult);
124 
125         // now lets parse it back again via JAXP
126         DocumentResult documentResult = new DocumentResult();
127         StreamSource streamSource = new StreamSource(new StringReader(buffer
128                 .toString()));
129 
130         transformer.transform(streamSource, documentResult);
131 
132         Document newDocument = documentResult.getDocument();
133 
134         // lets ensure names are same
135         newDocument.setName(document.getName());
136 
137         assertDocumentsEqual(document, newDocument);
138 
139         return newDocument;
140     }
141 
142     protected Document roundTripSAX(Document document) throws Exception {
143         // now lets write it back as SAX events to
144         // a SAX ContentHandler which should build up a new document
145         SAXContentHandler contentHandler = new SAXContentHandler();
146         SAXWriter saxWriter = new SAXWriter(contentHandler, contentHandler,
147                 contentHandler);
148 
149         saxWriter.write(document);
150 
151         Document newDocument = contentHandler.getDocument();
152 
153         // lets ensure names are same
154         newDocument.setName(document.getName());
155 
156         assertDocumentsEqual(document, newDocument);
157 
158         return newDocument;
159     }
160 
161     protected Document roundTripText(Document document) throws Exception {
162         StringWriter out = new StringWriter();
163         XMLWriter xmlWriter = new XMLWriter(out);
164 
165         xmlWriter.write(document);
166 
167         // now lets read it back
168         String xml = out.toString();
169 
170         StringReader in = new StringReader(xml);
171         SAXReader reader = new SAXReader();
172         Document newDocument = reader.read(in);
173 
174         // lets ensure names are same
175         newDocument.setName(document.getName());
176 
177         assertDocumentsEqual(document, newDocument);
178 
179         return newDocument;
180     }
181 
182     protected Document roundTripFull(Document document) throws Exception {
183         Document doc2 = roundTripDOM(document);
184         Document doc3 = roundTripSAX(doc2);
185         Document doc4 = roundTripText(doc3);
186 
187         assertDocumentsEqual(document, doc4);
188 
189         return doc4;
190     }
191 }
192 
193 /*
194  * Redistribution and use of this software and associated documentation
195  * ("Software"), with or without modification, are permitted provided that the
196  * following conditions are met:
197  * 
198  * 1. Redistributions of source code must retain copyright statements and
199  * notices. Redistributions must also contain a copy of this document.
200  * 
201  * 2. Redistributions in binary form must reproduce the above copyright notice,
202  * this list of conditions and the following disclaimer in the documentation
203  * and/or other materials provided with the distribution.
204  * 
205  * 3. The name "DOM4J" must not be used to endorse or promote products derived
206  * from this Software without prior written permission of MetaStuff, Ltd. For
207  * written permission, please contact dom4j-info@metastuff.com.
208  * 
209  * 4. Products derived from this Software may not be called "DOM4J" nor may
210  * "DOM4J" appear in their names without prior written permission of MetaStuff,
211  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
212  * 
213  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
214  * 
215  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
216  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
217  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
218  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
219  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
220  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
221  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
222  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
223  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
224  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
225  * POSSIBILITY OF SUCH DAMAGE.
226  * 
227  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
228  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/SetContentTest.html0000644000175000017500000003173510242117736022371 0ustar ebourgebourg SetContentTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  /***
13   * Tests the setContent method
14   * 
15   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
16   * @version $Revision: 1.3 $
17   */
18  public class SetContentTest extends AbstractTestCase {
19      public static void main(String[] args) {
20          TestRunner.run(SetContentTest.class);
21      }
22  
23      // Test case(s)
24      // -------------------------------------------------------------------------
25      public void testDocument() throws Exception {
26          document.setName("doc1");
27  
28          Element oldRoot = document.getRootElement();
29  
30          assertTrue("Current root has document",
31                  oldRoot.getDocument() == document);
32  
33          Document doc2 = DocumentHelper.createDocument();
34          doc2.setName("doc2");
35  
36          assertTrue("Doc2 has no root element", doc2.getRootElement() == null);
37  
38          doc2.setContent(document.content());
39  
40          Element newRoot = doc2.getRootElement();
41  
42          assertTrue("Current root has document",
43                  oldRoot.getDocument() == document);
44  
45          assertTrue("Doc2 has now has root element", newRoot != null);
46          assertTrue("Doc2 has different root element", newRoot != oldRoot);
47          assertTrue("Root element now has document",
48                  newRoot.getDocument() == doc2);
49  
50          testParent(doc2.getRootElement());
51          testDocument(doc2, doc2);
52  
53          doc2.clearContent();
54  
55          assertTrue("New Doc has no root", doc2.getRootElement() == null);
56          assertTrue("New root has no document", newRoot.getDocument() == null);
57      }
58  
59      public void testRootElement() throws Exception {
60          Document doc3 = DocumentHelper.createDocument();
61          doc3.setName("doc3");
62  
63          Element root = doc3.addElement("root");
64          Element oldElement = root.addElement("old");
65  
66          assertTrue("Doc3 has root element", root != null);
67  
68          root.setContent(document.getRootElement().content());
69  
70          assertTrue("Doc3's root now has content", root.nodeCount() > 0);
71          assertTrue("Old element has no parent now",
72                  oldElement.getParent() == null);
73          assertTrue("Old element has no document now",
74                  oldElement.getDocument() == null);
75  
76          testParent(root);
77          testDocument(root, doc3);
78      }
79  
80      /***
81       * Tests all the children of the branch have the correct parent
82       * 
83       * @param parent
84       *            DOCUMENT ME!
85       */
86      protected void testParent(Branch parent) {
87          for (int i = 0, size = parent.nodeCount(); i < size; i++) {
88              Node node = parent.node(i);
89              assertTrue("Child node of root has parent of root", node
90                      .getParent() == parent);
91          }
92      }
93  
94      /***
95       * Tests all the children of the branch have the correct document
96       * 
97       * @param branch
98       *            DOCUMENT ME!
99       * @param doc
100      *            DOCUMENT ME!
101      */
102     protected void testDocument(Branch branch, Document doc) {
103         for (int i = 0, size = branch.nodeCount(); i < size; i++) {
104             Node node = branch.node(i);
105             assertTrue("Node has correct document", node.getDocument() == doc);
106         }
107     }
108 }
109 
110 /*
111  * Redistribution and use of this software and associated documentation
112  * ("Software"), with or without modification, are permitted provided that the
113  * following conditions are met:
114  * 
115  * 1. Redistributions of source code must retain copyright statements and
116  * notices. Redistributions must also contain a copy of this document.
117  * 
118  * 2. Redistributions in binary form must reproduce the above copyright notice,
119  * this list of conditions and the following disclaimer in the documentation
120  * and/or other materials provided with the distribution.
121  * 
122  * 3. The name "DOM4J" must not be used to endorse or promote products derived
123  * from this Software without prior written permission of MetaStuff, Ltd. For
124  * written permission, please contact dom4j-info@metastuff.com.
125  * 
126  * 4. Products derived from this Software may not be called "DOM4J" nor may
127  * "DOM4J" appear in their names without prior written permission of MetaStuff,
128  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
129  * 
130  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
131  * 
132  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
133  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
134  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
135  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
136  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
137  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
138  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
139  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
140  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
141  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
142  * POSSIBILITY OF SUCH DAMAGE.
143  * 
144  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
145  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/util/0000755000175000017500000000000012133227266017522 5ustar ebourgebourgdom4j-1.6.1/docs/xref-test/org/dom4j/util/package-summary.html0000644000175000017500000000426210242117710023471 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.util

Class Summary
PerThreadSingletonTest
SimpleSingletonTest
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref-test/org/dom4j/util/PerThreadSingletonTest.html0000644000175000017500000003365610242117737025026 0ustar ebourgebourg PerThreadSingletonTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.util;
9   
10  import junit.framework.Test;
11  import junit.framework.TestSuite;
12  import junit.framework.TestCase;
13  import junit.extensions.RepeatedTest;
14  
15  import java.util.HashMap;
16  import java.util.Map;
17  
18  import com.clarkware.junitperf.LoadTest;
19  import com.clarkware.junitperf.TimedTest;
20  
21  /***
22   * PerThreadSingleton Tester.
23   * 
24   * @author ddlucas
25   * @since
26   * 
27   * <pre>
28   * 01 / 05 / 2005
29   * </pre>
30   * 
31   * @version 1.0
32   */
33  public class PerThreadSingletonTest extends TestCase {
34      public PerThreadSingletonTest(String name) {
35          super(name);
36      }
37  
38      private static SingletonStrategy singleton;
39  
40      private static ThreadLocal reference = new ThreadLocal();
41  
42      public void setUp() throws Exception {
43          super.setUp();
44          synchronized (PerThreadSingletonTest.class) {
45              if (singleton == null) {
46                  singleton = new PerThreadSingleton();
47                  singleton.setSingletonClassName(HashMap.class.getName());
48              }
49          }
50      }
51  
52      public void tearDown() throws Exception {
53          super.tearDown();
54      }
55  
56      public void testInstance() throws Exception {
57          String tid = Thread.currentThread().getName();
58          Map map = (Map) singleton.instance();
59  
60          String expected = "new value";
61          if (!map.containsKey(tid) && reference.get() != null) {
62              System.out.println("tid=" + tid + " map=" + map);
63              System.out.println("reference=" + reference);
64              System.out.println("singleton=" + singleton);
65              fail("created singleton more than once");
66          } else {
67              map.put(tid, expected);
68              reference.set(map);
69          }
70  
71          String actual = (String) map.get(tid);
72          // System.out.println("tid="+tid+ " map="+map);
73          assertEquals("testInstance", expected, actual);
74  
75          map = (Map) singleton.instance();
76          expected = "new value";
77          actual = (String) map.get(tid);
78          // System.out.println("tid="+tid+ " map="+map);
79          // System.out.println("reference="+reference);
80          // System.out.println("singleton="+singleton);
81          assertEquals("testInstance", expected, actual);
82          assertEquals("testInstance reference", reference.get(), map);
83  
84      }
85  
86      /***
87       * Assembles and returns a test suite.
88       * 
89       * @return The suite
90       */
91      public static Test suite() {
92          TestSuite suite = new TestSuite();
93          suite.addTest(makeRepeatedLoadTest(5, 100, "testInstance"));
94          return suite;
95      }
96  
97      /***
98       * JUnit method to exercise test via threads and loops
99       * 
100      * @param users
101      *            Number of users to simulate (i.e. Threads).
102      * @param iterations
103      *            Number of iterations per user ( repeat the test x times).
104      * @param testMethod
105      *            method to execute (testXXX).
106      * 
107      * @return A Junit test
108      */
109     protected static Test makeRepeatedLoadTest(int users, int iterations,
110             String testMethod) {
111         long maxElapsedTime = 1200 + (1000 * users * iterations);
112 
113         Test testCase = new PerThreadSingletonTest(testMethod);
114 
115         Test repeatedTest = new RepeatedTest(testCase, iterations);
116         Test loadTest = new LoadTest(repeatedTest, users);
117         Test timedTest = new TimedTest(loadTest, maxElapsedTime);
118 
119         return timedTest;
120     }
121 }
122 
123 /*
124  * Redistribution and use of this software and associated documentation
125  * ("Software"), with or without modification, are permitted provided that the
126  * following conditions are met:
127  * 
128  * 1. Redistributions of source code must retain copyright statements and
129  * notices. Redistributions must also contain a copy of this document.
130  * 
131  * 2. Redistributions in binary form must reproduce the above copyright notice,
132  * this list of conditions and the following disclaimer in the documentation
133  * and/or other materials provided with the distribution.
134  * 
135  * 3. The name "DOM4J" must not be used to endorse or promote products derived
136  * from this Software without prior written permission of MetaStuff, Ltd. For
137  * written permission, please contact dom4j-info@metastuff.com.
138  * 
139  * 4. Products derived from this Software may not be called "DOM4J" nor may
140  * "DOM4J" appear in their names without prior written permission of MetaStuff,
141  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
142  * 
143  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
144  * 
145  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
146  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
147  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
148  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
149  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
150  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
151  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
152  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
153  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
154  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
155  * POSSIBILITY OF SUCH DAMAGE.
156  * 
157  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
158  */
159 

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/util/package-frame.html0000644000175000017500000000152310242117732023067 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.util

org.dom4j.util

Classes

  • PerThreadSingletonTest
  • SimpleSingletonTest
dom4j-1.6.1/docs/xref-test/org/dom4j/util/SimpleSingletonTest.html0000644000175000017500000002525610242117703024367 0ustar ebourgebourg SimpleSingletonTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.util;
9   
10  import junit.framework.Test;
11  import junit.framework.TestSuite;
12  import junit.framework.TestCase;
13  
14  import java.util.HashMap;
15  import java.util.Map;
16  
17  /***
18   * PerThreadSingleton Tester.
19   * 
20   * @author ddlucas
21   * @since
22   * 
23   * <pre>
24   * 01 / 05 / 2005
25   * </pre>
26   * 
27   * @version 1.0
28   */
29  public class SimpleSingletonTest extends TestCase {
30      public SimpleSingletonTest(String name) {
31          super(name);
32      }
33  
34      private static SingletonStrategy singleton;
35  
36      private static Object reference;
37  
38      public void setUp() throws Exception {
39          super.setUp();
40          if (singleton == null) {
41              singleton = new PerThreadSingleton();
42              singleton.setSingletonClassName(HashMap.class.getName());
43          }
44      }
45  
46      public void tearDown() throws Exception {
47          super.tearDown();
48      }
49  
50      public void testFirstInstance() throws Exception {
51          Map map = (Map) singleton.instance();
52          String expected = null;
53          String actual = (String) map.get("Test");
54          assertEquals("testInstance", expected, actual);
55  
56          expected = "new value";
57          map.put("Test", expected);
58  
59          map = (Map) singleton.instance();
60          reference = map;
61          actual = (String) map.get("Test");
62          assertEquals("testFirstInstance", expected, actual);
63      }
64  
65      public void testSecondInstance() throws Exception {
66          Map map = (Map) singleton.instance();
67          assertEquals("testSecondInstance reference", reference, map);
68          String actual = (String) map.get("Test");
69          String expected = "new value";
70          assertEquals("testInstance", expected, actual);
71      }
72  
73      public static Test suite() {
74          TestSuite suite = new TestSuite();
75          suite.addTest(TestSuite.createTest(SimpleSingletonTest.class,
76                  "testFirstInstance"));
77          suite.addTest(TestSuite.createTest(SimpleSingletonTest.class,
78                  "testSecondInstance"));
79          return suite;
80      }
81  }
82  
83  /*
84   * Redistribution and use of this software and associated documentation
85   * ("Software"), with or without modification, are permitted provided that the
86   * following conditions are met:
87   * 
88   * 1. Redistributions of source code must retain copyright statements and
89   * notices. Redistributions must also contain a copy of this document.
90   * 
91   * 2. Redistributions in binary form must reproduce the above copyright notice,
92   * this list of conditions and the following disclaimer in the documentation
93   * and/or other materials provided with the distribution.
94   * 
95   * 3. The name "DOM4J" must not be used to endorse or promote products derived
96   * from this Software without prior written permission of MetaStuff, Ltd. For
97   * written permission, please contact dom4j-info@metastuff.com.
98   * 
99   * 4. Products derived from this Software may not be called "DOM4J" nor may
100  * "DOM4J" appear in their names without prior written permission of MetaStuff,
101  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
102  * 
103  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
104  * 
105  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
106  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
107  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
108  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
109  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
110  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
111  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
112  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
113  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
114  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
115  * POSSIBILITY OF SUCH DAMAGE.
116  * 
117  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
118  */
119 

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/XPathExamplesTest.html0000644000175000017500000004746210242117764023033 0ustar ebourgebourg XPathExamplesTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.Iterator;
13  import java.util.List;
14  
15  import org.dom4j.io.SAXReader;
16  import org.dom4j.rule.Pattern;
17  
18  /***
19   * Performs a number of unit test cases on the XPath engine
20   * 
21   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
22   * @version $Revision: 1.5 $
23   */
24  public class XPathExamplesTest extends AbstractTestCase {
25      protected SAXReader xmlReader = new SAXReader();
26  
27      /*** The document on which the tests are being run */
28      protected Document testDocument;
29  
30      /*** The context node on which the tests are being run */
31      protected Node testContext;
32  
33      /*** factory for XPath, Patterns and nodes */
34      protected DocumentFactory factory = DocumentFactory.getInstance();
35  
36      public static void main(String[] args) {
37          TestRunner.run(XPathExamplesTest.class);
38      }
39  
40      // Test case(s)
41      // -------------------------------------------------------------------------
42      public void testXPaths() throws Exception {
43          Document document = getDocument("/xml/test/xpath/tests.xml");
44          Element root = document.getRootElement();
45  
46          Iterator iter = root.elementIterator("document");
47  
48          while (iter.hasNext()) {
49              Element documentTest = (Element) iter.next();
50              testDocument(documentTest);
51          }
52      }
53  
54      // Implementation methods
55      // -------------------------------------------------------------------------
56      protected void testDocument(Element documentTest) throws Exception {
57          String url = documentTest.attributeValue("url");
58          testDocument = xmlReader.read(getFile(url));
59          assertTrue("Loaded test document: " + url, testDocument != null);
60  
61          log("Loaded document: " + url);
62  
63          for (Iterator iter = documentTest.elementIterator("context"); iter
64                  .hasNext();) {
65              Element context = (Element) iter.next();
66              testContext(documentTest, context);
67          }
68      }
69  
70      protected void testContext(Element documentTest, Element context)
71              throws Exception {
72          String xpath = context.attributeValue("select");
73  
74          List list = testDocument.selectNodes(xpath);
75  
76          assertTrue("Found at least one context nodes to test for path: "
77                  + xpath, (list != null) && (list.size() > 0));
78  
79          for (Iterator iter = list.iterator(); iter.hasNext();) {
80              Object object = iter.next();
81              assertTrue("Context node is a Node: " + object,
82                      object instanceof Node);
83              testContext = (Node) object;
84  
85              log("Context is now: " + testContext);
86              runTests(documentTest, context);
87              log("");
88          }
89      }
90  
91      protected void runTests(Element documentTest, Element context)
92              throws Exception {
93          for (Iterator iter = context.elementIterator("test"); iter.hasNext();) {
94              Element test = (Element) iter.next();
95              runTest(documentTest, context, test);
96          }
97  
98          for (Iterator it = context.elementIterator("valueOf"); it.hasNext();) {
99              Element valueOf = (Element) it.next();
100             testValueOf(documentTest, context, valueOf);
101         }
102 
103         for (Iterator it = context.elementIterator("pattern"); it.hasNext();) {
104             Element pattern = (Element) it.next();
105             testPattern(documentTest, context, pattern);
106         }
107 
108         Iterator it = context.elementIterator("fileter");
109 
110         while (it.hasNext()) {
111             Element filter = (Element) it.next();
112             testFilter(documentTest, context, filter);
113         }
114     }
115 
116     protected void runTest(Element documentTest, Element context, Element test)
117             throws Exception {
118         String xpath = test.attributeValue("select");
119 
120         String description = "Path: " + xpath;
121 
122         String exception = test.attributeValue("exception");
123         if ((exception != null) && exception.equals("true")) {
124             try {
125                 testContext.selectNodes(xpath);
126                 fail("Exception was not thrown");
127             } catch (XPathException e) {
128                 return;
129             }
130         }
131         
132         String count = test.attributeValue("count");
133 
134         if (count != null) {
135             int expectedSize = Integer.parseInt(count);
136             List results = testContext.selectNodes(xpath);
137 
138             log(description + " found result size: " + results.size());
139 
140             assertEquals(description + " wrong result size", expectedSize,
141                     results.size());
142         }
143 
144         Element valueOf = test.element("valueOf");
145 
146         if (valueOf != null) {
147             Node node = testContext.selectSingleNode(xpath);
148             assertTrue(description + " found node", node != null);
149 
150             String expected = valueOf.getText();
151             String result = node.valueOf(valueOf.attributeValue("select"));
152 
153             log(description);
154             log("\texpected: " + expected + " result: " + result);
155 
156             assertEquals(description, expected, result);
157         }
158     }
159 
160     protected void testValueOf(Element documentTest, Element context,
161             Element valueOf) throws Exception {
162         String xpath = valueOf.attributeValue("select");
163         String description = "valueOf: " + xpath;
164 
165         String expected = valueOf.getText();
166         String result = testContext.valueOf(xpath);
167 
168         log(description);
169         log("\texpected: " + expected + " result: " + result);
170 
171         assertEquals(description, expected, result);
172     }
173 
174     protected void testPattern(Element documentTest, Element context,
175             Element patternElement) throws Exception {
176         String match = patternElement.attributeValue("match");
177         String description = "match: " + match;
178 
179         log("");
180         log(description);
181 
182         Pattern pattern = factory.createPattern(match);
183 
184         assertTrue(description, pattern.matches(testContext));
185     }
186 
187     protected void testFilter(Element documentTest, Element context,
188             Element pattern) throws Exception {
189         String match = pattern.attributeValue("match");
190         String description = "match: " + match;
191 
192         assertTrue(description, testContext.matches(match));
193     }
194 }
195 
196 /*
197  * Redistribution and use of this software and associated documentation
198  * ("Software"), with or without modification, are permitted provided that the
199  * following conditions are met:
200  * 
201  * 1. Redistributions of source code must retain copyright statements and
202  * notices. Redistributions must also contain a copy of this document.
203  * 
204  * 2. Redistributions in binary form must reproduce the above copyright notice,
205  * this list of conditions and the following disclaimer in the documentation
206  * and/or other materials provided with the distribution.
207  * 
208  * 3. The name "DOM4J" must not be used to endorse or promote products derived
209  * from this Software without prior written permission of MetaStuff, Ltd. For
210  * written permission, please contact dom4j-info@metastuff.com.
211  * 
212  * 4. Products derived from this Software may not be called "DOM4J" nor may
213  * "DOM4J" appear in their names without prior written permission of MetaStuff,
214  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
215  * 
216  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
217  * 
218  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
219  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
220  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
221  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
222  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
223  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
224  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
225  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
226  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
227  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
228  * POSSIBILITY OF SUCH DAMAGE.
229  * 
230  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
231  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/NamespacesTest.html0000644000175000017500000007764610242117606022371 0ustar ebourgebourg NamespacesTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.StringReader;
13  import java.util.Iterator;
14  import java.util.List;
15  
16  import javax.xml.parsers.DocumentBuilder;
17  import javax.xml.parsers.DocumentBuilderFactory;
18  
19  import org.dom4j.io.DOMReader;
20  
21  import org.xml.sax.InputSource;
22  
23  /***
24   * Test the use of namespaces
25   * 
26   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
27   * @version $Revision: 1.4 $
28   */
29  public class NamespacesTest extends AbstractTestCase {
30      public static void main(String[] args) {
31          TestRunner.run(NamespacesTest.class);
32      }
33  
34      // Test case(s)
35      // -------------------------------------------------------------------------
36      public void testNamespaces() throws Exception {
37          testNamespaces(document);
38          testNamespaces(saxRoundTrip(document));
39          testNamespaces(domRoundTrip(document));
40      }
41  
42      public void testNamespaces(Document document) throws Exception {
43          Document doc2 = (Document) document.clone();
44  
45          Element root = doc2.getRootElement();
46          assertNamespace(root.getNamespace(), "",
47                  "http://www.w3.org/2001/XMLSchema");
48          assertEquals("xmlns=\"http://www.w3.org/2001/XMLSchema\"", root
49                  .getNamespace().asXML());
50          assertEquals("namespace::*[name()='']", root.getNamespace().getPath());
51          assertEquals("namespace::*[name()='']", root.getNamespace()
52                  .getUniquePath());
53  
54          List additionalNS = root.additionalNamespaces();
55          assertTrue("at least one additional namespace", (additionalNS != null)
56                  && (additionalNS.size() > 0));
57  
58          Namespace ns = (Namespace) additionalNS.get(0);
59          assertNamespace(ns, "t", "http://www.w3.org/namespace/");
60          assertEquals("xmlns:t=\"http://www.w3.org/namespace/\"", ns.asXML());
61          assertEquals("namespace::t", ns.getPath());
62          assertEquals("namespace::t", ns.getUniquePath());
63  
64          Node node = root.node(0);
65          assertTrue("First node is a namespace", node instanceof Namespace);
66  
67          // now lets try change the namespace
68          root.remove(ns);
69          root.addNamespace("t", "myNewURI");
70  
71          additionalNS = root.additionalNamespaces();
72          assertTrue("at least one additional namespace", (additionalNS != null)
73                  && (additionalNS.size() > 0));
74  
75          ns = (Namespace) additionalNS.get(0);
76          assertNamespace(ns, "t", "myNewURI");
77  
78          // lets test the list is backed
79          additionalNS.remove(0);
80          additionalNS.add(Namespace.get("t", "myNewURI-2"));
81  
82          additionalNS = root.additionalNamespaces();
83          assertTrue("at least one additional namespace", (additionalNS != null)
84                  && (additionalNS.size() > 0));
85  
86          ns = (Namespace) additionalNS.get(0);
87          assertNamespace(ns, "t", "myNewURI-2");
88  
89          additionalNS.clear();
90          root.addNamespace("t", "myNewURI");
91  
92          additionalNS = root.additionalNamespaces();
93          assertTrue("at least one additional namespace", (additionalNS != null)
94                  && (additionalNS.size() > 0));
95  
96          ns = (Namespace) additionalNS.get(0);
97          assertNamespace(ns, "t", "myNewURI");
98  
99          log("Namespaces: " + additionalNS);
100         log("XML is now");
101         log(root.asXML());
102     }
103 
104     public void testNamespaceForPrefix() throws Exception {
105         testNamespaceForPrefix(document);
106         testNamespaceForPrefix(saxRoundTrip(document));
107         testNamespaceForPrefix(domRoundTrip(document));
108     }
109 
110     public void testNamespaceForPrefix(Document document) throws Exception {
111         Element root = document.getRootElement();
112         Namespace ns = root.getNamespaceForPrefix("t");
113 
114         assertNamespace(ns, "t", "http://www.w3.org/namespace/");
115 
116         Element element = (Element) root.elements().get(0);
117         Namespace ns2 = element.getNamespaceForPrefix("t");
118 
119         assertNamespace(ns2, "t", "http://www.w3.org/namespace/");
120         assertTrue("Same namespace instance returned", ns == ns2);
121 
122         log("found: " + ns.asXML());
123     }
124 
125     public void testNamespaceForDefaultPrefix() throws Exception {
126         Document document = getDocument("/xml/test/defaultNamespace.xml");
127 
128         testNamespaceForDefaultPrefix(document);
129         testNamespaceForDefaultPrefix(saxRoundTrip(document));
130         testNamespaceForDefaultPrefix(domRoundTrip(document));
131     }
132 
133     public void testNamespaceForDefaultPrefix(Document document)
134             throws Exception {
135         List list = document.selectNodes("//*");
136 
137         for (Iterator iter = list.iterator(); iter.hasNext();) {
138             Element element = (Element) iter.next();
139             Namespace ns = element.getNamespaceForPrefix("");
140             assertNamespace(ns, "", "dummyNamespace");
141             ns = element.getNamespaceForPrefix(null);
142             assertNamespace(ns, "", "dummyNamespace");
143             log("found: " + ns.asXML());
144         }
145     }
146 
147     public void testAttributeDefaultPrefix() throws Exception {
148         Document document = getDocument("/xml/test/soap3.xml");
149 
150         testAttributeDefaultPrefix(document);
151         testAttributeDefaultPrefix(saxRoundTrip(document));
152         testAttributeDefaultPrefix(domRoundTrip(document));
153     }
154 
155     public void testAttributeDefaultPrefix(Document document) throws Exception {
156         List list = document.selectNodes("//@*[local-name()='actor']");
157 
158         assertTrue("Matched at least one 'actor' attribute", list.size() > 0);
159 
160         for (Iterator iter = list.iterator(); iter.hasNext();) {
161             Attribute attribute = (Attribute) iter.next();
162 
163             log("found: " + attribute.asXML());
164 
165             Element element = attribute.getParent();
166             assertTrue("Attribute has a parent", element != null);
167 
168             Namespace ns = element.getNamespaceForPrefix("");
169 
170             String uri = "http://schemas.xmlsoap.org/soap/envelope/";
171             assertNamespace(ns, "", uri);
172 
173             Namespace ns2 = attribute.getNamespace();
174 
175             // Note that namespaces do not inherit the default namespace!
176             assertNamespace(ns2, "", "");
177         }
178     }
179 
180     public void testNamespaceForURI() throws Exception {
181         testNamespaceForURI(document);
182         testNamespaceForURI(saxRoundTrip(document));
183         testNamespaceForURI(domRoundTrip(document));
184     }
185 
186     public void testNamespaceForURI(Document document) throws Exception {
187         Element root = document.getRootElement();
188 
189         Namespace ns = root.getNamespaceForURI("http://www.w3.org/namespace/");
190 
191         assertNamespace(ns, "t", "http://www.w3.org/namespace/");
192 
193         Element element = (Element) root.elements().get(0);
194         Namespace ns2 = element
195                 .getNamespaceForURI("http://www.w3.org/namespace/");
196 
197         assertNamespace(ns2, "t", "http://www.w3.org/namespace/");
198 
199         assertTrue("Same namespace instance returned", ns == ns2);
200 
201         log("found: " + ns.asXML());
202     }
203 
204     public void testRedeclareNamespaces() throws Exception {
205         Document document = getDocument("/xml/test/soap2.xml");
206         testRedeclareNamespaces(document);
207         testRedeclareNamespaces(saxRoundTrip(document));
208         testRedeclareNamespaces(domRoundTrip(document));
209     }
210 
211     public void testRedeclareNamespaces(Document document) throws Exception {
212         String uri = "http://schemas.xmlsoap.org/soap/envelope/";
213         assertNamespaces(document.selectNodes("//*[local-name()='Envelope']"),
214                 "SOAP-ENV", uri);
215         assertNamespaces(document.selectNodes("//*[local-name()='Body']"),
216                 "SOAP-ENV", uri);
217         assertNamespaces(document.selectNodes("//*[local-name()='bar']"), "a",
218                 "barURI");
219         assertNamespaces(document.selectNodes("//*[local-name()='newBar']"),
220                 "a", "newBarURI");
221         assertNamespaces(document.selectNodes("//*[local-name()='foo']"), "",
222                 "fooURI");
223         assertNamespaces(document.selectNodes("//*[local-name()='newFoo']"),
224                 "", "newFooURI");
225     }
226 
227     public void testDefaultNamespaceIssue() throws Exception {
228         Document document = getDocument("/xml/test/defaultNamespaceIssue.xsd");
229         testDefaultNamespaceIssue(document);
230         testDefaultNamespaceIssue(saxRoundTrip(document));
231         testDefaultNamespaceIssue(domRoundTrip(document));
232     }
233 
234     public void testDefaultNamespaceIssue(Document document) throws Exception {
235         // When writing documents using a default namespace with XMLWriter
236         // a redeclaration of the default namespace to "" was dropped in the
237         // output. Test that
238         // <xsd:schema><xsd:element><xsd:annotation><xsd:documentation><text>
239         // is in no namespace.
240         String expr 
241             = "/xsd:schema/xsd:element/xsd:annotation/xsd:documentation/text";
242         assertNotNull("default namespace redeclaration", (Element) document
243                 .selectSingleNode(expr));
244 
245         // The test document has a default namespace declaration on the root
246         // element ("schema"), but the element itself is not in the default
247         // namespace. Test that declaredNamespaces on the root element also
248         // returns the default namespace declaration.
249         Iterator iter = document.getRootElement().declaredNamespaces()
250                 .iterator();
251 
252         while (iter.hasNext()) {
253             Namespace ns = (Namespace) iter.next();
254 
255             if ("urn:wapforum:devicesheet".equals(ns.getURI())
256                     && "".equals(ns.getPrefix())) {
257                 return;
258             }
259         }
260 
261         fail("Default namespace declaration not present on root element");
262     }
263 
264     public void testDefaultNamespace() throws Exception {
265         Document doc = DocumentHelper.createDocument();
266         Element processDef = doc.addElement("process-definition",
267                 "http://jbpm.org/statedefinition-2.0-beta3");
268         Element startState = processDef.addElement("start-state");
269         startState.addAttribute("name", "start");
270 
271         Element transition = startState.addElement("transition");
272         transition.addAttribute("to", "first");
273 
274         assertEquals("http://jbpm.org/statedefinition-2.0-beta3", startState
275                 .getNamespace().getURI());
276         assertEquals("", startState.getNamespace().getPrefix());
277 
278         System.out.println(doc.asXML());
279     }
280 
281     // Implementation methods
282     // -------------------------------------------------------------------------
283     protected void setUp() throws Exception {
284         super.setUp();
285         document = getDocument("/xml/test/test_schema.xml");
286     }
287 
288     protected Document saxRoundTrip(Document document) throws Exception {
289         return DocumentHelper.parseText(document.asXML());
290     }
291 
292     protected Document domRoundTrip(Document document) throws Exception {
293         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
294         factory.setNamespaceAware(true);
295 
296         DocumentBuilder builder = factory.newDocumentBuilder();
297         org.w3c.dom.Document domDocument = builder.parse(new InputSource(
298                 new StringReader(document.asXML())));
299 
300         // now lets read it back as a DOM4J object
301         DOMReader domReader = new DOMReader();
302 
303         return domReader.read(domDocument);
304     }
305 
306     protected void assertNamespaces(List elements, String prefix, String uri)
307             throws Exception {
308         for (Iterator iter = elements.iterator(); iter.hasNext();) {
309             Element element = (Element) iter.next();
310             assertNamespace(element.getNamespace(), prefix, uri);
311         }
312     }
313 
314     protected void assertNamespace(Namespace ns, String prefix, String uri)
315             throws Exception {
316         assertEquals("namespace prefix", prefix, ns.getPrefix());
317         assertEquals("namespace URI", uri, ns.getURI());
318     }
319 }
320 
321 /*
322  * Redistribution and use of this software and associated documentation
323  * ("Software"), with or without modification, are permitted provided that the
324  * following conditions are met:
325  * 
326  * 1. Redistributions of source code must retain copyright statements and
327  * notices. Redistributions must also contain a copy of this document.
328  * 
329  * 2. Redistributions in binary form must reproduce the above copyright notice,
330  * this list of conditions and the following disclaimer in the documentation
331  * and/or other materials provided with the distribution.
332  * 
333  * 3. The name "DOM4J" must not be used to endorse or promote products derived
334  * from this Software without prior written permission of MetaStuff, Ltd. For
335  * written permission, please contact dom4j-info@metastuff.com.
336  * 
337  * 4. Products derived from this Software may not be called "DOM4J" nor may
338  * "DOM4J" appear in their names without prior written permission of MetaStuff,
339  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
340  * 
341  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
342  * 
343  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
344  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
345  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
346  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
347  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
348  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
349  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
350  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
351  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
352  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
353  * POSSIBILITY OF SUCH DAMAGE.
354  * 
355  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
356  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/DetachTest.html0000644000175000017500000002345510242117745021473 0ustar ebourgebourg DetachTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  /***
13   * A test harness to test the detach() method on root elements
14   * 
15   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
16   * @version $Revision: 1.3 $
17   */
18  public class DetachTest extends AbstractTestCase {
19      public static void main(String[] args) {
20          TestRunner.run(DetachTest.class);
21      }
22  
23      // Test case(s)
24      // -------------------------------------------------------------------------
25      public void testRoot() throws Exception {
26          document.setName("doc1");
27  
28          Element root = document.getRootElement();
29          assertTrue("Has root element", root != null);
30          assertTrue("Root has no parent", root.getParent() == null);
31  
32          root.detach();
33  
34          assertTrue("Detached root now has no document",
35                  root.getDocument() == null);
36          assertTrue("Original doc now has no root element", document
37                  .getRootElement() == null);
38  
39          Document doc2 = DocumentHelper.createDocument();
40          doc2.setName("doc2");
41  
42          assertTrue("Doc2 has no root element", doc2.getRootElement() == null);
43  
44          doc2.setRootElement(root);
45  
46          assertTrue("Doc2 has now has root element",
47                  doc2.getRootElement() == root);
48          assertTrue("Root element now has document", root.getDocument() == doc2);
49  
50          Document doc3 = DocumentHelper.createDocument();
51          doc3.setName("doc3");
52          doc3.addElement("foo");
53  
54          assertTrue("Doc3 has root element", doc3.getRootElement() != null);
55  
56          root = doc2.getRootElement();
57          root.detach();
58          doc3.setRootElement(root);
59  
60          assertTrue("Doc3 now has root element", doc3.getRootElement() == root);
61          assertSame("Root element now has a document", root.getDocument(), doc3);
62          assertTrue("Doc2 has no root element", doc2.getRootElement() == null);
63      }
64  }
65  
66  /*
67   * Redistribution and use of this software and associated documentation
68   * ("Software"), with or without modification, are permitted provided that the
69   * following conditions are met:
70   * 
71   * 1. Redistributions of source code must retain copyright statements and
72   * notices. Redistributions must also contain a copy of this document.
73   * 
74   * 2. Redistributions in binary form must reproduce the above copyright notice,
75   * this list of conditions and the following disclaimer in the documentation
76   * and/or other materials provided with the distribution.
77   * 
78   * 3. The name "DOM4J" must not be used to endorse or promote products derived
79   * from this Software without prior written permission of MetaStuff, Ltd. For
80   * written permission, please contact dom4j-info@metastuff.com.
81   * 
82   * 4. Products derived from this Software may not be called "DOM4J" nor may
83   * "DOM4J" appear in their names without prior written permission of MetaStuff,
84   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
85   * 
86   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
87   * 
88   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
89   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
90   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
91   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
92   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
93   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
94   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
95   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
96   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
97   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
98   * POSSIBILITY OF SUCH DAMAGE.
99   * 
100  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
101  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/XSLTTest.html0000644000175000017500000002464310242117607021072 0ustar ebourgebourg XSLTTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.List;
13  
14  import javax.xml.transform.Source;
15  import javax.xml.transform.Transformer;
16  import javax.xml.transform.TransformerFactory;
17  import javax.xml.transform.stream.StreamSource;
18  
19  import org.dom4j.io.DocumentResult;
20  import org.dom4j.io.DocumentSource;
21  
22  /***
23   * Tests that XSLT works correctly
24   * 
25   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
26   * @version $Revision: 1.4 $
27   */
28  public class XSLTTest extends AbstractTestCase {
29      public static void main(String[] args) {
30          TestRunner.run(XSLTTest.class);
31      }
32  
33      // Test case(s)
34      // -------------------------------------------------------------------------
35      public void testTransform() throws Exception {
36          Document transformedDoc = transform("/xml/nitf/ashtml.xsl");
37  
38          // log( transformedDoc.asXML() );
39          assertTrue("Transformed Document is not null", transformedDoc != null);
40  
41          List h1List = transformedDoc.selectNodes("/html//h1");
42  
43          assertTrue("At least one <h1>", h1List.size() > 0);
44  
45          List pList = transformedDoc.selectNodes("//p");
46  
47          assertTrue("At least one <p>", pList.size() > 0);
48      }
49  
50      // Implementation methods
51      // -------------------------------------------------------------------------
52      protected void setUp() throws Exception {
53          super.setUp();
54          document = getDocument("/xml/nitf/sample.xml");
55      }
56  
57      protected Document transform(String xsl) throws Exception {
58          assertTrue("Document is not null", document != null);
59  
60          // load the transformer
61          TransformerFactory factory = TransformerFactory.newInstance();
62          Transformer transformer = factory.newTransformer(new StreamSource(
63                  getFile(xsl)));
64  
65          // now lets create the TrAX source and result
66          // objects and do the transformation
67          Source source = new DocumentSource(document);
68          DocumentResult result = new DocumentResult();
69          transformer.transform(source, result);
70  
71          return result.getDocument();
72      }
73  }
74  
75  /*
76   * Redistribution and use of this software and associated documentation
77   * ("Software"), with or without modification, are permitted provided that the
78   * following conditions are met:
79   * 
80   * 1. Redistributions of source code must retain copyright statements and
81   * notices. Redistributions must also contain a copy of this document.
82   * 
83   * 2. Redistributions in binary form must reproduce the above copyright notice,
84   * this list of conditions and the following disclaimer in the documentation
85   * and/or other materials provided with the distribution.
86   * 
87   * 3. The name "DOM4J" must not be used to endorse or promote products derived
88   * from this Software without prior written permission of MetaStuff, Ltd. For
89   * written permission, please contact dom4j-info@metastuff.com.
90   * 
91   * 4. Products derived from this Software may not be called "DOM4J" nor may
92   * "DOM4J" appear in their names without prior written permission of MetaStuff,
93   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
94   * 
95   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
96   * 
97   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
98   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
99   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
100  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
101  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
102  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
103  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
104  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
105  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
106  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
107  * POSSIBILITY OF SUCH DAMAGE.
108  * 
109  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
110  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/GetQNamesTest.html0000644000175000017500000002251310242117752022117 0ustar ebourgebourg GetQNamesTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.List;
13  
14  import org.dom4j.io.SAXReader;
15  
16  /***
17   * A test harness to test the DocumentFactory.getQNames() method
18   * 
19   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
20   * @version $Revision: 1.4 $
21   */
22  public class GetQNamesTest extends AbstractTestCase {
23      public static void main(String[] args) {
24          TestRunner.run(GetQNamesTest.class);
25      }
26  
27      // Test case(s)
28      // -------------------------------------------------------------------------
29      public void testQNames() throws Exception {
30          DocumentFactory factory = new DocumentFactory();
31  
32          SAXReader reader = new SAXReader();
33          reader.setDocumentFactory(factory);
34          getDocument("/xml/test/soap2.xml", reader);
35  
36          List qnames = factory.getQNames();
37          assertEquals("Number of QNames not correct", 15, qnames.size());
38      }
39  
40      /***
41       * Test the element rename functionality which was lacking as spotted by Rob
42       * Lebowitz
43       * 
44       * @throws Exception
45       *             DOCUMENT ME!
46       */
47      public void testRename() throws Exception {
48          Document doc = DocumentHelper.createDocument();
49          Element root = doc.addElement("foo");
50  
51          assertEquals("named correctly", "foo", root.getName());
52  
53          root.setName("bar");
54  
55          assertEquals("named correctly", "bar", root.getName());
56  
57          QName xyz = root.getQName("xyz");
58  
59          root.setQName(xyz);
60  
61          assertEquals("QNamed correctly", xyz, root.getQName());
62      }
63  }
64  
65  /*
66   * Redistribution and use of this software and associated documentation
67   * ("Software"), with or without modification, are permitted provided that the
68   * following conditions are met:
69   * 
70   * 1. Redistributions of source code must retain copyright statements and
71   * notices. Redistributions must also contain a copy of this document.
72   * 
73   * 2. Redistributions in binary form must reproduce the above copyright notice,
74   * this list of conditions and the following disclaimer in the documentation
75   * and/or other materials provided with the distribution.
76   * 
77   * 3. The name "DOM4J" must not be used to endorse or promote products derived
78   * from this Software without prior written permission of MetaStuff, Ltd. For
79   * written permission, please contact dom4j-info@metastuff.com.
80   * 
81   * 4. Products derived from this Software may not be called "DOM4J" nor may
82   * "DOM4J" appear in their names without prior written permission of MetaStuff,
83   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
84   * 
85   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
86   * 
87   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
88   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
89   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
90   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
91   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
92   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
93   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
94   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
95   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
96   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
97   * POSSIBILITY OF SUCH DAMAGE.
98   * 
99   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
100  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/dtd/0000755000175000017500000000000012133227266017320 5ustar ebourgebourgdom4j-1.6.1/docs/xref-test/org/dom4j/dtd/AttributeDeclTest.html0000644000175000017500000005553610242117702023607 0ustar ebourgebourg AttributeDeclTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dtd;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.AbstractTestCase;
13  
14  /***
15   * Tests the {@link AttributeDecl}functionality. Tests each of the property
16   * access methods and the serialization mechanisms. Correct parsing is tested by
17   * {@link DocTypeTest}.
18   * 
19   * <p>
20   * There are several key variations that need to be tested both here and in
21   * {@link DocTypeTest}, which is responsible for testing correct parsing of the
22   * {@link DocumentType}. Those variations include the different
23   * <code>valueDefault</code> and <code>value</code> variations so that we
24   * can test for correct acceptance and correct rejection of attribute
25   * declarations.
26   * </p>
27   * 
28   * <p>
29   * </p>
30   * 
31   * @author Bryan Thompson
32   * @author Maarten Coene
33   * @version $Revision: 1.3 $
34   * 
35   * @todo The dom4j documentation needs to describe what representation SHOULD be
36   *       generated by {@link AttributeDecl#toString()}.
37   * @todo The dom4j AttributeDecl should expose some methods that make it easier
38   *       for people to use the DTD grammar, e.g., isFixed(), isRequired(),
39   *       isImplied().
40   */
41  public class AttributeDeclTest extends AbstractTestCase {
42      public static void main(String[] args) {
43          TestRunner.run(AttributeDeclTest.class);
44      }
45  
46      // Test case(s)
47      // -------------------------------------------------------------------------
48  
49      /***
50       * Test
51       * 
52       * <pre>
53       * 
54       *  &lt;!ATTLIST foo bar ID #IMPLIED&gt;
55       *  
56       * </pre>.
57       */
58      public void testIdImpliedNone() {
59          MyTestAttributeDecl decl = new MyTestAttributeDecl("foo", // elementName
60                  "bar", // attributeName
61                  "ID", // type
62                  "#IMPLIED", // valueDefault
63                  null, // value
64                  "<!ATTLIST foo bar ID #IMPLIED>");
65          assertSameAttributeDecl(decl, new AttributeDecl("foo", "bar", "ID",
66                  "#IMPLIED", null));
67      }
68  
69      /***
70       * Test
71       * 
72       * <pre>
73       * 
74       *  &lt;!ATTLIST foo bar CDATA #FIXED \&quot;goo\&quot;&gt;
75       *  
76       * </pre>.
77       */
78      public void testCDataFixedValue() {
79          MyTestAttributeDecl decl = new MyTestAttributeDecl("foo", // elementName
80                  "bar", // attributeName
81                  "CDATA", // type
82                  "#FIXED", // valueDefault
83                  "goo", // value
84                  "<!ATTLIST foo bar CDATA #FIXED \"goo\">");
85          assertSameAttributeDecl(decl, new AttributeDecl("foo", "bar", "CDATA",
86                  "#FIXED", "goo"));
87      }
88  
89      /***
90       * Test
91       * 
92       * <pre>
93       * 
94       *  &lt;!ATTLIST foo bar CDATA &quot;goo&quot;&gt;
95       *  
96       * </pre>.
97       */
98      public void testCDataNoneValue() {
99          MyTestAttributeDecl decl = new MyTestAttributeDecl("foo", // elementName
100                 "bar", // attributeName
101                 "CDATA", // type
102                 null, // valueDefault
103                 "goo", // value
104                 "<!ATTLIST foo bar CDATA \"goo\">");
105         assertSameAttributeDecl(decl, new AttributeDecl("foo", "bar", "CDATA",
106                 null, "goo"));
107     }
108 
109     // Implementation methods
110     // -------------------------------------------------------------------------
111     protected void assertSameAttributeDecl(MyTestAttributeDecl expected,
112             AttributeDecl actual) {
113         assertEquals("elementName is correct", expected.getElementName(),
114                 actual.getElementName());
115 
116         assertEquals("attributeName is correct", expected.getAttributeName(),
117                 actual.getAttributeName());
118 
119         assertEquals("type is correct", expected.getType(), actual.getType());
120 
121         assertEquals("valueDefault is correct", expected.getValueDefault(),
122                 actual.getValueDefault());
123 
124         assertEquals("toString() is correct", expected.getText(), actual
125                 .toString());
126     }
127 
128     /***
129      * Helper is useful since we are trying to exhaustively test the ATTLIST
130      * variations and their correct serialization.
131      */
132     protected static class MyTestAttributeDecl {
133         private String elName;
134 
135         private String attName;
136 
137         private String declType;
138 
139         private String defaultValue;
140 
141         private String declValue;
142 
143         private String txt;
144 
145         /***
146          * DOCUMENT ME!
147          * 
148          * @param elementName
149          *            The name of the element whose attribute is being
150          *            described.
151          * @param attributeName
152          *            The name of the attribute.
153          * @param type
154          *            The type of the declared attribute, e.g., CDATA, ID,
155          *            IDREF, IDREFS, ENTITY, ENTITIES, NMTOKEN, NKTOKENS
156          * @param valueDefault
157          *            The type of default that applies for this attribute
158          *            declaration, e.g., #REQUIRED, #IMPLIED, #FIXED (in which
159          *            case the <i>value </i> MUST be non- <code>null</code>
160          *            and specifies the fixed value for the attribute, or
161          *            <code>null</code> if no valueDefault was specified in
162          *            the attribute declaration (in which case the <i>value </i>
163          *            MUST be non- <code>null</code> and specifies the default
164          *            value for the attribute).
165          * @param value
166          *            The value of the attribute assigned in the attribute
167          *            declaration -or- <code>null</code> if no value was
168          *            provided in the attribute declaration. The value MUST be
169          *            <code>null</code> unless the <i>valueDefault </i> is
170          *            either "#FIXED" or <code>null</code>.
171          * @param text
172          *            The text representation of the attribute declaration,
173          *            e.g., <code>&lt;!ATTLIST foo id ID #IMPLIED&gt;</code>.
174          * 
175          * @todo The constructor and properties in {@link AttributeDecl}should
176          *       have some similar javadoc so that people more easily understand
177          *       the interaction and difference between the <i>valueDefault </i>
178          *       and <i>value </i> properties. The constructor SHOULD be clear
179          *       about whether and when the <code>valueDefault</code> and
180          *       <code>value</code> properties MUST be <code>null</code>.
181          */
182         public MyTestAttributeDecl(String elementName, String attributeName,
183                 String type, String valueDefault, String value, String text) {
184             elName = elementName;
185 
186             attName = attributeName;
187 
188             declType = type;
189 
190             defaultValue = valueDefault;
191 
192             declValue = value;
193 
194             txt = text;
195         }
196 
197         public String getElementName() {
198             return elName;
199         }
200 
201         public String getAttributeName() {
202             return attName;
203         }
204 
205         public String getType() {
206             return declType;
207         }
208 
209         public String getValueDefault() {
210             return defaultValue;
211         }
212 
213         public String getValue() {
214             return declValue;
215         }
216 
217         public String getText() {
218             return txt;
219         }
220     } // Class TestAttributeDecl
221 }
222 
223 /*
224  * Redistribution and use of this software and associated documentation
225  * ("Software"), with or without modification, are permitted provided that the
226  * following conditions are met:
227  * 
228  * 1. Redistributions of source code must retain copyright statements and
229  * notices. Redistributions must also contain a copy of this document.
230  * 
231  * 2. Redistributions in binary form must reproduce the above copyright notice,
232  * this list of conditions and the following disclaimer in the documentation
233  * and/or other materials provided with the distribution.
234  * 
235  * 3. The name "DOM4J" must not be used to endorse or promote products derived
236  * from this Software without prior written permission of MetaStuff, Ltd. For
237  * written permission, please contact dom4j-info@metastuff.com.
238  * 
239  * 4. Products derived from this Software may not be called "DOM4J" nor may
240  * "DOM4J" appear in their names without prior written permission of MetaStuff,
241  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
242  * 
243  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
244  * 
245  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
246  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
247  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
248  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
249  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
250  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
251  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
252  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
253  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
254  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
255  * POSSIBILITY OF SUCH DAMAGE.
256  * 
257  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
258  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/dtd/package-summary.html0000644000175000017500000000502310242117650023266 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.dtd

Class Summary
AttributeDeclTest
ElementDeclTest
ExternalEntityDeclTest
InternalEntityDeclTest
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref-test/org/dom4j/dtd/ElementDeclTest.html0000644000175000017500000002245510242117737023237 0ustar ebourgebourg ElementDeclTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dtd;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.AbstractTestCase;
13  
14  /***
15   * Tests the {@link ElementDecl}functionality. Tests each of the property
16   * access methods and the serialization mechanisms. Correct parsing is tested by
17   * {@link DocTypeTest}.
18   * 
19   * <P>
20   * </p>
21   * 
22   * @author Bryan Thompson
23   * @author Maarten Coene
24   * @version $Revision: 1.3 $
25   * 
26   * @todo The dom4j documentation needs to describe what representation SHOULD be
27   *       generated by {@link ElementDecl#toString()}.
28   */
29  public class ElementDeclTest extends AbstractTestCase {
30      public static void main(String[] args) {
31          TestRunner.run(ElementDeclTest.class);
32      }
33  
34      // Test case(s)
35      // -------------------------------------------------------------------------
36  
37      /***
38       * Test
39       * 
40       * <pre>
41       * 
42       *  &lt;!ELEMENT an-element (#PCDATA)&gt;
43       *  
44       * </pre>
45       */
46      public void testSimpleElementDecl() {
47          String expectedName = "an-element";
48  
49          String expectedModel = "(#PCDATA)";
50  
51          String expectedText = "<!ELEMENT an-element (#PCDATA)>";
52  
53          ElementDecl actual = new ElementDecl(expectedName, expectedModel);
54  
55          assertEquals("name is correct", expectedName, actual.getName());
56  
57          assertEquals("model is correct", expectedModel, actual.getModel());
58  
59          assertEquals("toString() is correct", expectedText, actual.toString());
60      }
61  
62      // Implementation methods
63      // -------------------------------------------------------------------------
64  }
65  
66  /*
67   * Redistribution and use of this software and associated documentation
68   * ("Software"), with or without modification, are permitted provided that the
69   * following conditions are met:
70   * 
71   * 1. Redistributions of source code must retain copyright statements and
72   * notices. Redistributions must also contain a copy of this document.
73   * 
74   * 2. Redistributions in binary form must reproduce the above copyright notice,
75   * this list of conditions and the following disclaimer in the documentation
76   * and/or other materials provided with the distribution.
77   * 
78   * 3. The name "DOM4J" must not be used to endorse or promote products derived
79   * from this Software without prior written permission of MetaStuff, Ltd. For
80   * written permission, please contact dom4j-info@metastuff.com.
81   * 
82   * 4. Products derived from this Software may not be called "DOM4J" nor may
83   * "DOM4J" appear in their names without prior written permission of MetaStuff,
84   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
85   * 
86   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
87   * 
88   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
89   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
90   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
91   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
92   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
93   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
94   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
95   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
96   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
97   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
98   * POSSIBILITY OF SUCH DAMAGE.
99   * 
100  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
101  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/dtd/ExternalEntityDeclTest.html0000644000175000017500000003201110242117745024611 0ustar ebourgebourg ExternalEntityDeclTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dtd;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.AbstractTestCase;
13  
14  /***
15   * Tests the {@link ExternalEntityDecl}functionality. Tests each of the
16   * property access methods and the serialization mechanisms. Correct parsing is
17   * tested by {@link DocTypeTest}.
18   * 
19   * <P>
20   * </p>
21   * 
22   * @author Bryan Thompson
23   * @author Maarten Coene
24   * @version $Revision: 1.3 $
25   * 
26   * @todo The dom4j documentation needs to describe what representation SHOULD be
27   *       generated by {@link ExternalEntityDecl#toString()}.
28   * @todo Test support for NOTATION and NDATA when used as part of an external
29   *       entity declaration. dom4j does not appear to support NOTATION and NDATA
30   *       at this time.
31   */
32  public class ExternalEntityDeclTest extends AbstractTestCase {
33      public static void main(String[] args) {
34          TestRunner.run(ExternalEntityDeclTest.class);
35      }
36  
37      // Test case(s)
38      // -------------------------------------------------------------------------
39      public void testToString() {
40          ExternalEntityDecl decl1 = new ExternalEntityDecl("name", null,
41                  "systemID");
42          ExternalEntityDecl decl2 = new ExternalEntityDecl("%name", null,
43                  "systemID");
44  
45          assertEquals("<!ENTITY name SYSTEM \"systemID\" >", decl1.toString());
46          assertEquals("<!ENTITY % name SYSTEM \"systemID\" >", decl2.toString());
47      }
48  
49      /***
50       * Tests external entity declaration using only the SYSTEM identifier.
51       */
52      public void testSystemId() {
53          String expectedName = "anEntity";
54  
55          String expectedPublicID = null;
56  
57          String expectedSystemID = "http://www.myorg.org/foo";
58  
59          String expectedText = "<!ENTITY anEntity "
60                  + "SYSTEM \"http://www.myorg.org/foo\" >";
61  
62          ExternalEntityDecl actual = new ExternalEntityDecl(expectedName,
63                  expectedPublicID, expectedSystemID);
64  
65          assertEquals("name is correct", expectedName, actual.getName());
66  
67          assertEquals("publicID is correct", expectedPublicID, actual
68                  .getPublicID());
69  
70          assertEquals("systemID is correct", expectedSystemID, actual
71                  .getSystemID());
72  
73          assertEquals("toString() is correct", expectedText, actual.toString());
74      }
75  
76      /***
77       * Tests external entity declaration using both SYSTEM and PUBLIC
78       * identifiers.
79       */
80      public void testPublicIdSystemId() {
81          String expectedName = "anEntity";
82  
83          String expectedPublicID = "-//dom4j//DTD sample";
84  
85          String expectedSystemID = "http://www.myorg.org/foo";
86  
87          String expectedText = "<!ENTITY anEntity "
88                  + "PUBLIC \"-//dom4j//DTD sample\" "
89                  + "\"http://www.myorg.org/foo\" >";
90  
91          ExternalEntityDecl actual = new ExternalEntityDecl(expectedName,
92                  expectedPublicID, expectedSystemID);
93  
94          assertEquals("name is correct", expectedName, actual.getName());
95  
96          assertEquals("publicID is correct", expectedPublicID, actual
97                  .getPublicID());
98  
99          assertEquals("systemID is correct", expectedSystemID, actual
100                 .getSystemID());
101 
102         assertEquals("toString() is correct", expectedText, actual.toString());
103     }
104 }
105 
106 /*
107  * Redistribution and use of this software and associated documentation
108  * ("Software"), with or without modification, are permitted provided that the
109  * following conditions are met:
110  * 
111  * 1. Redistributions of source code must retain copyright statements and
112  * notices. Redistributions must also contain a copy of this document.
113  * 
114  * 2. Redistributions in binary form must reproduce the above copyright notice,
115  * this list of conditions and the following disclaimer in the documentation
116  * and/or other materials provided with the distribution.
117  * 
118  * 3. The name "DOM4J" must not be used to endorse or promote products derived
119  * from this Software without prior written permission of MetaStuff, Ltd. For
120  * written permission, please contact dom4j-info@metastuff.com.
121  * 
122  * 4. Products derived from this Software may not be called "DOM4J" nor may
123  * "DOM4J" appear in their names without prior written permission of MetaStuff,
124  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
125  * 
126  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
127  * 
128  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
129  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
130  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
131  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
132  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
133  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
134  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
135  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
136  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
137  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
138  * POSSIBILITY OF SUCH DAMAGE.
139  * 
140  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
141  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/dtd/package-frame.html0000644000175000017500000000212110242117707022662 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.dtd

org.dom4j.dtd

Classes

  • AttributeDeclTest
  • ElementDeclTest
  • ExternalEntityDeclTest
  • InternalEntityDeclTest
dom4j-1.6.1/docs/xref-test/org/dom4j/dtd/InternalEntityDeclTest.html0000644000175000017500000003367110242117747024622 0ustar ebourgebourg InternalEntityDeclTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dtd;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.AbstractTestCase;
13  
14  /***
15   * Tests the {@link InternalEntityDecl}functionality. Tests each of the
16   * property access methods and the serialization mechanisms. Correct parsing is
17   * tested by {@link DocTypeTest}.
18   * 
19   * <p>
20   * </p>
21   * 
22   * @author Bryan Thompson
23   * @author Maarten Coene
24   * @version $Revision: 1.3 $
25   * 
26   * @todo The dom4j documentation needs to describe what representation SHOULD be
27   *       generated by {@link InternalEntityDecl#toString()}.
28   */
29  public class InternalEntityDeclTest extends AbstractTestCase {
30      public static void main(String[] args) {
31          TestRunner.run(InternalEntityDeclTest.class);
32      }
33  
34      // Test case(s)
35      // -------------------------------------------------------------------------
36      public void testToString() {
37          InternalEntityDecl decl1 = new InternalEntityDecl("name", "value");
38          InternalEntityDecl decl2 = new InternalEntityDecl("%name", "value");
39  
40          assertEquals("<!ENTITY name \"value\">", decl1.toString());
41          assertEquals("<!ENTITY % name \"value\">", decl2.toString());
42      }
43  
44      /***
45       * Tests parameter entity declaration, such as
46       * 
47       * <pre>
48       * 
49       *  
50       *   &lt;!ENTITY % boolean &quot;( true | false )&quot;&gt;
51       *   
52       *  
53       * </pre>
54       * 
55       * Note: There is a required whitespace between the "%" and the name of the
56       * entity. This whitespace is required in the declaration and is not allowed
57       * when writing a reference to the entity, e.g., "%boolean;" is a legal
58       * reference but not "% boolean;".
59       * 
60       * <p>
61       * Note: The "%" is part of the parameter entity name as reported by the SAX
62       * API. See <a href="http://tinyurl.com/6xe9y">LexicalHandler </a>, which
63       * states:
64       * 
65       * <pre>
66       * 
67       *  
68       *   General entities are reported with their regular names,
69       *   parameter entities have '%' prepended to their names, and the
70       *   external DTD subset has the pseudo-entity name &quot;[dtd]&quot;.
71       *   
72       *  
73       * </pre>
74       * 
75       * </p>
76       */
77      public void testParameterEntity() {
78          String expectedName = "%boolean";
79  
80          String expectedValue = "( true | false )";
81  
82          String expectedText = "<!ENTITY % boolean \"( true | false )\">";
83  
84          InternalEntityDecl actual = new InternalEntityDecl(expectedName,
85                  expectedValue);
86  
87          assertEquals("name is correct", expectedName, actual.getName());
88  
89          assertEquals("value is correct", expectedValue, actual.getValue());
90  
91          assertEquals("toString() is correct", expectedText, actual.toString());
92      }
93  
94      /***
95       * Tests general entity declaration, such as:
96       * 
97       * <pre>
98       * 
99       *  
100      *   &lt;!ENTITY foo &quot;bar&quot;&gt;
101      *   
102      *  
103      * </pre>
104      */
105     public void testGeneralEntity() {
106         String expectedName = "foo";
107 
108         String expectedValue = "bar";
109 
110         String expectedText = "<!ENTITY foo \"bar\">";
111 
112         InternalEntityDecl actual = new InternalEntityDecl(expectedName,
113                 expectedValue);
114 
115         assertEquals("name is correct", expectedName, actual.getName());
116 
117         assertEquals("value is correct", expectedValue, actual.getValue());
118 
119         assertEquals("toString() is correct", expectedText, actual.toString());
120     }
121 }
122 
123 /*
124  * Redistribution and use of this software and associated documentation
125  * ("Software"), with or without modification, are permitted provided that the
126  * following conditions are met:
127  * 
128  * 1. Redistributions of source code must retain copyright statements and
129  * notices. Redistributions must also contain a copy of this document.
130  * 
131  * 2. Redistributions in binary form must reproduce the above copyright notice,
132  * this list of conditions and the following disclaimer in the documentation
133  * and/or other materials provided with the distribution.
134  * 
135  * 3. The name "DOM4J" must not be used to endorse or promote products derived
136  * from this Software without prior written permission of MetaStuff, Ltd. For
137  * written permission, please contact dom4j-info@metastuff.com.
138  * 
139  * 4. Products derived from this Software may not be called "DOM4J" nor may
140  * "DOM4J" appear in their names without prior written permission of MetaStuff,
141  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
142  * 
143  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
144  * 
145  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
146  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
147  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
148  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
149  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
150  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
151  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
152  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
153  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
154  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
155  * POSSIBILITY OF SUCH DAMAGE.
156  * 
157  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
158  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/ElementByIDTest.html0000644000175000017500000002152310242117627022375 0ustar ebourgebourg ElementByIDTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  /***
13   * Tests the elementByID() method
14   * 
15   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
16   * @version $Revision: 1.4 $
17   */
18  public class ElementByIDTest extends AbstractTestCase {
19      /*** Input XML file to read */
20      protected static final String INPUT_XML_FILE = "xml/test/elementByID.xml";
21  
22      public static void main(String[] args) {
23          TestRunner.run(ElementByIDTest.class);
24      }
25  
26      // Test case(s)
27      // -------------------------------------------------------------------------
28      public void testElementByID() throws Exception {
29          String id = "message";
30          Document document = getDocument(INPUT_XML_FILE);
31  
32          // test XPath
33          Element element = (Element) document.selectSingleNode("//*[@ID='" + id
34                  + "']");
35          assertTrue("Found element by ID: " + id, element != null);
36          assertEquals("ID is equal", id, element.attributeValue("ID"));
37  
38          // test with elementByID
39          element = document.elementByID(id);
40  
41          assertTrue("Found element by ID: " + id, element != null);
42          assertEquals("ID is equal", id, element.attributeValue("ID"));
43  
44          log("Found element: " + element.getText());
45  
46          element = document.elementByID("DoesNotExist");
47  
48          assertTrue("Found no element", element == null);
49      }
50  }
51  
52  /*
53   * Redistribution and use of this software and associated documentation
54   * ("Software"), with or without modification, are permitted provided that the
55   * following conditions are met:
56   * 
57   * 1. Redistributions of source code must retain copyright statements and
58   * notices. Redistributions must also contain a copy of this document.
59   * 
60   * 2. Redistributions in binary form must reproduce the above copyright notice,
61   * this list of conditions and the following disclaimer in the documentation
62   * and/or other materials provided with the distribution.
63   * 
64   * 3. The name "DOM4J" must not be used to endorse or promote products derived
65   * from this Software without prior written permission of MetaStuff, Ltd. For
66   * written permission, please contact dom4j-info@metastuff.com.
67   * 
68   * 4. Products derived from this Software may not be called "DOM4J" nor may
69   * "DOM4J" appear in their names without prior written permission of MetaStuff,
70   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
71   * 
72   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
73   * 
74   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
75   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
76   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
77   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
78   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
79   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
80   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
81   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
82   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
83   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
84   * POSSIBILITY OF SUCH DAMAGE.
85   * 
86   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
87   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/datatype/0000755000175000017500000000000012133227266020360 5ustar ebourgebourgdom4j-1.6.1/docs/xref-test/org/dom4j/datatype/DataTypesTest.html0000644000175000017500000004130410242117737024006 0ustar ebourgebourg DataTypesTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.datatype;
9   
10  import junit.textui.TestRunner;
11  
12  import java.math.BigDecimal;
13  import java.math.BigInteger;
14  import java.util.Calendar;
15  
16  import org.dom4j.DocumentFactory;
17  import org.dom4j.io.SAXReader;
18  
19  /***
20   * Test harness to test the various data types supported in the XML Schema Data
21   * Type integration.
22   * 
23   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
24   * @version $Revision: 1.4 $
25   */
26  public class DataTypesTest extends AbstractDataTypeTestCase {
27      public static void main(String[] args) {
28          TestRunner.run(DataTypesTest.class);
29      }
30  
31      // Test case(s)
32      // -------------------------------------------------------------------------
33      public void testgMonthDay() throws Exception {
34          testNodes("//gMonthDayTag", Calendar.class);
35      }
36  
37      public void testgDay() throws Exception {
38          testNodes("//gDayTag", Calendar.class);
39      }
40  
41      public void testgMonth() throws Exception {
42          testNodes("//gMonthTag", Calendar.class);
43      }
44  
45      public void testDate() throws Exception {
46          testNodes("//dateTag", Calendar.class);
47      }
48  
49      public void testTime() throws Exception {
50          testNodes("//timeTag", Calendar.class);
51      }
52  
53      public void testDateTime() throws Exception {
54          testNodes("//dateTimeTag", Calendar.class);
55      }
56  
57      public void testgYearMonth() throws Exception {
58          testNodes("//gYearMonthTag", Calendar.class);
59      }
60  
61      public void testgYear() throws Exception {
62          testNodes("//gYearTag", Calendar.class);
63      }
64  
65      public void testBoolean() throws Exception {
66          testNodes("//booleanTag", Boolean.class);
67      }
68  
69      public void testBase64Binary() throws Exception {
70          testNodes("//base64BinaryTag", byte[].class);
71      }
72  
73      public void testHexBinary() throws Exception {
74          testNodes("//hexBinaryTag", byte[].class);
75      }
76  
77      // Number types
78      public void testFloat() throws Exception {
79          testNodes("//floatTag", Float.class);
80      }
81  
82      public void testDouble() throws Exception {
83          testNodes("//doubleTag", Double.class);
84      }
85  
86      public void testDecimal() throws Exception {
87          testNodes("//decimalTag", BigDecimal.class);
88      }
89  
90      public void testInteger() throws Exception {
91          testNodes("//integerTag", BigInteger.class);
92      }
93  
94      public void testNonPositiveInteger() throws Exception {
95          testNodes("//nonPositiveIntegerTag", BigInteger.class);
96      }
97  
98      public void testNegativeInteger() throws Exception {
99          testNodes("//negativeIntegerTag", BigInteger.class);
100     }
101 
102     public void testLong() throws Exception {
103         testNodes("//longTag", Long.class);
104     }
105 
106     public void testInt() throws Exception {
107         testNodes("//intTag", Integer.class);
108     }
109 
110     public void testShort() throws Exception {
111         testNodes("//shortTag", Short.class);
112     }
113 
114     public void testByte() throws Exception {
115         testNodes("//byteTag", Byte.class);
116     }
117 
118     public void testNonNegativeInteger() throws Exception {
119         testNodes("//nonNegativeIntegerTag", BigInteger.class);
120     }
121 
122     public void testUnsignedLong() throws Exception {
123         testNodes("//unsignedLongTag", BigInteger.class);
124     }
125 
126     public void testUnsignedInt() throws Exception {
127         testNodes("//unsignedIntTag", Long.class);
128     }
129 
130     public void testUnsignedShort() throws Exception {
131         testNodes("//unsignedShortTag", Integer.class);
132     }
133 
134     public void testUnsignedByte() throws Exception {
135         testNodes("//unsignedByteTag", Short.class);
136     }
137 
138     public void testPositiveInteger() throws Exception {
139         testNodes("//positiveIntegerTag", BigInteger.class);
140     }
141 
142     // Implementation methods
143     // -------------------------------------------------------------------------
144     protected void setUp() throws Exception {
145         super.setUp();
146 
147         DocumentFactory factory = DatatypeDocumentFactory.getInstance();
148         SAXReader reader = new SAXReader(factory);
149         document = getDocument("/xml/test/schema/test.xml", reader);
150     }
151 }
152 
153 /*
154  * Redistribution and use of this software and associated documentation
155  * ("Software"), with or without modification, are permitted provided that the
156  * following conditions are met:
157  * 
158  * 1. Redistributions of source code must retain copyright statements and
159  * notices. Redistributions must also contain a copy of this document.
160  * 
161  * 2. Redistributions in binary form must reproduce the above copyright notice,
162  * this list of conditions and the following disclaimer in the documentation
163  * and/or other materials provided with the distribution.
164  * 
165  * 3. The name "DOM4J" must not be used to endorse or promote products derived
166  * from this Software without prior written permission of MetaStuff, Ltd. For
167  * written permission, please contact dom4j-info@metastuff.com.
168  * 
169  * 4. Products derived from this Software may not be called "DOM4J" nor may
170  * "DOM4J" appear in their names without prior written permission of MetaStuff,
171  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
172  * 
173  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
174  * 
175  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
176  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
177  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
178  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
179  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
180  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
181  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
182  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
183  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
184  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
185  * POSSIBILITY OF SUCH DAMAGE.
186  * 
187  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
188  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/datatype/package-summary.html0000644000175000017500000000627010242117763024340 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.datatype

Class Summary
AbstractDataTypeTestCase
AutoSchemaTest
DataTypesTest
Datatype2Test
ManualSchemaPrefixTest
ManualSchemaTest
SchemaParseTest
SetDataTest
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref-test/org/dom4j/datatype/SchemaParseTest.html0000644000175000017500000001760510242117553024306 0ustar ebourgebourg SchemaParseTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.datatype;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.AbstractTestCase;
13  import org.dom4j.Document;
14  import org.dom4j.io.SAXReader;
15  
16  /***
17   * Tests the SchemaParser based on a test case provided by Luis Pea Snchez
18   * 
19   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
20   * @version $Revision: 1.4 $
21   */
22  public class SchemaParseTest extends AbstractTestCase {
23      public static void main(String[] args) {
24          TestRunner.run(SchemaParseTest.class);
25      }
26  
27      // Test case(s)
28      // -------------------------------------------------------------------------
29      public void testParseSchema() throws Exception {
30          DatatypeDocumentFactory factory = new DatatypeDocumentFactory();
31  
32          SAXReader reader = new SAXReader();
33          reader.setDocumentFactory(factory);
34  
35          Document schema = getDocument("/xml/test/LuisSchema.xsd", reader);
36          factory.loadSchema(schema);
37  
38          log("Loaded the schema");
39  
40          // now load an instance document
41      }
42  }
43  
44  /*
45   * Redistribution and use of this software and associated documentation
46   * ("Software"), with or without modification, are permitted provided that the
47   * following conditions are met:
48   * 
49   * 1. Redistributions of source code must retain copyright statements and
50   * notices. Redistributions must also contain a copy of this document.
51   * 
52   * 2. Redistributions in binary form must reproduce the above copyright notice,
53   * this list of conditions and the following disclaimer in the documentation
54   * and/or other materials provided with the distribution.
55   * 
56   * 3. The name "DOM4J" must not be used to endorse or promote products derived
57   * from this Software without prior written permission of MetaStuff, Ltd. For
58   * written permission, please contact dom4j-info@metastuff.com.
59   * 
60   * 4. Products derived from this Software may not be called "DOM4J" nor may
61   * "DOM4J" appear in their names without prior written permission of MetaStuff,
62   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
63   * 
64   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
65   * 
66   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
67   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
68   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
69   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
70   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
71   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
72   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
73   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
74   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
75   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
76   * POSSIBILITY OF SUCH DAMAGE.
77   * 
78   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
79   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/datatype/AbstractDataTypeTestCase.html0000644000175000017500000002224410242117743026102 0ustar ebourgebourg AbstractDataTypeTestCase xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.datatype;
9   
10  import java.util.Iterator;
11  import java.util.List;
12  
13  import org.dom4j.AbstractTestCase;
14  import org.dom4j.Attribute;
15  import org.dom4j.Element;
16  import org.dom4j.Node;
17  
18  /***
19   * Abstract base class useful for implementation inheritence for testing XML
20   * Schema Data Type integration.
21   * 
22   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
23   * @version $Revision: 1.3 $
24   */
25  public class AbstractDataTypeTestCase extends AbstractTestCase {
26      // Implementation methods
27      // -------------------------------------------------------------------------
28      protected void testNodes(String xpath, Class type) {
29          List list = document.selectNodes(xpath);
30  
31          assertTrue("Results are not empty", !list.isEmpty());
32  
33          for (Iterator iter = list.iterator(); iter.hasNext();) {
34              Node node = (Node) iter.next();
35  
36              if (node instanceof Element) {
37                  Element element = (Element) node;
38                  testDataType(element, element.getData(), type);
39              } else if (node instanceof Attribute) {
40                  Attribute attribute = (Attribute) node;
41                  testDataType(attribute, attribute.getData(), type);
42              } else {
43                  assertTrue("Did not find an attribute or element: " + node,
44                          false);
45              }
46          }
47      }
48  
49      protected void testDataType(Node node, Object data, Class type) {
50          assertTrue("Data object is not null", data != null);
51  
52          assertTrue("Data object is of the correct type. Expected: "
53                  + type.getName() + " and found: " + data.getClass().getName(),
54                  type.isAssignableFrom(data.getClass()));
55      }
56  }
57  
58  /*
59   * Redistribution and use of this software and associated documentation
60   * ("Software"), with or without modification, are permitted provided that the
61   * following conditions are met:
62   * 
63   * 1. Redistributions of source code must retain copyright statements and
64   * notices. Redistributions must also contain a copy of this document.
65   * 
66   * 2. Redistributions in binary form must reproduce the above copyright notice,
67   * this list of conditions and the following disclaimer in the documentation
68   * and/or other materials provided with the distribution.
69   * 
70   * 3. The name "DOM4J" must not be used to endorse or promote products derived
71   * from this Software without prior written permission of MetaStuff, Ltd. For
72   * written permission, please contact dom4j-info@metastuff.com.
73   * 
74   * 4. Products derived from this Software may not be called "DOM4J" nor may
75   * "DOM4J" appear in their names without prior written permission of MetaStuff,
76   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
77   * 
78   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
79   * 
80   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
81   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
82   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
83   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
84   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
85   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
86   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
87   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
88   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
89   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
90   * POSSIBILITY OF SUCH DAMAGE.
91   * 
92   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
93   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/datatype/package-frame.html0000644000175000017500000000306710242117571023733 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.datatype

org.dom4j.datatype

Classes

  • AbstractDataTypeTestCase
  • AutoSchemaTest
  • DataTypesTest
  • Datatype2Test
  • ManualSchemaPrefixTest
  • ManualSchemaTest
  • SchemaParseTest
  • SetDataTest
dom4j-1.6.1/docs/xref-test/org/dom4j/datatype/Datatype2Test.html0000644000175000017500000006521010242117735023745 0ustar ebourgebourg Datatype2Test xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.datatype;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.StringReader;
13  import java.text.DateFormat;
14  import java.text.SimpleDateFormat;
15  import java.util.Calendar;
16  import java.util.GregorianCalendar;
17  import java.util.SimpleTimeZone;
18  import java.util.TimeZone;
19  
20  import org.dom4j.Attribute;
21  import org.dom4j.Document;
22  import org.dom4j.Element;
23  import org.dom4j.io.SAXReader;
24  
25  /***
26   * Test harness for XML Schema Datatypes support
27   * 
28   * @author Yuxin Ruan
29   * @version $Revision: 1.3 $
30   */
31  public class Datatype2Test extends AbstractDataTypeTestCase {
32      public static final int YEAR = 2001;
33  
34      public static final int MONTH = 10;
35  
36      public static final int DATE = 31;
37  
38      public static void main(String[] args) {
39          TestRunner.run(Datatype2Test.class);
40      }
41  
42      public void testSchema() throws Exception {
43          Document schema = getSchema();
44          validateDocumentWithSchema(schema);
45      }
46  
47      public void testSchemaWithNamedComplexType() throws Exception {
48          Document schema = getSchemaWithNamedComplexType();
49          validateDocumentWithSchema(schema);
50      }
51  
52      public void testSchemaWithReference() throws Exception {
53          Document schema = getSchemaWithReference();
54          validateDocumentWithSchema(schema);
55      }
56  
57      public void testSchemaWithNamedSimpleType() throws Exception {
58          Document schema = getSchemaWithNamedSimpleType();
59          validateDocumentWithSchema(schema);
60      }
61  
62      private void validateDocumentWithSchema(Document schema) throws Exception {
63          Document doc = getSource(schema);
64          Element root = doc.getRootElement();
65          validateLongAttribute(root);
66          validateFloatElement(root);
67          validateDateElement(root);
68      }
69  
70      private void validateLongAttribute(Element root) throws Exception {
71          Attribute attr = root.attribute("longAttribute");
72          Object attrData = attr.getData();
73          validateData("testLongAttribute", attrData, new Long(123));
74          System.out.println("retrieved attribute " + attrData);
75      }
76  
77      private void validateFloatElement(Element root) throws Exception {
78          Element elem = root.element("floatElement");
79          Object elemData = elem.getData();
80          validateData("testFloatElement", elemData, new Float(1.23));
81          System.out.println("retrieved element:" + elemData);
82      }
83  
84      private void validateDateElement(Element root) throws Exception {
85          Element elem = root.element("dateElement");
86          Object elemData = elem.getData();
87          Calendar expected = getDate();
88  
89          System.out.println("retrieved element:" + elemData);
90  
91          // don't compare the Calendar instances, compare their strings instead!
92          assertTrue(elemData instanceof Calendar);
93  
94          Calendar elemCal = (Calendar) elemData;
95  
96          DateFormat format = new SimpleDateFormat("MM/dd/yyyyZ");
97          format.setTimeZone(elemCal.getTimeZone());
98  
99          String elemStr = format.format(elemCal.getTime());
100 
101         format.setTimeZone(expected.getTimeZone());
102 
103         String expectedStr = format.format(expected.getTime());
104 
105         assertEquals("testDateElement", expectedStr, elemStr);
106     }
107 
108     private void validateData(String test, Object retrieved, Object expected)
109             throws Exception {
110         Class retrievedClass = retrieved.getClass();
111         Class expectedClass = expected.getClass();
112 
113         // compare class
114         if (!expectedClass.equals(retrievedClass)) {
115             String msg = "class mismatch in " + test + ":expected "
116                     + expectedClass + ", retrieved " + retrievedClass;
117             throw new Exception(msg);
118         }
119 
120         // compare value
121         if (!expected.equals(retrieved)) {
122             String msg = "value mismatch in " + test + ":expected " + expected
123                     + ", retrieved " + retrieved;
124             throw new Exception(msg);
125         }
126     }
127 
128     private Document getSource(Document schema) throws Exception {
129         StringBuffer b = new StringBuffer();
130         b.append("<?xml version='1.0' ?>");
131         b.append("<test xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'");
132         b.append("        xsi:noNamespaceSchemaLocation='long.xsd'");
133         b.append("        longAttribute='123' >");
134         b.append("    <floatElement>1.23</floatElement>");
135         b.append("    <dateElement>" + getDateString() + "</dateElement>");
136         b.append("</test>");
137 
138         StringReader in = new StringReader(b.toString());
139         DatatypeDocumentFactory docFactory = new DatatypeDocumentFactory();
140         docFactory.loadSchema(schema);
141 
142         SAXReader parser = new SAXReader(docFactory);
143 
144         return parser.read(in);
145     }
146 
147     private Document getSchema() throws Exception {
148         StringBuffer b = new StringBuffer();
149         b.append("<?xml version='1.0' encoding='UTF-8'?>");
150         b.append("<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>");
151         b.append(" <xsd:element name='test'>");
152         b.append("  <xsd:complexType>");
153         b.append("   <xsd:sequence>");
154         b.append("    <xsd:element name='floatElement' type='xsd:float' />");
155         b.append("    <xsd:element name='dateElement' type='xsd:date' />");
156         b.append("   </xsd:sequence>");
157         b.append("   <xsd:attribute name='longAttribute' type='xsd:long' />");
158         b.append("  </xsd:complexType>");
159         b.append(" </xsd:element>");
160         b.append("</xsd:schema>");
161 
162         StringReader in = new StringReader(b.toString());
163         SAXReader parser = new SAXReader();
164 
165         return parser.read(in);
166     }
167 
168     private Document getSchemaWithNamedComplexType() throws Exception {
169         StringBuffer b = new StringBuffer();
170         b.append("<?xml version='1.0' encoding='UTF-8'?>");
171         b.append("<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>");
172         b.append(" <xsd:element name='test' type='TimePeriodType' />");
173         b.append(" <xsd:complexType name='TimePeriodType'>");
174         b.append("  <xsd:sequence>");
175         b.append("   <xsd:element name='floatElement' type='xsd:float' />");
176         b.append("   <xsd:element name='dateElement' type='xsd:date' />");
177         b.append("  </xsd:sequence>");
178         b.append("  <xsd:attribute name='longAttribute' type='xsd:long' />");
179         b.append(" </xsd:complexType>");
180         b.append("</xsd:schema>");
181 
182         StringReader in = new StringReader(b.toString());
183         SAXReader parser = new SAXReader();
184 
185         return parser.read(in);
186     }
187 
188     private Document getSchemaWithReference() throws Exception {
189         StringBuffer b = new StringBuffer();
190         b.append("<?xml version='1.0' encoding='UTF-8'?>");
191         b.append("<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>");
192         b.append(" <xsd:element name='test' type='TimePeriodType' />");
193         b.append(" <xsd:complexType name='TimePeriodType'>");
194         b.append("  <xsd:sequence>");
195         b.append("   <xsd:element name='floatElement' type='xsd:float' />");
196         b.append("   <xsd:element ref='dateElement' />");
197         b.append("  </xsd:sequence>");
198         b.append("  <xsd:attribute name='longAttribute' type='xsd:long' />");
199         b.append(" </xsd:complexType>");
200         b.append(" <xsd:element name='dateElement' type='xsd:date' />");
201         b.append("</xsd:schema>");
202 
203         StringReader in = new StringReader(b.toString());
204         SAXReader parser = new SAXReader();
205 
206         return parser.read(in);
207     }
208 
209     private Document getSchemaWithNamedSimpleType() throws Exception {
210         StringBuffer b = new StringBuffer();
211         b.append("<?xml version='1.0' encoding='UTF-8'?>");
212         b.append("<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>");
213         b.append(" <xsd:element name='test'>");
214         b.append("  <xsd:complexType>");
215         b.append("   <xsd:sequence>");
216         b.append("    <xsd:element name='floatElement' type='xsd:float' />");
217         b.append("    <xsd:element name='dateElement' type='dateType' />");
218         b.append("   </xsd:sequence>");
219         b.append("   <xsd:attribute name='longAttribute' type='xsd:long' />");
220         b.append("  </xsd:complexType>");
221         b.append(" </xsd:element>");
222         b.append(" <xsd:simpleType name='dateType'>");
223         b.append("  <xsd:restriction base='xsd:date'>");
224         b.append("  </xsd:restriction>");
225         b.append(" </xsd:simpleType>");
226         b.append("</xsd:schema>");
227 
228         StringReader in = new StringReader(b.toString());
229         SAXReader parser = new SAXReader();
230 
231         return parser.read(in);
232     }
233 
234     private static String getDateString() {
235         // return dateTime in ISO8601 format
236         String yyyy = Integer.toString(YEAR);
237         String mm = Integer.toString(MONTH);
238         String dd = Integer.toString(DATE);
239 
240         return yyyy + "-" + mm + "-" + dd + "Z";
241     }
242 
243     private static Calendar getDate() {
244         Calendar calendar = new GregorianCalendar();
245         calendar.clear();
246         calendar.set(Calendar.YEAR, YEAR);
247         calendar.set(Calendar.MONTH, MONTH - 1);
248         calendar.set(Calendar.DAY_OF_MONTH, DATE);
249         calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
250         calendar.setTimeZone(new SimpleTimeZone(0, "XSD 'Z' timezone"));
251 
252         return calendar;
253     }
254 }
255 
256 /*
257  * Redistribution and use of this software and associated documentation
258  * ("Software"), with or without modification, are permitted provided that the
259  * following conditions are met:
260  * 
261  * 1. Redistributions of source code must retain copyright statements and
262  * notices. Redistributions must also contain a copy of this document.
263  * 
264  * 2. Redistributions in binary form must reproduce the above copyright notice,
265  * this list of conditions and the following disclaimer in the documentation
266  * and/or other materials provided with the distribution.
267  * 
268  * 3. The name "DOM4J" must not be used to endorse or promote products derived
269  * from this Software without prior written permission of MetaStuff, Ltd. For
270  * written permission, please contact dom4j-info@metastuff.com.
271  * 
272  * 4. Products derived from this Software may not be called "DOM4J" nor may
273  * "DOM4J" appear in their names without prior written permission of MetaStuff,
274  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
275  * 
276  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
277  * 
278  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
279  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
280  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
281  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
282  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
283  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
284  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
285  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
286  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
287  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
288  * POSSIBILITY OF SUCH DAMAGE.
289  * 
290  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
291  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/datatype/SetDataTest.html0000644000175000017500000004266210242117546023443 0ustar ebourgebourg SetDataTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.datatype;
9   
10  import junit.textui.TestRunner;
11  
12  import java.math.BigInteger;
13  
14  import org.dom4j.AbstractTestCase;
15  import org.dom4j.Attribute;
16  import org.dom4j.Document;
17  import org.dom4j.Element;
18  import org.dom4j.Namespace;
19  import org.dom4j.QName;
20  
21  /***
22   * Tests setting the value of datatype aware element or attribute value
23   * 
24   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
25   * @version $Revision: 1.4 $
26   */
27  public class SetDataTest extends AbstractTestCase {
28      private DatatypeDocumentFactory factory = new DatatypeDocumentFactory();
29  
30      public static void main(String[] args) {
31          TestRunner.run(SetDataTest.class);
32      }
33  
34      // Test case(s)
35      // -------------------------------------------------------------------------
36      public void testAttribute() throws Exception {
37          QName personName = factory.createQName("person");
38          QName ageName = factory.createQName("age");
39  
40          Element person = factory.createElement(personName);
41  
42          person.addAttribute(ageName, "10");
43  
44          Attribute age = person.attribute(ageName);
45  
46          assertTrue("Created DatatypeAttribute not correct",
47                  age instanceof DatatypeAttribute);
48  
49          log("Found attribute: " + age);
50  
51          Object data = age.getData();
52          Object expected = new BigInteger("10");
53  
54          assertEquals("Data is correct type", BigInteger.class, data.getClass());
55  
56          assertEquals("Set age correctly", expected, data);
57  
58          age.setValue("32");
59          data = age.getData();
60          expected = new BigInteger("32");
61  
62          assertEquals("Set age correctly", expected, data);
63  
64          /***
65           * not sure if numeric types should be round tripped back to BigDecimal
66           * (say) age.setData( new Long( 21 ) ); data = age.getData(); expected =
67           * new BigInteger( "21" ); assertEquals( "Set age correctly", expected,
68           * data );
69           */
70  
71          // now lets set an invalid value
72          try {
73              age.setValue("abc");
74              fail("Appeared to set an invalid value");
75          } catch (IllegalArgumentException e) {
76          }
77      }
78  
79      public void testAttributeWithNamespace() throws Exception {
80          QName personName = factory.createQName("person", "t", "urn://testing");
81          QName ageName = factory.createQName("age", "t", "urn://testing");
82  
83          Element person = factory.createElement(personName);
84  
85          person.addAttribute(ageName, "10");
86  
87          Attribute age = person.attribute(ageName);
88  
89          assertTrue("Created DatatypeAttribute not correct",
90                  age instanceof DatatypeAttribute);
91  
92          log("Found attribute: " + age);
93  
94          Object data = age.getData();
95          Object expected = new BigInteger("10");
96  
97          assertEquals("Data is correct type", BigInteger.class, data.getClass());
98  
99          assertEquals("Set age correctly", expected, data);
100 
101         age.setValue("32");
102         data = age.getData();
103         expected = new BigInteger("32");
104 
105         assertEquals("Set age correctly", expected, data);
106 
107         try {
108             age.setValue("abc");
109             fail("Appeared to set an invalid value");
110         } catch (IllegalArgumentException e) {
111         }
112     }
113 
114     public void testElement() throws Exception {
115         QName personName = factory.createQName("person");
116         QName numberOfCarsName = factory.createQName("numberOfCars");
117 
118         Element person = factory.createElement(personName);
119 
120         Element cars = person.addElement(numberOfCarsName);
121 
122         log("Found element: " + cars);
123 
124         Object expected = new Short((short) 10);
125         cars.setData(expected);
126 
127         Object data = cars.getData();
128 
129         assertEquals("Data is correct type", Short.class, data.getClass());
130         assertEquals("Set cars correctly", expected, data);
131 
132         cars.setData(new Short((short) 32));
133         data = cars.getData();
134         expected = new Short((short) 32);
135 
136         assertEquals("Set cars correctly", expected, data);
137 
138         cars.setText("34");
139         data = cars.getData();
140         expected = new Short((short) 34);
141 
142         assertEquals("Set cars correctly", expected, data);
143 
144         // now lets set an invalid value
145         try {
146             cars.setText("abc");
147             fail("Appeared to set an invalid value");
148         } catch (IllegalArgumentException e) {
149         }
150     }
151 
152     // Implementation methods
153     // -------------------------------------------------------------------------
154     protected void setUp() throws Exception {
155         super.setUp();
156 
157         Document schema = getDocument("/xml/test/schema/personal.xsd");
158         factory.loadSchema(schema);
159 
160         Namespace ns = new Namespace("t", "urn://testing");
161         factory.loadSchema(schema, ns);
162     }
163 }
164 
165 /*
166  * Redistribution and use of this software and associated documentation
167  * ("Software"), with or without modification, are permitted provided that the
168  * following conditions are met:
169  * 
170  * 1. Redistributions of source code must retain copyright statements and
171  * notices. Redistributions must also contain a copy of this document.
172  * 
173  * 2. Redistributions in binary form must reproduce the above copyright notice,
174  * this list of conditions and the following disclaimer in the documentation
175  * and/or other materials provided with the distribution.
176  * 
177  * 3. The name "DOM4J" must not be used to endorse or promote products derived
178  * from this Software without prior written permission of MetaStuff, Ltd. For
179  * written permission, please contact dom4j-info@metastuff.com.
180  * 
181  * 4. Products derived from this Software may not be called "DOM4J" nor may
182  * "DOM4J" appear in their names without prior written permission of MetaStuff,
183  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
184  * 
185  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
186  * 
187  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
188  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
189  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
190  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
191  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
192  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
193  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
194  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
195  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
196  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
197  * POSSIBILITY OF SUCH DAMAGE.
198  * 
199  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
200  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/datatype/ManualSchemaPrefixTest.html0000644000175000017500000001723610242117737025633 0ustar ebourgebourg ManualSchemaPrefixTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.datatype;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.Document;
13  import org.dom4j.DocumentFactory;
14  
15  /***
16   * Test harness for the XML Schema Data Type integration. These tests manually
17   * load the schemas using prefixes in the XSD file.
18   * 
19   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
20   * @version $Revision: 1.4 $
21   */
22  public class ManualSchemaPrefixTest extends AutoSchemaTest {
23      public static void main(String[] args) {
24          TestRunner.run(ManualSchemaPrefixTest.class);
25      }
26  
27      // Implementation methods
28      // -------------------------------------------------------------------------
29      protected DocumentFactory loadDocumentFactory() throws Exception {
30          DatatypeDocumentFactory factory = new DatatypeDocumentFactory();
31  
32          Document schemaDocument = 
33                  getDocument("/xml/test/schema/personal-prefix.xsd");
34          factory.loadSchema(schemaDocument);
35  
36          return factory;
37      }
38  }
39  
40  /*
41   * Redistribution and use of this software and associated documentation
42   * ("Software"), with or without modification, are permitted provided that the
43   * following conditions are met:
44   * 
45   * 1. Redistributions of source code must retain copyright statements and
46   * notices. Redistributions must also contain a copy of this document.
47   * 
48   * 2. Redistributions in binary form must reproduce the above copyright notice,
49   * this list of conditions and the following disclaimer in the documentation
50   * and/or other materials provided with the distribution.
51   * 
52   * 3. The name "DOM4J" must not be used to endorse or promote products derived
53   * from this Software without prior written permission of MetaStuff, Ltd. For
54   * written permission, please contact dom4j-info@metastuff.com.
55   * 
56   * 4. Products derived from this Software may not be called "DOM4J" nor may
57   * "DOM4J" appear in their names without prior written permission of MetaStuff,
58   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
59   * 
60   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
61   * 
62   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
63   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
65   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
66   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
67   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
68   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
69   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
70   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
71   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
72   * POSSIBILITY OF SUCH DAMAGE.
73   * 
74   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
75   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/datatype/AutoSchemaTest.html0000644000175000017500000002454210242117544024142 0ustar ebourgebourg AutoSchemaTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.datatype;
9   
10  import junit.textui.TestRunner;
11  
12  import java.math.BigInteger;
13  import java.util.Calendar;
14  
15  import org.dom4j.DocumentFactory;
16  import org.dom4j.io.SAXReader;
17  
18  /***
19   * Test harness for the XML Schema Data Type integration. These tests use
20   * auto-loading of the XML Schema document
21   * 
22   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
23   * @version $Revision: 1.4 $
24   */
25  public class AutoSchemaTest extends AbstractDataTypeTestCase {
26      public static void main(String[] args) {
27          TestRunner.run(AutoSchemaTest.class);
28      }
29  
30      // Test case(s)
31      // -------------------------------------------------------------------------
32      public void testIntAttribute() throws Exception {
33          testNodes("//person/@x", Integer.class);
34      }
35  
36      public void testIntElement() throws Exception {
37          testNodes("//person/salary", Integer.class);
38      }
39  
40      public void testString() throws Exception {
41          testNodes("//person/note", String.class);
42      }
43  
44      public void testDate() throws Exception {
45          testNodes("//person/@d", Calendar.class);
46      }
47  
48      public void testDateTime() throws Exception {
49          testNodes("//person/@dt", Calendar.class);
50      }
51  
52      public void testInteger() throws Exception {
53          testNodes("//person/@age", BigInteger.class);
54      }
55  
56      // Implementation methods
57      // -------------------------------------------------------------------------
58      protected void setUp() throws Exception {
59          super.setUp();
60  
61          DocumentFactory factory = loadDocumentFactory();
62          SAXReader reader = new SAXReader(factory);
63          document = getDocument(getDocumentURI(), reader);
64      }
65  
66      protected String getDocumentURI() {
67          return "/xml/test/schema/personal-schema.xml";
68      }
69  
70      protected DocumentFactory loadDocumentFactory() throws Exception {
71          return DatatypeDocumentFactory.getInstance();
72      }
73  }
74  
75  /*
76   * Redistribution and use of this software and associated documentation
77   * ("Software"), with or without modification, are permitted provided that the
78   * following conditions are met:
79   * 
80   * 1. Redistributions of source code must retain copyright statements and
81   * notices. Redistributions must also contain a copy of this document.
82   * 
83   * 2. Redistributions in binary form must reproduce the above copyright notice,
84   * this list of conditions and the following disclaimer in the documentation
85   * and/or other materials provided with the distribution.
86   * 
87   * 3. The name "DOM4J" must not be used to endorse or promote products derived
88   * from this Software without prior written permission of MetaStuff, Ltd. For
89   * written permission, please contact dom4j-info@metastuff.com.
90   * 
91   * 4. Products derived from this Software may not be called "DOM4J" nor may
92   * "DOM4J" appear in their names without prior written permission of MetaStuff,
93   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
94   * 
95   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
96   * 
97   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
98   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
99   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
100  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
101  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
102  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
103  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
104  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
105  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
106  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
107  * POSSIBILITY OF SUCH DAMAGE.
108  * 
109  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
110  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/datatype/ManualSchemaTest.html0000644000175000017500000001751610242117712024447 0ustar ebourgebourg ManualSchemaTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.datatype;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.Document;
13  import org.dom4j.DocumentFactory;
14  
15  /***
16   * Test harness for the XML Schema Data Type integration. These tests manually
17   * load the schemas
18   * 
19   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
20   * @version $Revision: 1.4 $
21   */
22  public class ManualSchemaTest extends AutoSchemaTest {
23      public static void main(String[] args) {
24          TestRunner.run(ManualSchemaTest.class);
25      }
26  
27      // Implementation methods
28      // -------------------------------------------------------------------------
29      protected String getDocumentURI() {
30          return "/xml/test/schema/personal.xml";
31      }
32  
33      protected DocumentFactory loadDocumentFactory() throws Exception {
34          DatatypeDocumentFactory factory = new DatatypeDocumentFactory();
35  
36          Document schemaDocument = getDocument("/xml/test/schema/personal.xsd");
37          factory.loadSchema(schemaDocument);
38  
39          return factory;
40      }
41  }
42  
43  /*
44   * Redistribution and use of this software and associated documentation
45   * ("Software"), with or without modification, are permitted provided that the
46   * following conditions are met:
47   * 
48   * 1. Redistributions of source code must retain copyright statements and
49   * notices. Redistributions must also contain a copy of this document.
50   * 
51   * 2. Redistributions in binary form must reproduce the above copyright notice,
52   * this list of conditions and the following disclaimer in the documentation
53   * and/or other materials provided with the distribution.
54   * 
55   * 3. The name "DOM4J" must not be used to endorse or promote products derived
56   * from this Software without prior written permission of MetaStuff, Ltd. For
57   * written permission, please contact dom4j-info@metastuff.com.
58   * 
59   * 4. Products derived from this Software may not be called "DOM4J" nor may
60   * "DOM4J" appear in their names without prior written permission of MetaStuff,
61   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
62   * 
63   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
64   * 
65   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
66   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
67   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
68   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
69   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
70   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
71   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
72   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
73   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
74   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
75   * POSSIBILITY OF SUCH DAMAGE.
76   * 
77   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
78   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/NullAttributesTest.html0000644000175000017500000002630510242117736023261 0ustar ebourgebourg NullAttributesTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  /***
13   * Tests the use of null attribute values
14   * 
15   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
16   * @version $Revision: 1.3 $
17   */
18  public class NullAttributesTest extends AbstractTestCase {
19      protected DocumentFactory factory = DocumentFactory.getInstance();
20  
21      protected Document document = factory.createDocument();
22  
23      protected Element element = document.addElement("root");
24  
25      public static void main(String[] args) {
26          TestRunner.run(NullAttributesTest.class);
27      }
28  
29      // Test case(s)
30      // -------------------------------------------------------------------------
31      public void testStringNames() throws Exception {
32          element.addAttribute("foo", null);
33  
34          Attribute attribute = element.attribute("foo");
35          assertTrue(attribute == null);
36  
37          element.addAttribute("foo", "123");
38          attribute = element.attribute("foo");
39          assertTrue(attribute != null);
40  
41          element.addAttribute("foo", null);
42          attribute = element.attribute("foo");
43          assertTrue(attribute == null);
44      }
45  
46      public void testQNames() throws Exception {
47          QName bar = QName.get("bar");
48  
49          element.addAttribute(bar, null);
50  
51          Attribute attribute = element.attribute(bar);
52          assertTrue(attribute == null);
53  
54          element.addAttribute(bar, "123");
55          attribute = element.attribute(bar);
56          assertTrue(attribute != null);
57  
58          element.addAttribute(bar, null);
59          attribute = element.attribute(bar);
60          assertTrue(attribute == null);
61      }
62  
63      public void testAttributes() throws Exception {
64          Attribute attribute = factory.createAttribute(element, "v", null);
65  
66          assertTrue(attribute.getText() == null);
67          assertTrue(attribute.getValue() == null);
68  
69          element.add(attribute);
70          attribute = element.attribute("v");
71          assertTrue(attribute == null);
72  
73          attribute = factory.createAttribute(element, "v", "123");
74          element.add(attribute);
75          attribute = element.attribute("v");
76          assertTrue(attribute != null);
77  
78          attribute = factory.createAttribute(element, "v", null);
79          element.add(attribute);
80          attribute = element.attribute("v");
81          assertTrue(attribute == null);
82      }
83  }
84  
85  /*
86   * Redistribution and use of this software and associated documentation
87   * ("Software"), with or without modification, are permitted provided that the
88   * following conditions are met:
89   * 
90   * 1. Redistributions of source code must retain copyright statements and
91   * notices. Redistributions must also contain a copy of this document.
92   * 
93   * 2. Redistributions in binary form must reproduce the above copyright notice,
94   * this list of conditions and the following disclaimer in the documentation
95   * and/or other materials provided with the distribution.
96   * 
97   * 3. The name "DOM4J" must not be used to endorse or promote products derived
98   * from this Software without prior written permission of MetaStuff, Ltd. For
99   * written permission, please contact dom4j-info@metastuff.com.
100  * 
101  * 4. Products derived from this Software may not be called "DOM4J" nor may
102  * "DOM4J" appear in their names without prior written permission of MetaStuff,
103  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
104  * 
105  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
106  * 
107  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
108  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
109  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
110  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
111  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
112  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
113  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
114  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
115  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
116  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
117  * POSSIBILITY OF SUCH DAMAGE.
118  * 
119  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
120  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/NormalizeTest.html0000644000175000017500000002056610242117703022235 0ustar ebourgebourg NormalizeTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  /***
13   * A test harness for the normalize() method
14   * 
15   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
16   * @version $Revision: 1.3 $
17   */
18  public class NormalizeTest extends AbstractTestCase {
19      public static void main(String[] args) {
20          TestRunner.run(NormalizeTest.class);
21      }
22  
23      // Test case(s)
24      // -------------------------------------------------------------------------
25      public void testNormalize() throws Exception {
26          String text = document.asXML();
27  
28          document.normalize();
29  
30          String normalizedText = document.asXML();
31  
32          log("Initial: " + text);
33          log("Normalized: " + normalizedText);
34  
35          String value = document.valueOf("/dummy/full");
36          assertEquals("Should not trim text", " node ", value);
37      }
38  
39      // Implementation methods
40      // -------------------------------------------------------------------------
41      protected void setUp() throws Exception {
42          super.setUp();
43  
44          String xml = "<dummy> <full> node </full> with text "
45                  + "<and>another node</and> </dummy>";
46          document = DocumentHelper.parseText(xml);
47      }
48  }
49  
50  /*
51   * Redistribution and use of this software and associated documentation
52   * ("Software"), with or without modification, are permitted provided that the
53   * following conditions are met:
54   * 
55   * 1. Redistributions of source code must retain copyright statements and
56   * notices. Redistributions must also contain a copy of this document.
57   * 
58   * 2. Redistributions in binary form must reproduce the above copyright notice,
59   * this list of conditions and the following disclaimer in the documentation
60   * and/or other materials provided with the distribution.
61   * 
62   * 3. The name "DOM4J" must not be used to endorse or promote products derived
63   * from this Software without prior written permission of MetaStuff, Ltd. For
64   * written permission, please contact dom4j-info@metastuff.com.
65   * 
66   * 4. Products derived from this Software may not be called "DOM4J" nor may
67   * "DOM4J" appear in their names without prior written permission of MetaStuff,
68   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
69   * 
70   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
71   * 
72   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
73   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
74   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
75   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
76   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
77   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
78   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
79   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
80   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
81   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
82   * POSSIBILITY OF SUCH DAMAGE.
83   * 
84   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
85   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/0000755000175000017500000000000012133227266017671 5ustar ebourgebourgdom4j-1.6.1/docs/xref-test/org/dom4j/xpath/FilterTest.html0000644000175000017500000002311010242117721022632 0ustar ebourgebourg FilterTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.Iterator;
13  import java.util.List;
14  
15  import org.dom4j.AbstractTestCase;
16  import org.dom4j.DocumentHelper;
17  import org.dom4j.Node;
18  import org.dom4j.NodeFilter;
19  
20  /***
21   * Test harness for XPath filters
22   * 
23   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
24   * @version $Revision: 1.3 $
25   */
26  public class FilterTest extends AbstractTestCase {
27      protected static String[] paths = {".[name()='author']",
28              ".[name()='XXXX']", ".[.='James Strachan']", ".[.='XXXX']"};
29  
30      public static void main(String[] args) {
31          TestRunner.run(FilterTest.class);
32      }
33  
34      // Test case(s)
35      // -------------------------------------------------------------------------
36      public void testXPaths() throws Exception {
37          int size = paths.length;
38  
39          for (int i = 0; i < size; i++) {
40              testXPath(paths[i]);
41          }
42      }
43  
44      // Implementation methods
45      // -------------------------------------------------------------------------
46      protected void testXPath(String xpathExpression) {
47          NodeFilter nodeFilter = DocumentHelper
48                  .createXPathFilter(xpathExpression);
49          assertTrue("No NodeFilter object was created", nodeFilter != null);
50  
51          List list = document.selectNodes("//author");
52  
53          for (Iterator iter = list.iterator(); iter.hasNext();) {
54              Node node = (Node) iter.next();
55  
56              if (nodeFilter.matches(node)) {
57                  log("Matches node: " + node.asXML());
58              } else {
59                  log("No match for node: " + node.asXML());
60              }
61          }
62      }
63  }
64  
65  /*
66   * Redistribution and use of this software and associated documentation
67   * ("Software"), with or without modification, are permitted provided that the
68   * following conditions are met:
69   * 
70   * 1. Redistributions of source code must retain copyright statements and
71   * notices. Redistributions must also contain a copy of this document.
72   * 
73   * 2. Redistributions in binary form must reproduce the above copyright notice,
74   * this list of conditions and the following disclaimer in the documentation
75   * and/or other materials provided with the distribution.
76   * 
77   * 3. The name "DOM4J" must not be used to endorse or promote products derived
78   * from this Software without prior written permission of MetaStuff, Ltd. For
79   * written permission, please contact dom4j-info@metastuff.com.
80   * 
81   * 4. Products derived from this Software may not be called "DOM4J" nor may
82   * "DOM4J" appear in their names without prior written permission of MetaStuff,
83   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
84   * 
85   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
86   * 
87   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
88   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
89   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
90   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
91   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
92   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
93   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
94   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
95   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
96   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
97   * POSSIBILITY OF SUCH DAMAGE.
98   * 
99   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
100  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/BadPathTest.html0000644000175000017500000002126510242117750022723 0ustar ebourgebourg BadPathTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.AbstractTestCase;
13  import org.dom4j.XPath;
14  
15  /***
16   * Tests bad XPath expressions
17   * 
18   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
19   * @version $Revision: 1.3 $
20   */
21  public class BadPathTest extends AbstractTestCase {
22      private String[] paths = {"+", "/foo/bar/"};
23  
24      public static void main(String[] args) {
25          TestRunner.run(BadPathTest.class);
26      }
27  
28      // Test case(s)
29      // -------------------------------------------------------------------------
30      public void testBadPaths() throws Exception {
31          for (int i = 0, size = paths.length; i < size; i++) {
32              String path = paths[i];
33              testBadPath(path);
34          }
35      }
36  
37      protected void testBadPath(String path) throws Exception {
38          try {
39              document.selectObject(path);
40  
41              fail("Should have thrown exception for: " + path);
42          } catch (Exception e) {
43              log("Successfully caught: " + e);
44          }
45  
46          try {
47              XPath xpath = document.createXPath(path);
48  
49              fail("Should have thrown exception for: " + path);
50          } catch (Exception e) {
51              log("Successfully caught: " + e);
52          }
53      }
54  }
55  
56  /*
57   * Redistribution and use of this software and associated documentation
58   * ("Software"), with or without modification, are permitted provided that the
59   * following conditions are met:
60   * 
61   * 1. Redistributions of source code must retain copyright statements and
62   * notices. Redistributions must also contain a copy of this document.
63   * 
64   * 2. Redistributions in binary form must reproduce the above copyright notice,
65   * this list of conditions and the following disclaimer in the documentation
66   * and/or other materials provided with the distribution.
67   * 
68   * 3. The name "DOM4J" must not be used to endorse or promote products derived
69   * from this Software without prior written permission of MetaStuff, Ltd. For
70   * written permission, please contact dom4j-info@metastuff.com.
71   * 
72   * 4. Products derived from this Software may not be called "DOM4J" nor may
73   * "DOM4J" appear in their names without prior written permission of MetaStuff,
74   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
75   * 
76   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
77   * 
78   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
79   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
81   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
82   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
83   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
84   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
85   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
86   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
87   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
88   * POSSIBILITY OF SUCH DAMAGE.
89   * 
90   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
91   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/TextTest.html0000644000175000017500000002310410242117713022335 0ustar ebourgebourg TextTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.Iterator;
13  import java.util.List;
14  
15  import org.dom4j.AbstractTestCase;
16  import org.dom4j.Text;
17  
18  /***
19   * Test harness for the text() function
20   * 
21   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
22   * @version $Revision: 1.3 $
23   */
24  public class TextTest extends AbstractTestCase {
25      protected static String[] paths = {"text()", "//author/text()"};
26  
27      public static void main(String[] args) {
28          TestRunner.run(TextTest.class);
29      }
30  
31      // Test case(s)
32      // -------------------------------------------------------------------------
33      public void testXPaths() throws Exception {
34          int size = paths.length;
35  
36          for (int i = 0; i < size; i++) {
37              testXPath(paths[i]);
38          }
39      }
40  
41      // Implementation methods
42      // -------------------------------------------------------------------------
43      protected void testXPath(String xpath) {
44          List list = document.selectNodes(xpath);
45  
46          for (Iterator iter = list.iterator(); iter.hasNext();) {
47              Object object = iter.next();
48  
49              log("Found Result: " + object);
50  
51              assertTrue("Results not Text objects", object instanceof Text);
52  
53              Text text = (Text) object;
54  
55              assertTrue("Results should support the parent relationship", text
56                      .supportsParent());
57              assertTrue(
58                      "Results should contain reference to the parent element",
59                      text.getParent() != null);
60              assertTrue("Results should not reference to the owning document",
61                      text.getDocument() != null);
62          }
63      }
64  }
65  
66  /*
67   * Redistribution and use of this software and associated documentation
68   * ("Software"), with or without modification, are permitted provided that the
69   * following conditions are met:
70   * 
71   * 1. Redistributions of source code must retain copyright statements and
72   * notices. Redistributions must also contain a copy of this document.
73   * 
74   * 2. Redistributions in binary form must reproduce the above copyright notice,
75   * this list of conditions and the following disclaimer in the documentation
76   * and/or other materials provided with the distribution.
77   * 
78   * 3. The name "DOM4J" must not be used to endorse or promote products derived
79   * from this Software without prior written permission of MetaStuff, Ltd. For
80   * written permission, please contact dom4j-info@metastuff.com.
81   * 
82   * 4. Products derived from this Software may not be called "DOM4J" nor may
83   * "DOM4J" appear in their names without prior written permission of MetaStuff,
84   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
85   * 
86   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
87   * 
88   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
89   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
90   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
91   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
92   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
93   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
94   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
95   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
96   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
97   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
98   * POSSIBILITY OF SUCH DAMAGE.
99   * 
100  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
101  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/UriMapTest.html0000644000175000017500000002150310242117736022614 0ustar ebourgebourg UriMapTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.File;
13  import java.util.HashMap;
14  import java.util.Map;
15  
16  import org.dom4j.AbstractTestCase;
17  import org.dom4j.Node;
18  import org.dom4j.XPath;
19  import org.dom4j.io.SAXReader;
20  
21  /***
22   * Tests the use of a Map for defining namespace URIs
23   * 
24   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
25   * @version $Revision: 1.3 $
26   */
27  public class UriMapTest extends AbstractTestCase {
28      public static void main(String[] args) {
29          TestRunner.run(UriMapTest.class);
30      }
31  
32      // Test case(s)
33      // -------------------------------------------------------------------------
34      public void testURIMap() throws Exception {
35          Map uris = new HashMap();
36          uris.put("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/");
37          uris.put("m", "urn:xmethodsBabelFish");
38  
39          String path = "/SOAP-ENV:Envelope/SOAP-ENV:Body/m:BabelFish";
40          XPath xpath = document.createXPath(path);
41          xpath.setNamespaceURIs(uris);
42  
43          Node babelfish = xpath.selectSingleNode(document);
44  
45          // log( "Found: " + babelfish );
46          assertTrue("Found valid node", babelfish != null);
47      }
48  
49      protected void setUp() throws Exception {
50          super.setUp();
51          document = new SAXReader().read(new File("xml/soap.xml"));
52      }
53  }
54  
55  /*
56   * Redistribution and use of this software and associated documentation
57   * ("Software"), with or without modification, are permitted provided that the
58   * following conditions are met:
59   * 
60   * 1. Redistributions of source code must retain copyright statements and
61   * notices. Redistributions must also contain a copy of this document.
62   * 
63   * 2. Redistributions in binary form must reproduce the above copyright notice,
64   * this list of conditions and the following disclaimer in the documentation
65   * and/or other materials provided with the distribution.
66   * 
67   * 3. The name "DOM4J" must not be used to endorse or promote products derived
68   * from this Software without prior written permission of MetaStuff, Ltd. For
69   * written permission, please contact dom4j-info@metastuff.com.
70   * 
71   * 4. Products derived from this Software may not be called "DOM4J" nor may
72   * "DOM4J" appear in their names without prior written permission of MetaStuff,
73   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
74   * 
75   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
76   * 
77   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
78   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
79   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
80   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
81   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
82   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
83   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
84   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
85   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
86   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
87   * POSSIBILITY OF SUCH DAMAGE.
88   * 
89   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
90   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/package-summary.html0000644000175000017500000001110110242117713023631 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.xpath

Class Summary
AttributeTest
BadPathTest
BooleanTest
FilterTest
GetPathTest
MatrixConcatTest
NamespaceTest
NumberTest
ObjectTest
PrefixTest
SelectSingleNodeTest
SortByTest
SubstringTest
TextTest
UriMapTest
ValueOfTest
VariableTest
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/NumberTest.html0000644000175000017500000002533610242117740022652 0ustar ebourgebourg NumberTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.AbstractTestCase;
13  import org.dom4j.Node;
14  import org.dom4j.XPath;
15  
16  /***
17   * Test harness for numeric XPath expressions
18   * 
19   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
20   * @version $Revision: 1.3 $
21   */
22  public class NumberTest extends AbstractTestCase {
23      protected static String[] paths = {"2+2", "2 + 2", "2 + number(1) + 2",
24              "number(1) * 2", "2 + count(//author) + 2", "2 + (2 * 5)",
25              "count(//author) + count(//author/attribute::*)",
26              "(12 + count(//author) + count(//author/attribute::*)) div 2",
27              "count(//author)", "count(//author/attribute::*)",
28              "2 + number(1) * 2", "count(descendant::author)",
29              "count(ancestor::author)", "count(descendant::*)",
30              "count(descendant::author)+1", "count(ancestor::*)",
31              "10 + count(ancestor-or-self::author) + 5",
32              "10 + count(descendant::author) * 5",
33              "10 + (count(descendant::author) * 5)"};
34  
35      public static void main(String[] args) {
36          TestRunner.run(NumberTest.class);
37      }
38  
39      // Test case(s)
40      // -------------------------------------------------------------------------
41      public void testXPaths() throws Exception {
42          Node element = document.selectSingleNode("//author");
43          int size = paths.length;
44  
45          for (int i = 0; i < size; i++) {
46              testXPath(document, paths[i]);
47              testXPath(element, paths[i]);
48          }
49  
50          log("Finished successfully");
51      }
52  
53      // Implementation methods
54      // -------------------------------------------------------------------------
55      protected void testXPath(Node node, String xpathText) throws Exception {
56          try {
57              XPath xpath = node.createXPath(xpathText);
58  
59              Number number = xpath.numberValueOf(node);
60  
61              log("Searched path: " + xpathText + " found: " + number);
62          } catch (Throwable e) {
63              log("Caught exception: " + e);
64              e.printStackTrace();
65              assertTrue("Failed to process:  " + xpathText
66                      + " caught exception: " + e, false);
67          }
68      }
69  }
70  
71  /*
72   * Redistribution and use of this software and associated documentation
73   * ("Software"), with or without modification, are permitted provided that the
74   * following conditions are met:
75   * 
76   * 1. Redistributions of source code must retain copyright statements and
77   * notices. Redistributions must also contain a copy of this document.
78   * 
79   * 2. Redistributions in binary form must reproduce the above copyright notice,
80   * this list of conditions and the following disclaimer in the documentation
81   * and/or other materials provided with the distribution.
82   * 
83   * 3. The name "DOM4J" must not be used to endorse or promote products derived
84   * from this Software without prior written permission of MetaStuff, Ltd. For
85   * written permission, please contact dom4j-info@metastuff.com.
86   * 
87   * 4. Products derived from this Software may not be called "DOM4J" nor may
88   * "DOM4J" appear in their names without prior written permission of MetaStuff,
89   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
90   * 
91   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
92   * 
93   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
94   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
95   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
96   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
97   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
98   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
99   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
100  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
101  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
103  * POSSIBILITY OF SUCH DAMAGE.
104  * 
105  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
106  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/MatrixConcatTest.html0000644000175000017500000002412110242117742024007 0ustar ebourgebourg MatrixConcatTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.File;
13  import java.util.List;
14  
15  import org.dom4j.AbstractTestCase;
16  import org.dom4j.io.SAXReader;
17  
18  /***
19   * Test harness for the matrix-concat extension function
20   * 
21   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
22   * @version $Revision: 1.3 $
23   */
24  public class MatrixConcatTest extends AbstractTestCase {
25      public static void main(String[] args) {
26          TestRunner.run(MatrixConcatTest.class);
27      }
28  
29      // Test case(s)
30      // -------------------------------------------------------------------------
31      public void testMatrixConcat() throws Exception {
32          String[] exp1 = {"EQUITY_CF1", "EQUITY_CF2", "EQUITY_CF3"};
33  
34          String[] exp2 = {"EQUITY_BAR_CF1", "EQUITY_BAR_CF2", "EQUITY_BAR_CF3"};
35  
36          testMatrixConcat("'EQUITY_',/product/cashflows/CashFlow/XREF", exp1);
37          testMatrixConcat("'EQUITY_','BAR_',/product/cashflows/CashFlow/XREF",
38                  exp2);
39      }
40  
41      // Implementation methods
42      // -------------------------------------------------------------------------
43      protected void testMatrixConcat(String path, String[] results)
44              throws Exception {
45          log("Using XPath: " + path);
46  
47          List list = document.selectNodes("matrix-concat(" + path + ")");
48  
49          log("Found: " + list);
50  
51          // Object object = list.get(0);
52          // log( "(0) = " + object + " type: " + object.getClass() );
53          int size = results.length;
54          assertTrue("List should contain " + size + " results: " + list, list
55                  .size() == size);
56  
57          for (int i = 0; i < size; i++) {
58              assertEquals(list.get(i), results[i]);
59          }
60      }
61  
62      protected void setUp() throws Exception {
63          super.setUp();
64          document = new SAXReader().read(new File("xml/test/product.xml"));
65      }
66  }
67  
68  /*
69   * Redistribution and use of this software and associated documentation
70   * ("Software"), with or without modification, are permitted provided that the
71   * following conditions are met:
72   * 
73   * 1. Redistributions of source code must retain copyright statements and
74   * notices. Redistributions must also contain a copy of this document.
75   * 
76   * 2. Redistributions in binary form must reproduce the above copyright notice,
77   * this list of conditions and the following disclaimer in the documentation
78   * and/or other materials provided with the distribution.
79   * 
80   * 3. The name "DOM4J" must not be used to endorse or promote products derived
81   * from this Software without prior written permission of MetaStuff, Ltd. For
82   * written permission, please contact dom4j-info@metastuff.com.
83   * 
84   * 4. Products derived from this Software may not be called "DOM4J" nor may
85   * "DOM4J" appear in their names without prior written permission of MetaStuff,
86   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
87   * 
88   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
89   * 
90   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
91   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
92   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
93   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
94   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
95   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
96   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
97   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
98   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
99   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
100  * POSSIBILITY OF SUCH DAMAGE.
101  * 
102  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
103  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/package-frame.html0000644000175000017500000000500410242117741023234 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.xpath

org.dom4j.xpath

Classes

  • AttributeTest
  • BadPathTest
  • BooleanTest
  • FilterTest
  • GetPathTest
  • MatrixConcatTest
  • NamespaceTest
  • NumberTest
  • ObjectTest
  • PrefixTest
  • SelectSingleNodeTest
  • SortByTest
  • SubstringTest
  • TextTest
  • UriMapTest
  • ValueOfTest
  • VariableTest
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/ValueOfTest.html0000644000175000017500000002637010242117703022761 0ustar ebourgebourg ValueOfTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.List;
13  
14  import org.dom4j.AbstractTestCase;
15  import org.dom4j.Element;
16  import org.dom4j.Node;
17  import org.dom4j.XPath;
18  
19  /***
20   * Test harness for the valueOf() function
21   * 
22   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
23   * @version $Revision: 1.3 $
24   */
25  public class ValueOfTest extends AbstractTestCase {
26      protected static String[] paths = {"/root", "//author", "//author/@name",
27              "/root/author[1]", "/root/author[1]/@name", "/root/author[2]",
28              "/root/author[2]/@name", "/root/author[3]",
29              "/root/author[3]/@name", "name()", "name(.)", "name(..)",
30              "name(child::node())", "name(parent::*)", "name(../*)",
31              "name(../child::node())", "local-name()", "local-name(..)",
32              "local-name(parent::*)", "local-name(../*)", "parent::*",
33              "name(/.)", "name(/child::node())", "name(/*)", ".", "..", "../*",
34              "../child::node()", "/.", "/*", "*", "/child::node()"};
35  
36      public static void main(String[] args) {
37          TestRunner.run(ValueOfTest.class);
38      }
39  
40      // Test case(s)
41      // -------------------------------------------------------------------------
42      public void testXPaths() throws Exception {
43          Element root = document.getRootElement();
44          List children = root.elements("author");
45          Element child1 = (Element) children.get(0);
46  
47          testXPath(document);
48          testXPath(root);
49          testXPath(child1);
50      }
51  
52      protected void testXPath(Node node) throws Exception {
53          log("Testing XPath on: " + node);
54          log("===============================");
55  
56          int size = paths.length;
57  
58          for (int i = 0; i < size; i++) {
59              testXPath(node, paths[i]);
60          }
61      }
62  
63      protected void testXPath(Node node, String xpathExpr) throws Exception {
64          try {
65              XPath xpath = node.createXPath(xpathExpr);
66              String value = xpath.valueOf(node);
67  
68              log("valueOf: " + xpathExpr + " is: " + value);
69          } catch (Throwable e) {
70              e.printStackTrace();
71              assertTrue("Failed with exception: " + e, false);
72          }
73      }
74  }
75  
76  /*
77   * Redistribution and use of this software and associated documentation
78   * ("Software"), with or without modification, are permitted provided that the
79   * following conditions are met:
80   * 
81   * 1. Redistributions of source code must retain copyright statements and
82   * notices. Redistributions must also contain a copy of this document.
83   * 
84   * 2. Redistributions in binary form must reproduce the above copyright notice,
85   * this list of conditions and the following disclaimer in the documentation
86   * and/or other materials provided with the distribution.
87   * 
88   * 3. The name "DOM4J" must not be used to endorse or promote products derived
89   * from this Software without prior written permission of MetaStuff, Ltd. For
90   * written permission, please contact dom4j-info@metastuff.com.
91   * 
92   * 4. Products derived from this Software may not be called "DOM4J" nor may
93   * "DOM4J" appear in their names without prior written permission of MetaStuff,
94   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
95   * 
96   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
97   * 
98   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
99   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
100  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
101  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
102  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
103  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
104  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
105  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
106  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
107  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
108  * POSSIBILITY OF SUCH DAMAGE.
109  * 
110  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
111  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/SelectSingleNodeTest.html0000644000175000017500000002447610242117737024623 0ustar ebourgebourg SelectSingleNodeTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.AbstractTestCase;
13  import org.dom4j.Document;
14  import org.dom4j.Element;
15  import org.dom4j.Node;
16  
17  /***
18   * Tests the selectSingleNode method
19   * 
20   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
21   * @version $Revision: 1.4 $
22   */
23  public class SelectSingleNodeTest extends AbstractTestCase {
24      public static void main(String[] args) {
25          TestRunner.run(SelectSingleNodeTest.class);
26      }
27  
28      // Test case(s)
29      // -------------------------------------------------------------------------
30      public void testSelectSingleNode() throws Exception {
31          Document document = getDocument("/xml/test/jimBrain.xml");
32          Node node = document.selectSingleNode("/properties/client/threadsafe");
33          assertTrue("Found a valid node", node != null);
34  
35          Element server = (Element) document
36                  .selectSingleNode("/properties/server");
37          assertTrue("Found a valid server", server != null);
38  
39          Element root = document.getRootElement();
40          server = (Element) root.selectSingleNode("/properties/server");
41          assertTrue("Found a valid server", server != null);
42  
43          // try finding it via a relative path
44          server = (Element) document.selectSingleNode("properties/server");
45          assertTrue("Found a valid server", server != null);
46  
47          // now lets use a relative path
48          Element connection = (Element) server.selectSingleNode("db/connection");
49          assertTrue("Found a valid connection", connection != null);
50      }
51  
52      /***
53       * Test out Steen's bug
54       * 
55       * @throws Exception
56       *             DOCUMENT ME!
57       */
58      public void testSteensBug() throws Exception {
59          Document document = getDocument("/xml/schema/personal.xsd");
60  
61          String xpath = "/xs:schema/xs:element[@name='person']";
62          assertNotNull("element is null", document.selectSingleNode(xpath));
63  
64          Element root = document.getRootElement();
65  
66          assertNotNull("element is null", root.selectSingleNode(xpath));
67      }
68  }
69  
70  /*
71   * Redistribution and use of this software and associated documentation
72   * ("Software"), with or without modification, are permitted provided that the
73   * following conditions are met:
74   * 
75   * 1. Redistributions of source code must retain copyright statements and
76   * notices. Redistributions must also contain a copy of this document.
77   * 
78   * 2. Redistributions in binary form must reproduce the above copyright notice,
79   * this list of conditions and the following disclaimer in the documentation
80   * and/or other materials provided with the distribution.
81   * 
82   * 3. The name "DOM4J" must not be used to endorse or promote products derived
83   * from this Software without prior written permission of MetaStuff, Ltd. For
84   * written permission, please contact dom4j-info@metastuff.com.
85   * 
86   * 4. Products derived from this Software may not be called "DOM4J" nor may
87   * "DOM4J" appear in their names without prior written permission of MetaStuff,
88   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
89   * 
90   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
91   * 
92   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
93   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
95   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
96   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
97   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
98   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
99   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
100  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
102  * POSSIBILITY OF SUCH DAMAGE.
103  * 
104  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
105  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/VariableTest.html0000644000175000017500000002567510242117760023157 0ustar ebourgebourg VariableTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.List;
13  
14  import org.dom4j.AbstractTestCase;
15  import org.dom4j.DocumentHelper;
16  import org.dom4j.Node;
17  import org.dom4j.XPath;
18  
19  import org.jaxen.SimpleVariableContext;
20  
21  /***
22   * Test harness for the valueOf() function
23   * 
24   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
25   * @version $Revision: 1.4 $
26   */
27  public class VariableTest extends AbstractTestCase {
28      // TODO: uncomment these if jaxen bug is fixed
29      // http://jira.codehaus.org/browse/JAXEN-73
30      protected static String[] paths = {
31              "$author",
32  //            "$author/@name",
33  //            "$root/author",
34  //            "$root/author[1]",
35  //            "$root/author[1]/@name",
36  //            "$author/@name"
37          };
38  
39      private SimpleVariableContext variableContext = new SimpleVariableContext();
40  
41      private Node rootNode;
42  
43      private Node authorNode;
44  
45      public static void main(String[] args) {
46          TestRunner.run(VariableTest.class);
47      }
48  
49      // Test case(s)
50      // -------------------------------------------------------------------------
51      public void testXPaths() throws Exception {
52          int size = paths.length;
53  
54          for (int i = 0; i < size; i++) {
55              testXPath(paths[i]);
56          }
57      }
58  
59      protected void testXPath(String xpathText) {
60          XPath xpath = createXPath(xpathText);
61          List list = xpath.selectNodes(document);
62  
63          log("Searched path: " + xpathText + " found: " + list.size()
64                  + " result(s)");
65  
66          assertTrue("Results should not contain the root node", !list
67                  .contains(rootNode));
68      }
69  
70      protected XPath createXPath(String xpath) {
71          return DocumentHelper.createXPath(xpath, variableContext);
72      }
73  
74      protected void setUp() throws Exception {
75          super.setUp();
76  
77          rootNode = document.selectSingleNode("/root");
78          authorNode = document.selectSingleNode("/root/author[1]");
79  
80          variableContext.setVariableValue("root", rootNode);
81          variableContext.setVariableValue("author", authorNode);
82      }
83  }
84  
85  /*
86   * Redistribution and use of this software and associated documentation
87   * ("Software"), with or without modification, are permitted provided that the
88   * following conditions are met:
89   * 
90   * 1. Redistributions of source code must retain copyright statements and
91   * notices. Redistributions must also contain a copy of this document.
92   * 
93   * 2. Redistributions in binary form must reproduce the above copyright notice,
94   * this list of conditions and the following disclaimer in the documentation
95   * and/or other materials provided with the distribution.
96   * 
97   * 3. The name "DOM4J" must not be used to endorse or promote products derived
98   * from this Software without prior written permission of MetaStuff, Ltd. For
99   * written permission, please contact dom4j-info@metastuff.com.
100  * 
101  * 4. Products derived from this Software may not be called "DOM4J" nor may
102  * "DOM4J" appear in their names without prior written permission of MetaStuff,
103  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
104  * 
105  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
106  * 
107  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
108  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
109  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
110  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
111  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
112  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
113  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
114  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
115  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
116  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
117  * POSSIBILITY OF SUCH DAMAGE.
118  * 
119  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
120  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/NamespaceTest.html0000644000175000017500000002627610242117711023320 0ustar ebourgebourg NamespaceTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.File;
13  import java.util.Iterator;
14  import java.util.List;
15  
16  import org.dom4j.AbstractTestCase;
17  import org.dom4j.DocumentHelper;
18  import org.dom4j.Namespace;
19  import org.dom4j.XPath;
20  import org.dom4j.io.SAXReader;
21  
22  /***
23   * Test harness for the namespace axis
24   * 
25   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
26   * @version $Revision: 1.3 $
27   */
28  public class NamespaceTest extends AbstractTestCase {
29      protected static String[] paths = {"namespace::*",
30              "/Template/Application1/namespace::*",
31              "/Template/Application1/namespace::xplt", "//namespace::*"};
32  
33      public static void main(String[] args) {
34          TestRunner.run(NamespaceTest.class);
35      }
36  
37      // Test case(s)
38      // -------------------------------------------------------------------------
39      public void testXPaths() throws Exception {
40          int size = paths.length;
41  
42          for (int i = 0; i < size; i++) {
43              testXPath(paths[i]);
44          }
45      }
46  
47      // Implementation methods
48      // -------------------------------------------------------------------------
49      protected void testXPath(String xpathText) {
50          XPath xpath = DocumentHelper.createXPath(xpathText);
51          List list = xpath.selectNodes(document);
52  
53          log("Searched path: " + xpathText + " found: " + list.size()
54                  + " result(s)");
55  
56          for (Iterator iter = list.iterator(); iter.hasNext();) {
57              Object object = iter.next();
58  
59              log("Found Result: " + object);
60  
61              assertTrue("Results should be Namespace objects",
62                      object instanceof Namespace);
63  
64              Namespace namespace = (Namespace) object;
65  
66              log("Parent node: " + namespace.getParent());
67  
68              assertTrue("Results should support the parent relationship",
69                      namespace.supportsParent());
70              assertTrue(
71                      "Results should contain reference to the parent element",
72                      namespace.getParent() != null);
73              assertTrue("Results should contain reference to the document",
74                      namespace.getDocument() != null);
75          }
76      }
77  
78      protected void setUp() throws Exception {
79          super.setUp();
80          document = new SAXReader().read(new File("xml/testNamespaces.xml"));
81      }
82  }
83  
84  /*
85   * Redistribution and use of this software and associated documentation
86   * ("Software"), with or without modification, are permitted provided that the
87   * following conditions are met:
88   * 
89   * 1. Redistributions of source code must retain copyright statements and
90   * notices. Redistributions must also contain a copy of this document.
91   * 
92   * 2. Redistributions in binary form must reproduce the above copyright notice,
93   * this list of conditions and the following disclaimer in the documentation
94   * and/or other materials provided with the distribution.
95   * 
96   * 3. The name "DOM4J" must not be used to endorse or promote products derived
97   * from this Software without prior written permission of MetaStuff, Ltd. For
98   * written permission, please contact dom4j-info@metastuff.com.
99   * 
100  * 4. Products derived from this Software may not be called "DOM4J" nor may
101  * "DOM4J" appear in their names without prior written permission of MetaStuff,
102  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
103  * 
104  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
105  * 
106  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
107  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
108  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
109  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
110  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
111  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
112  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
113  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
114  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
115  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
116  * POSSIBILITY OF SUCH DAMAGE.
117  * 
118  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
119  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/SubstringTest.html0000644000175000017500000002376410242117553023407 0ustar ebourgebourg SubstringTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.File;
13  import java.util.List;
14  
15  import org.dom4j.AbstractTestCase;
16  import org.dom4j.Element;
17  import org.dom4j.io.SAXReader;
18  
19  /***
20   * Test harness for the substring function
21   * 
22   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
23   * @version $Revision: 1.3 $
24   */
25  public class SubstringTest extends AbstractTestCase {
26      public static void main(String[] args) {
27          TestRunner.run(SubstringTest.class);
28      }
29  
30      // Test case(s)
31      // -------------------------------------------------------------------------
32      public void testSubstring() throws Exception {
33          String[] results1 = {"1100", "1101"};
34  
35          testSubstring("//field[substring(@id,1,2)='11']", results1);
36  
37          String[] results2 = {"2111", "3111"};
38          testSubstring("//field[substring(@id,3)='11']", results2);
39      }
40  
41      // Implementation methods
42      // -------------------------------------------------------------------------
43      protected void testSubstring(String path, String[] results)
44              throws Exception {
45          log("Using XPath: " + path);
46  
47          List list = document.selectNodes(path);
48  
49          log("Found: " + list);
50  
51          // Object object = list.get(0);
52          // log( "(0) = " + object + " type: " + object.getClass() );
53          int size = results.length;
54          assertTrue("List should contain " + size + " results: " + list, list
55                  .size() == size);
56  
57          for (int i = 0; i < size; i++) {
58              Element element = (Element) list.get(i);
59              assertEquals(element.attributeValue("id"), results[i]);
60          }
61      }
62  
63      protected void setUp() throws Exception {
64          super.setUp();
65          document = new SAXReader().read(new File("xml/test/fields.xml"));
66      }
67  }
68  
69  /*
70   * Redistribution and use of this software and associated documentation
71   * ("Software"), with or without modification, are permitted provided that the
72   * following conditions are met:
73   * 
74   * 1. Redistributions of source code must retain copyright statements and
75   * notices. Redistributions must also contain a copy of this document.
76   * 
77   * 2. Redistributions in binary form must reproduce the above copyright notice,
78   * this list of conditions and the following disclaimer in the documentation
79   * and/or other materials provided with the distribution.
80   * 
81   * 3. The name "DOM4J" must not be used to endorse or promote products derived
82   * from this Software without prior written permission of MetaStuff, Ltd. For
83   * written permission, please contact dom4j-info@metastuff.com.
84   * 
85   * 4. Products derived from this Software may not be called "DOM4J" nor may
86   * "DOM4J" appear in their names without prior written permission of MetaStuff,
87   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
88   * 
89   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
90   * 
91   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
92   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
94   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
95   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
96   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
97   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
98   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
99   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
100  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
101  * POSSIBILITY OF SUCH DAMAGE.
102  * 
103  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
104  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/ObjectTest.html0000644000175000017500000002052610242117705022625 0ustar ebourgebourg ObjectTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import org.dom4j.AbstractTestCase;
13  import org.dom4j.Node;
14  import org.dom4j.XPath;
15  
16  /***
17   * Test harness for numeric XPath expressions
18   * 
19   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
20   * @version $Revision: 1.3 $
21   */
22  public class ObjectTest extends AbstractTestCase {
23      protected static String[] paths = {"name(/.)", "name()"};
24  
25      public static void main(String[] args) {
26          TestRunner.run(ObjectTest.class);
27      }
28  
29      // Test case(s)
30      // -------------------------------------------------------------------------
31      public void testXPaths() throws Exception {
32          Node element = document.selectSingleNode("//author");
33          int size = paths.length;
34  
35          for (int i = 0; i < size; i++) {
36              testXPath(document, paths[i]);
37              testXPath(element, paths[i]);
38          }
39      }
40  
41      // Implementation methods
42      // -------------------------------------------------------------------------
43      protected void testXPath(Node node, String xpathText) {
44          XPath xpath = node.createXPath(xpathText);
45          Object object = xpath.evaluate(node);
46      }
47  }
48  
49  /*
50   * Redistribution and use of this software and associated documentation
51   * ("Software"), with or without modification, are permitted provided that the
52   * following conditions are met:
53   * 
54   * 1. Redistributions of source code must retain copyright statements and
55   * notices. Redistributions must also contain a copy of this document.
56   * 
57   * 2. Redistributions in binary form must reproduce the above copyright notice,
58   * this list of conditions and the following disclaimer in the documentation
59   * and/or other materials provided with the distribution.
60   * 
61   * 3. The name "DOM4J" must not be used to endorse or promote products derived
62   * from this Software without prior written permission of MetaStuff, Ltd. For
63   * written permission, please contact dom4j-info@metastuff.com.
64   * 
65   * 4. Products derived from this Software may not be called "DOM4J" nor may
66   * "DOM4J" appear in their names without prior written permission of MetaStuff,
67   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
68   * 
69   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
70   * 
71   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
72   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
73   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
74   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
75   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
76   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
77   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
78   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
79   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
80   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
81   * POSSIBILITY OF SUCH DAMAGE.
82   * 
83   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
84   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/GetPathTest.html0000644000175000017500000004363710242117751022764 0ustar ebourgebourg GetPathTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.Iterator;
13  import java.util.List;
14  
15  import org.dom4j.AbstractTestCase;
16  import org.dom4j.Attribute;
17  import org.dom4j.Branch;
18  import org.dom4j.Document;
19  import org.dom4j.DocumentFactory;
20  import org.dom4j.DocumentHelper;
21  import org.dom4j.Element;
22  import org.dom4j.Node;
23  import org.dom4j.QName;
24  
25  /***
26   * Test harness for the GetPath() method
27   * 
28   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
29   * @version $Revision: 1.4 $
30   */
31  public class GetPathTest extends AbstractTestCase {
32      public static void main(String[] args) {
33          TestRunner.run(GetPathTest.class);
34      }
35  
36      // Test case(s)
37      // -------------------------------------------------------------------------
38      public void testGetPath() throws Exception {
39          log("Testing paths");
40  
41          // testBranchPath( document );
42          testPath(document, "/");
43  
44          Element root = document.getRootElement();
45  
46          testPath(root, "/root");
47  
48          List elements = root.elements();
49  
50          testPath((Node) elements.get(0), "/root/author", "/root/author[1]");
51  
52          for (int i = 0, size = elements.size(); i < size; i++) {
53              String path = "/root/author";
54              String uniquePath = "/root/author";
55              String pathRel = "author";
56              String uniquePathRel = "author";
57  
58              if (size > 1) {
59                  uniquePath = "/root/author[" + (i + 1) + "]";
60                  uniquePathRel = "author[" + (i + 1) + "]";
61              }
62  
63              Element element = (Element) elements.get(i);
64              testPath(element, path, uniquePath);
65              testRelativePath(root, element, pathRel, uniquePathRel);
66  
67              Attribute attribute = element.attribute("name");
68              testPath(attribute, path + "/@name", uniquePath + "/@name");
69              testRelativePath(root, attribute, pathRel + "/@name", uniquePathRel
70                      + "/@name");
71  
72              Element child = element.element("url");
73              testPath(child, path + "/url", uniquePath + "/url");
74              testRelativePath(root, child, pathRel + "/url", uniquePathRel
75                      + "/url");
76          }
77      }
78  
79      public void testDefaultNamespace() throws Exception {
80          Document doc = getDocument("/xml/test/defaultNamespace.xml");
81          Element root = doc.getRootElement();
82          testPath(root, "/*[name()='a']");
83  
84          Element child = (Element) root.elements().get(0);
85          testPath(child, "/*[name()='a']/*[name()='b']");
86          testRelativePath(root, child, "*[name()='b']");
87      }
88  
89      public void testBug770410() {
90          Document doc = DocumentHelper.createDocument();
91          Element a = doc.addElement("a");
92          Element b = a.addElement("b");
93          Element c = b.addElement("c");
94  
95          b.detach();
96  
97          String relativePath = b.getPath(b);
98          assertSame(b, b.selectSingleNode(relativePath));
99      }
100 
101     public void testBug569927() {
102         Document doc = DocumentHelper.createDocument();
103         QName elName = DocumentFactory.getInstance().createQName("a", "ns",
104                 "uri://myuri");
105         Element a = doc.addElement(elName);
106         QName attName = DocumentFactory.getInstance().createQName("attribute",
107                 "ns", "uri://myuri");
108         a = a.addAttribute(attName, "test");
109 
110         Attribute att = a.attribute(attName);
111 
112         assertSame(att, doc.selectSingleNode(att.getPath()));
113         assertSame(att, doc.selectSingleNode(att.getUniquePath()));
114     }
115 
116     protected void testPath(Node node, String value) {
117         testPath(node, value, value);
118     }
119 
120     protected void testPath(Node node, String path, String uniquePath) {
121         assertEquals("getPath expression should be what is expected", path,
122                 node.getPath());
123         assertEquals("getUniquePath expression should be what is expected",
124                 uniquePath, node.getUniquePath());
125     }
126 
127     protected void testRelativePath(Element context, Node node, String path) {
128         testRelativePath(context, node, path, path);
129     }
130 
131     protected void testRelativePath(Element context, Node node, String pathRel,
132             String uniquePathRel) {
133         assertEquals("relative getPath expression should be what is expected",
134                 pathRel, node.getPath(context));
135         assertEquals("relative getUniquePath expression not correct",
136                 uniquePathRel, node.getUniquePath(context));
137     }
138 
139     protected void testBranchPath(Branch branch) {
140         testNodePath(branch);
141 
142         if (branch instanceof Element) {
143             Element element = (Element) branch;
144 
145             for (Iterator iter = element.attributeIterator(); iter.hasNext();) {
146                 Node node = (Node) iter.next();
147                 testNodePath(node);
148             }
149         }
150 
151         for (Iterator iter = branch.nodeIterator(); iter.hasNext();) {
152             Node node = (Node) iter.next();
153 
154             if (node instanceof Branch) {
155                 testBranchPath((Branch) node);
156             } else {
157                 testNodePath(node);
158             }
159         }
160     }
161 
162     protected void testNodePath(Node node) {
163         String path = node.getPath();
164 
165         log("Path: " + path + " node: " + node);
166     }
167 }
168 
169 /*
170  * Redistribution and use of this software and associated documentation
171  * ("Software"), with or without modification, are permitted provided that the
172  * following conditions are met:
173  * 
174  * 1. Redistributions of source code must retain copyright statements and
175  * notices. Redistributions must also contain a copy of this document.
176  * 
177  * 2. Redistributions in binary form must reproduce the above copyright notice,
178  * this list of conditions and the following disclaimer in the documentation
179  * and/or other materials provided with the distribution.
180  * 
181  * 3. The name "DOM4J" must not be used to endorse or promote products derived
182  * from this Software without prior written permission of MetaStuff, Ltd. For
183  * written permission, please contact dom4j-info@metastuff.com.
184  * 
185  * 4. Products derived from this Software may not be called "DOM4J" nor may
186  * "DOM4J" appear in their names without prior written permission of MetaStuff,
187  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
188  * 
189  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
190  * 
191  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
192  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
193  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
194  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
195  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
196  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
197  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
198  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
199  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
200  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
201  * POSSIBILITY OF SUCH DAMAGE.
202  * 
203  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
204  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/SortByTest.html0000644000175000017500000002063610242117735022646 0ustar ebourgebourg SortByTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.File;
13  import java.util.List;
14  
15  import org.dom4j.AbstractTestCase;
16  import org.dom4j.io.SAXReader;
17  
18  /***
19   * Test harness for the sorting version of the selectNodes() function
20   * 
21   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
22   * @version $Revision: 1.3 $
23   */
24  public class SortByTest extends AbstractTestCase {
25      public static void main(String[] args) {
26          TestRunner.run(SortByTest.class);
27      }
28  
29      // Test case(s)
30      // -------------------------------------------------------------------------
31      public void testXPaths() throws Exception {
32          List list = document.selectNodes("//SPEAKER", "NAME");
33  
34          log("Number of SPEAKER instances: " + list.size());
35  
36          List noDuplicates = document.selectNodes("//SPEAKER", ".", true);
37  
38          log("Number of distinct SPEAKER instances: " + noDuplicates.size());
39  
40          log("Number of distinct SPEAKER instances: " + noDuplicates.size());
41      }
42  
43      protected void setUp() throws Exception {
44          super.setUp();
45          document = new SAXReader().read(new File("xml/much_ado.xml"));
46      }
47  }
48  
49  /*
50   * Redistribution and use of this software and associated documentation
51   * ("Software"), with or without modification, are permitted provided that the
52   * following conditions are met:
53   * 
54   * 1. Redistributions of source code must retain copyright statements and
55   * notices. Redistributions must also contain a copy of this document.
56   * 
57   * 2. Redistributions in binary form must reproduce the above copyright notice,
58   * this list of conditions and the following disclaimer in the documentation
59   * and/or other materials provided with the distribution.
60   * 
61   * 3. The name "DOM4J" must not be used to endorse or promote products derived
62   * from this Software without prior written permission of MetaStuff, Ltd. For
63   * written permission, please contact dom4j-info@metastuff.com.
64   * 
65   * 4. Products derived from this Software may not be called "DOM4J" nor may
66   * "DOM4J" appear in their names without prior written permission of MetaStuff,
67   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
68   * 
69   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
70   * 
71   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
72   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
73   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
74   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
75   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
76   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
77   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
78   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
79   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
80   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
81   * POSSIBILITY OF SUCH DAMAGE.
82   * 
83   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
84   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/BooleanTest.html0000644000175000017500000002343010242117656023000 0ustar ebourgebourg BooleanTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.Iterator;
13  import java.util.List;
14  
15  import org.dom4j.AbstractTestCase;
16  import org.dom4j.DocumentHelper;
17  import org.dom4j.Node;
18  import org.dom4j.XPath;
19  
20  /***
21   * Test harness for the boolean expressions
22   * 
23   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
24   * @version $Revision: 1.3 $
25   */
26  public class BooleanTest extends AbstractTestCase {
27      protected static String[] paths = {".[name()='author']",
28              ".[.='James Strachan']", ".[name()='XXXX']", ".[.='XXXX']",
29              "name()='author'", "name()='XXXX'", ".='James Strachan'",
30              ".='XXXX'"};
31  
32      public static void main(String[] args) {
33          TestRunner.run(BooleanTest.class);
34      }
35  
36      // Test case(s)
37      // -------------------------------------------------------------------------
38      public void testXPaths() throws Exception {
39          int size = paths.length;
40  
41          for (int i = 0; i < size; i++) {
42              testXPath(paths[i]);
43          }
44      }
45  
46      // Implementation methods
47      // -------------------------------------------------------------------------
48      protected void testXPath(String xpathExpression) {
49          XPath xpath = DocumentHelper.createXPath(xpathExpression);
50          assertTrue("No xpath object was created", xpath != null);
51  
52          log("Evaluating xpath: " + xpath);
53  
54          List list = document.selectNodes("//author");
55  
56          for (Iterator iter = list.iterator(); iter.hasNext();) {
57              Node node = (Node) iter.next();
58              testXPath(node, xpath);
59          }
60      }
61  
62      protected void testXPath(Node node, XPath xpath) {
63          List list = xpath.selectNodes(node);
64      }
65  }
66  
67  /*
68   * Redistribution and use of this software and associated documentation
69   * ("Software"), with or without modification, are permitted provided that the
70   * following conditions are met:
71   * 
72   * 1. Redistributions of source code must retain copyright statements and
73   * notices. Redistributions must also contain a copy of this document.
74   * 
75   * 2. Redistributions in binary form must reproduce the above copyright notice,
76   * this list of conditions and the following disclaimer in the documentation
77   * and/or other materials provided with the distribution.
78   * 
79   * 3. The name "DOM4J" must not be used to endorse or promote products derived
80   * from this Software without prior written permission of MetaStuff, Ltd. For
81   * written permission, please contact dom4j-info@metastuff.com.
82   * 
83   * 4. Products derived from this Software may not be called "DOM4J" nor may
84   * "DOM4J" appear in their names without prior written permission of MetaStuff,
85   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
86   * 
87   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
88   * 
89   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
90   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
91   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
92   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
93   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
94   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
95   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
96   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
97   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
98   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
99   * POSSIBILITY OF SUCH DAMAGE.
100  * 
101  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
102  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/AttributeTest.html0000644000175000017500000002454710242117562023372 0ustar ebourgebourg AttributeTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.Iterator;
13  import java.util.List;
14  
15  import org.dom4j.AbstractTestCase;
16  import org.dom4j.Attribute;
17  import org.dom4j.DocumentHelper;
18  import org.dom4j.XPath;
19  
20  /***
21   * Test harness for the attribute axis
22   * 
23   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
24   * @version $Revision: 1.3 $
25   */
26  public class AttributeTest extends AbstractTestCase {
27      protected static String[] paths = {"attribute::*",
28              "/root/author/attribute::*", "//attribute::*", "@name"};
29  
30      public static void main(String[] args) {
31          TestRunner.run(AttributeTest.class);
32      }
33  
34      // Test case(s)
35      // -------------------------------------------------------------------------
36      public void testXPaths() throws Exception {
37          int size = paths.length;
38  
39          for (int i = 0; i < size; i++) {
40              testXPath(paths[i]);
41          }
42      }
43  
44      // Implementation methods
45      // -------------------------------------------------------------------------
46      protected void testXPath(String xpathText) {
47          XPath xpath = DocumentHelper.createXPath(xpathText);
48          List list = xpath.selectNodes(document);
49  
50          log("Searched path: " + xpathText + " found: " + list.size()
51                  + " result(s)");
52  
53          for (Iterator iter = list.iterator(); iter.hasNext();) {
54              Object object = iter.next();
55  
56              log("Found Result: " + object);
57  
58              assertTrue("Results should be Attribute objects",
59                      object instanceof Attribute);
60  
61              Attribute attribute = (Attribute) object;
62  
63              assertTrue("Results should support the parent relationship",
64                      attribute.supportsParent());
65              assertTrue(
66                      "Results should contain reference to the parent element",
67                      attribute.getParent() != null);
68              assertTrue("Resulting document not correct", attribute
69                      .getDocument() != null);
70          }
71      }
72  }
73  
74  /*
75   * Redistribution and use of this software and associated documentation
76   * ("Software"), with or without modification, are permitted provided that the
77   * following conditions are met:
78   * 
79   * 1. Redistributions of source code must retain copyright statements and
80   * notices. Redistributions must also contain a copy of this document.
81   * 
82   * 2. Redistributions in binary form must reproduce the above copyright notice,
83   * this list of conditions and the following disclaimer in the documentation
84   * and/or other materials provided with the distribution.
85   * 
86   * 3. The name "DOM4J" must not be used to endorse or promote products derived
87   * from this Software without prior written permission of MetaStuff, Ltd. For
88   * written permission, please contact dom4j-info@metastuff.com.
89   * 
90   * 4. Products derived from this Software may not be called "DOM4J" nor may
91   * "DOM4J" appear in their names without prior written permission of MetaStuff,
92   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
93   * 
94   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
95   * 
96   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
97   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
98   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
99   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
100  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
101  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
102  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
103  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
104  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
105  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
106  * POSSIBILITY OF SUCH DAMAGE.
107  * 
108  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
109  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/xpath/PrefixTest.html0000644000175000017500000002425110242117717022656 0ustar ebourgebourg PrefixTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import junit.textui.TestRunner;
11  
12  import java.io.File;
13  import java.util.List;
14  
15  import org.dom4j.AbstractTestCase;
16  import org.dom4j.DocumentHelper;
17  import org.dom4j.XPath;
18  import org.dom4j.io.SAXReader;
19  
20  import org.jaxen.SimpleNamespaceContext;
21  
22  /***
23   * Tests finding items using a namespace prefix
24   * 
25   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
26   * @version $Revision: 1.3 $
27   */
28  public class PrefixTest extends AbstractTestCase {
29      protected static String[] paths = {"//xplt:anyElement", "//xpl:insertText",
30              "/Template/Application1/xpl:insertText",
31              "/Template/Application2/xpl:insertText"};
32  
33      public static void main(String[] args) {
34          TestRunner.run(PrefixTest.class);
35      }
36  
37      // Test case(s)
38      // -------------------------------------------------------------------------
39      public void testXPaths() throws Exception {
40          int size = paths.length;
41  
42          for (int i = 0; i < size; i++) {
43              testXPath(paths[i]);
44          }
45      }
46  
47      // Implementation methods
48      // -------------------------------------------------------------------------
49      protected void testXPath(String xpathText) {
50          XPath xpath = DocumentHelper.createXPath(xpathText);
51  
52          SimpleNamespaceContext context = new SimpleNamespaceContext();
53          context.addNamespace("xplt", "www.xxxx.com");
54          context.addNamespace("xpl", "www.xxxx.com");
55          xpath.setNamespaceContext(context);
56  
57          List list = xpath.selectNodes(document);
58  
59          log("Searched path: " + xpathText + " found: " + list.size()
60                  + " result(s)");
61  
62          assertTrue("Should have found at lest one result", list.size() > 0);
63      }
64  
65      protected void setUp() throws Exception {
66          super.setUp();
67          document = new SAXReader().read(new File("xml/testNamespaces.xml"));
68      }
69  }
70  
71  /*
72   * Redistribution and use of this software and associated documentation
73   * ("Software"), with or without modification, are permitted provided that the
74   * following conditions are met:
75   * 
76   * 1. Redistributions of source code must retain copyright statements and
77   * notices. Redistributions must also contain a copy of this document.
78   * 
79   * 2. Redistributions in binary form must reproduce the above copyright notice,
80   * this list of conditions and the following disclaimer in the documentation
81   * and/or other materials provided with the distribution.
82   * 
83   * 3. The name "DOM4J" must not be used to endorse or promote products derived
84   * from this Software without prior written permission of MetaStuff, Ltd. For
85   * written permission, please contact dom4j-info@metastuff.com.
86   * 
87   * 4. Products derived from this Software may not be called "DOM4J" nor may
88   * "DOM4J" appear in their names without prior written permission of MetaStuff,
89   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
90   * 
91   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
92   * 
93   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
94   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
95   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
96   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
97   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
98   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
99   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
100  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
101  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
103  * POSSIBILITY OF SUCH DAMAGE.
104  * 
105  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
106  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/BackedListTest.html0000644000175000017500000003123710242117744022304 0ustar ebourgebourg BackedListTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  import java.util.List;
13  
14  import org.dom4j.io.XMLWriter;
15  
16  /***
17   * A test harness to test the backed list feature of DOM4J
18   * 
19   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
20   * @version $Revision: 1.3 $
21   */
22  public class BackedListTest extends AbstractTestCase {
23      public static void main(String[] args) {
24          TestRunner.run(BackedListTest.class);
25      }
26  
27      // Test case(s)
28      // -------------------------------------------------------------------------
29      public void testXPaths() throws Exception {
30          Element element = (Element) document.selectSingleNode("/root");
31          mutate(element);
32          element = (Element) document.selectSingleNode("//author");
33          mutate(element);
34      }
35  
36      public void testAddRemove() throws Exception {
37          Element parentElement = (Element) document.selectSingleNode("/root");
38          List children = parentElement.elements();
39          int lastPos = children.size() - 1;
40          Element child = (Element) children.get(lastPos);
41  
42          try {
43              // should throw an exception cause we cannot add same child twice
44              children.add(0, child);
45              fail();
46          } catch (IllegalAddException e) {
47          }
48      }
49  
50      public void testAddWithIndex() throws Exception {
51          DocumentFactory factory = DocumentFactory.getInstance();
52  
53          Element root = (Element) document.selectSingleNode("/root");
54          List children = root.elements(); // return a list of 2 author
55          // elements
56  
57          assertEquals(2, children.size());
58  
59          children.add(1, factory.createElement("dummy1"));
60          children = root.elements();
61  
62          assertEquals(3, children.size());
63  
64          children = root.elements("author");
65  
66          assertEquals(2, children.size());
67  
68          children.add(1, factory.createElement("dummy2"));
69  
70          children = root.elements();
71  
72          assertEquals(4, children.size());
73          assertEquals("dummy1", ((Node) children.get(1)).getName());
74          assertEquals("dummy2", ((Node) children.get(2)).getName());
75  
76          /*
77           * Some tests for issue reported at http://tinyurl.com/4jxrc
78           */
79          children.add(children.size(), factory.createElement("dummy3"));
80          children = root.elements("author");
81          children.add(children.size(), factory.createElement("dummy4"));
82      }
83  
84      // Implementation methods
85      // -------------------------------------------------------------------------
86      protected void mutate(Element element) throws Exception {
87          DocumentFactory factory = DocumentFactory.getInstance();
88  
89          List list = element.elements();
90          list.add(factory.createElement("last"));
91          list.add(0, factory.createElement("first"));
92  
93          List list2 = element.elements();
94  
95          assertTrue("Both lists should contain same number of elements", list
96                  .size() == list2.size());
97  
98          XMLWriter writer = new XMLWriter(System.out);
99  
100         log("Element content is now: " + element.content());
101         writer.write(element);
102     }
103 }
104 
105 /*
106  * Redistribution and use of this software and associated documentation
107  * ("Software"), with or without modification, are permitted provided that the
108  * following conditions are met:
109  * 
110  * 1. Redistributions of source code must retain copyright statements and
111  * notices. Redistributions must also contain a copy of this document.
112  * 
113  * 2. Redistributions in binary form must reproduce the above copyright notice,
114  * this list of conditions and the following disclaimer in the documentation
115  * and/or other materials provided with the distribution.
116  * 
117  * 3. The name "DOM4J" must not be used to endorse or promote products derived
118  * from this Software without prior written permission of MetaStuff, Ltd. For
119  * written permission, please contact dom4j-info@metastuff.com.
120  * 
121  * 4. Products derived from this Software may not be called "DOM4J" nor may
122  * "DOM4J" appear in their names without prior written permission of MetaStuff,
123  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
124  * 
125  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
126  * 
127  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
128  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
129  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
130  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
131  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
132  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
133  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
134  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
135  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
136  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
137  * POSSIBILITY OF SUCH DAMAGE.
138  * 
139  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
140  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref-test/org/dom4j/IsTextOnlyTest.html0000644000175000017500000001711010242117763022354 0ustar ebourgebourg IsTextOnlyTest xref

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import junit.textui.TestRunner;
11  
12  /***
13   * A test harness to test the parent relationship and use of the {@link
14   * Node#asXPathResult} method.
15   * 
16   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
17   * @version $Revision: 1.3 $
18   */
19  public class IsTextOnlyTest extends AbstractTestCase {
20      public static void main(String[] args) {
21          TestRunner.run(IsTextOnlyTest.class);
22      }
23  
24      // Test case(s)
25      // -------------------------------------------------------------------------
26      public void testDocument() throws Exception {
27          DocumentFactory factory = new DocumentFactory();
28          Element root = factory.createElement("root");
29          Element first = root.addElement("child");
30          first.addText("This is some text");
31  
32          assertTrue("Root node is not text only: " + root, !root.isTextOnly());
33          assertTrue("First child is text only: " + first, first.isTextOnly());
34      }
35  }
36  
37  /*
38   * Redistribution and use of this software and associated documentation
39   * ("Software"), with or without modification, are permitted provided that the
40   * following conditions are met:
41   * 
42   * 1. Redistributions of source code must retain copyright statements and
43   * notices. Redistributions must also contain a copy of this document.
44   * 
45   * 2. Redistributions in binary form must reproduce the above copyright notice,
46   * this list of conditions and the following disclaimer in the documentation
47   * and/or other materials provided with the distribution.
48   * 
49   * 3. The name "DOM4J" must not be used to endorse or promote products derived
50   * from this Software without prior written permission of MetaStuff, Ltd. For
51   * written permission, please contact dom4j-info@metastuff.com.
52   * 
53   * 4. Products derived from this Software may not be called "DOM4J" nor may
54   * "DOM4J" appear in their names without prior written permission of MetaStuff,
55   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
56   * 
57   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
58   * 
59   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
60   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
63   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
64   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
65   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
66   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
67   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
68   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
69   * POSSIBILITY OF SUCH DAMAGE.
70   * 
71   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
72   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/license.html0000644000175000017500000001643310242117677015342 0ustar ebourgebourgdom4j - License
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
    • Change Log
    • Changes
    • Checkstyle
    • Clover
    • Developer Activity
    • FAQs
    • File Activity
    • JavaDocs
    • JavaDoc Report
    • JavaDoc Warnings Report
    • Metrics
    • Unit Tests
    • Source Xref
    • Test Xref
    • Project License
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

BSD style license

Redistribution and use of this software and associated documentation ("Software"), with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain copyright statements and notices. Redistributions must also contain a copy of this document.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  3. The name "DOM4J" must not be used to endorse or promote products derived from this Software without prior written permission of MetaStuff, Ltd. For written permission, please contact dom4j-info@metastuff.com.
  4. Products derived from this Software may not be called "DOM4J" nor may "DOM4J" appear in their names without prior written permission of MetaStuff, Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
  5. Due credit should be given to the DOM4J Project - http://www.dom4j.org

THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.


2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/changes-report.html0000644000175000017500000010516710242117736016640 0ustar ebourgebourgdom4j - dom4j changes
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
    • Change Log
    • Changes
    • Checkstyle
    • Clover
    • Developer Activity
    • FAQs
    • File Activity
    • JavaDocs
    • JavaDoc Report
    • JavaDoc Warnings Report
    • Metrics
    • Unit Tests
    • Source Xref
    • Test Xref
    • Project License
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Release History

VersionDateDescription
1.6.1 2005-05-16
1.6 2005-04-15
1.5.2 2004-11-15
1.5.1 2004-10-29
1.5 2004-09-03
1.5-rc1 2004-07-04
1.5-beta-2 2004-05-12
1.5-beta-1 2004-03-25

Get the RSS feed of the last changes

Release 1.6.1 - 2005-05-16

TypeChangesBy
update Updated the XPP2 implementation to version 2.1.10. Thanks to Wolfgang Baer . maartenc
fix Fixed a problem with XMLWriterthat was causing too many new lines to be written to the resulting XML. Thanks to Thomas Fromm . maartenc
update Include more information about the cause if an XPathExceptionor InvalidXPathExceptionis thrown. Thanks to Gili Tzabari . maartenc

Release 1.6 - 2005-04-15

TypeChangesBy
add Added a methods to SAXReaderallowing to specify the encoding used when reading XML sources. Thanks to Filip Jirsak . maartenc
update Changed the DocumentHelper.parseText(String)method to make sure that the XML encoding is always set (if known) on the returned Document, even if the used SAXParser doesn't provide a way to retrieve that encoding. maartenc
add Added a setXMLEncoding(String)method to the Documentinterface. maartenc
fix Removed a static OutputFormatfield from AbstractBranch. This can cause problems if multiple threads are using the asXML()method simultaniously. Thanks to John Plaxton . maartenc
fix Fixed a whitespace problem with the pretty-print OutputFormat. Thanks to Brett Porter . maartenc
fix Fixed a bug in the DefaultElement.setContent(List)method that caused incorrectly resetting the parent of the nodes in the list. Thanks to Peter Schaefer . maartenc
remove Removed persistencepackage and sub-package. wolfftw
update Modified SAXEventRecorderto accomodate sax events generated when writing a DOMDocument. wolfftw
fix Fixed a problem in AbstractDocument.asXML()when an encoding was specified on the Document. Thanks to Pieter Valcke . maartenc
fix The DefaultNamespace.isReadOnly()method now returns false. This fixes issues with cloning this Node. maartenc
update Updated DocumentFactoryto create the instance untill the first time it is needed. Thanks to Brian Topping . maartenc
fix Fixed a bug in Stylesheetwhen an xpath expressions was used to select the nodes. Thanks to Brett Porter . maartenc
add Added a SingletonStrategyclass for managing singletons. This allows to use different strategies for singletons, like: one instance per VM, one instance per thread, ... This change removed the usage of ThreadLocals. ddlucas

Release 1.5.2 - 2004-11-15

TypeChangesBy
remove Removed the internal Aelfred2 parser due to incompatible license. maartenc
add Added a SAXEventRecorderthat can replay SAX events at a later time. This provides an alternative serialization approach. wolfftw

Release 1.5.1 - 2004-10-29

TypeChangesBy
fix Fixed problem where the namespace prefix was lost using DOMDocument. Thanks to Ara Vartanian . maartenc
fix Fixed bug in Document.asXML()which ignored the encoding of the document. Thanks to David Karlsen . maartenc
update Updated NamespaceCacheto use WeakReferences to allow Namespaceobjects to be garbage collected. maartenc
update Updated JAXBReaderto allow ElementHandlers to be notified when the specified path is encountered, without having to unmarshall XML content. Thanks to Wonne Keysers . maartenc
fix Fixed a bug in XMLWriterwhere a NullPointerExceptionwas thrown if trying to write a CData section containing nullcontent. Thanks to Daniel Hopper . maartenc
update Modified the internal Aelfred2 parser to no longer support the SAX2 Extensions 1.1 API. As a result, the SAX2 sources are no included with dom4j. maartenc
add Added support for the XPP3 parser. Thanks to Pelle Braendgaard . maartenc

Release 1.5 - 2004-09-03

TypeChangesBy
fix Fixed bug in XMLWriter.characters(...)where the escapeText property of the writer was ignored. Thanks to Dion Gillard . maartenc
fix Fixed the Stylesheet.removeRule(Rule)method which didn't remove the Rulebut added it again. Thanks to Peter Stibrany . maartenc
fix Fixed bug in BackedListcausing new elements to always be added at the first position if the size of the list is 1. Thanks to Robert Koberg . maartenc
update Upgraded the internal Aelfred2 parser to the latest version. maartenc
add Added initial JAXB support. Thanks to Wonne Keysers . maartenc
update Updated the STAX classes to provide document encoding. Thanks to Christian Niles . maartenc
add Added getXMLEncoding()method to org.dom4j.Documentwhich returns the encoding of the document. maartenc

Release 1.5-rc1 - 2004-07-04

TypeChangesBy
remove Removed the DocumentHelper.parseText(String xml, String encoding)method that was introduced in dom4j-1.5-beta2. maartenc
update Added the GNU JAXP DOM implementation to the default list of implementations in DOMWriter. maartenc
update Added method to ElementStackand DispatchHandlerto check if a handler is registered for a given path. Thanks to Wonne Keysers . maartenc
update ElementStackis now a public class. Thanks to Wonne Keysers . maartenc
update SAXContentHandler.endElement(...)can now throw SAXException. Thanks to Wonne Keysers . maartenc
fix Added the namespace-prefix of attributes to the paths returned by Attribute.getPath(Element context)and Attribute.getUniquePath(Element context). Thanks to Aaron Bell . maartenc
fix Element.declaredNamespaces()now only returns the namespaces that are declared on that element. Element.additionalNamespaces()now only returns namespaces that are declared on that element and is not the same as the namespace of that element. Thanks to Marc Pellmann . maartenc
fix Escape the values of internal DTD entity declarations when serializing to XML. Thanks to Marc Pellmann . maartenc
fix Fixed bug in AbstractElementcausing Node.getPath(Element context)to return an absolute path, even if a the current element was the same as the context element. The relative path "." is now returned. Thanks to Rob Grzywinski . maartenc
add Added method to Elementto retrieve all Namespacesfor a given URI. Thanks to Thomas Diesler . maartenc
fix Fixed bug in DOMReadercausing namespace declarations to get lost in some situations. Thanks to Thomas Diesler . maartenc
add Added a booleanValueOf(Object node)method to XPath. Thanks to Ben Scarlet . maartenc
fix Fixed bug in BeanElementwhich prevented proper execution of the bean samples. Thanks to Wonne Keysers . maartenc
update STAXEventWriternow uses XMLEventConsumerinstead of XMLEventWriter. Thanks to Christian Niles . maartenc
fix Fixed bug in SAXReaderthat caused problems parsing files in OSX. Thanks to Paul Libbrecht . maartenc
fix Fixed bug in XMLWriterthat caused whitespace to be added between successive calls of the characters(...)method. This is used particularly frequent in Apache Jelly. Thanks to Paul Libbrecht . maartenc
update Improved performance of NamespaceCachein multithreaded environments. Thanks to Brett Finnell . maartenc

Release 1.5-beta-2 - 2004-05-12

TypeChangesBy
add Added flag to OutputFormatthat supresses newline after XML declaration. wolfftw
update Upgraded dependencies to their latest version on ibiblio. maartenc
add Added method to DocumentHelperthat allows user to specify encoding when parsing an xml String. Thanks to Todd Wolff . maartenc
fix Fixed a ClassCastException bug in BeanElement. maartenc
fix Fixed a bug in SAXContentHandlerwhich caused a NullPointerExceptionin some situations. maartenc
fix Fixed bug which prevented an element's namespace prefix from being registered for use in xpath expressions. Thanks to Todd Wolff . maartenc
fix Fixed bug in XMLWriterthat caused duplication of the default namespace declaration. Thanks to Todd Wolff . maartenc
fix Added a bunch of patches to make the dom4j DOM classes more DOM compliant. Thanks to Curt Arnold . maartenc
update Fixed bug in DispatchHandlerwhich made the handler not reusable. Thanks to Ricardo Leon . maartenc
fix Fixed bug in SAXContentHandlerthat caused incorrect CDATA section parsing. Thanks to Todd Wolff . maartenc
fix Fixed bug in SAXContentHandlerthat caused incorrect entity handling. maartenc
fix Fixed bug in XMLWritercausing padding to be disabled, even if enabled in the specified outputformat. Thanks to Bo Gundersen . maartenc
add Added initial support for STaX streams. Thanks to Christian Niles . maartenc

Release 1.5-beta-1 - 2004-03-25

TypeChangesBy
fix Fixed encoding bug in Document.asXML()and DocumentHelper.parseText(). maartenc
fix Fixed bug in SAXReaderthat caused problems resolving relative URIs when parsing java.io.FileObjects. Thanks to Kohsuke Kawaguchi . maartenc
update The iterators returned by the Element.elementIterator(...)methods now support remove(). maartenc
update DOMWriterwrites now DOM Level 2 attributes and elements. Thanks to Geert Dendoncker and Joury Gokel . maartenc
update Use latest implementation of the Aelfred parser. maartenc
fix Fixed some problems with internal/external DTD declarations. Thanks to Bryan Thompson . maartenc
update Upgraded to Jaxen 1.1 beta 2. maartenc
update Ignore attribute order when comparing elements in NodeComparator. maartenc
update Fixed bug in XMLWriterwhere namespace declarations were duplicated. maartenc
fix Fixed bug in parsing a ProcessingInstruction. Thanks to Vladimir Kralik . maartenc
fix Added support for Stylesheetmodes. Thanks to Mark Diggory . maartenc
update Don't escape " and ' characters in attribute values if it's not necessary. Thanks to Christian Niles . maartenc
fix Fixed some DOMNodeHelperissues. Thanks to Henner Kollmann . maartenc
fix Fixed some datatype issues. Thanks to Thomas Draier . maartenc
fix Fixed an bug where the EntityResolver was not set on the XMLReader. maartenc
fix Fixed multithreaded access on DefaultElement. slehmann
fix Fixed problem parsing XML Files. Thanks to Geoffrey Vlassaks . maartenc
update Added xml:space attribute support based on XML Specification 1.0. ddlucas
update Maven build of dom4j is now nearly complete. Maven is now used for the website generation. maartenc
fix Fixed some bugs in BackedList. Thanks to Alessandro Vernet . maartenc

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/index.html0000644000175000017500000003266110242117727015024 0ustar ebourgebourgdom4j - dom4j: the flexible XML framework for Java
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Welcome to dom4j!

dom4j is an easy to use, open source library for working with XML, XPath and XSLT on the Java platform using the Java Collections Framework and with full support for DOM, SAX and JAXP.

News

  • dom4j 1.6.1 has been relased! This is a bugfix relase. Take a look at the changelog to see what has changed.
  • dom4j 1.6 has been released! Take a look at the changelog to see what has changed.
  • JetBrains was so kind to provide an open-source license of its famous IntelliJ IDEA product.
  • The internal Aelfred2 parser has been removed from the dom4j codebase due to an incompatible license. You can download a version of dom4j without Aelfred2 from the downloads page.
  • A maintenance relase of dom4j is available. Click here to see what has changed in dom4j 1.5.1.
  • dom4j 1.5 is finally released! A list of changes can be found here.
  • dom4j now has an open source license for the use of Clover
  • RefactorIT has added dom4j to it's list of featured open source projects. This means that all the power of RefactorIT is available for the dom4j sources.
  • The new dom4j 1.4 release is finally out featuring numerous bug fixes and patches.
  • Check out these new Performance Benchmarks comparing dom4j and Jaxen against Xerces and Xalan.
  • The new dom4j 1.3 release is out featuring numerous bug fixes and patches.
  • Check out Dennis Sosnoski's new article for IBM comparing various XML object models - its good stuff.
  • The new dom4j 1.2 release is out featuring improved whitespace handling for more efficient parsing, a new Swing TableModel for displaying XML data in Swing and numerous bug fixes and patches.
  • The Velocity projects new DVSL technology uses dom4j.
  • Interesting article outlining the social dominance of DOM and SAX and the importance of XPath.
  • The new dom4j 1.1 release is out featuring support for DTD declarations and numerous bug fixes and patches.
  • Read the latest performance benchmarks on IBM's site comparing dom4j against all the other XML document models.
  • The new dom4j 1.0 release is out featuring better SAX and Jaxen support, some performance tuning and numerous patches.
  • Sun's reference implementation of JAXM (Java API for XML Messaging) is based on dom4j!
  • The new dom4j 0.9 release is out featuring full Jaxen support!
  • Toby's cookbook is now online!
  • Updated the quick start guide

Features

  • designed for the Java platform with full support for the Java Collections Framework (Java 2 Collections)
  • full support for JAXP, TrAX, SAX, DOM, and XSLT
  • fully integrated XPath support for easy navigation of XML documents
  • event based proccessing mode to support for massive documents or XML streams
  • based on Java interfaces for flexible plug and play implementations.
  • support for XML Schema Data Type support using Kohsuke Kawaguchi's excellent Multi Schema Validator library

Getting Started

You can download the current release or a snapshot build via the download page.

For a quick overview of dom4j and how to use it try the reading the quick start guide or browsing the FAQ or the online JavaDoc.

To see how dom4j compares to other XML object models you could try reading our comparison

Contributors are welcome to join this project. Once you've browsed the FAQ you could try sending an email to one of the mailing lists below or check out the project page.

Useful Links

We really like XPath and if you are working with XML we highly recommend you try to experiment with it. If you need help learning XPath try the excellent Zvon tutorial .

Alternatively you could try Elliotte Rusty Harold's great XML in a nutshell .

Finally you could try reading the XPath spec.

Mailing Lists

For developers there is an email list at dom4j-dev where you can make requests for new features or changes to the API, discuss alternate implementation strategies, submit patches or just talk about any relevant topic of the day.

For dom4j users wanting help using dom4j there is an email list at dom4j-user where you can share ideas and experiences, ask for help, give us feedback or discuss your requirements.

You can browse the archives for here dom4j-dev or here dom4j-dev and here dom4j-user or here dom4j-user


2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/changelog-report.html0000644000175000017500000004424310242117761017152 0ustar ebourgebourgdom4j - Changelog Report
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
    • Change Log
    • Changes
    • Checkstyle
    • Clover
    • Developer Activity
    • FAQs
    • File Activity
    • JavaDocs
    • JavaDoc Report
    • JavaDoc Warnings Report
    • Metrics
    • Unit Tests
    • Source Xref
    • Test Xref
    • Project License
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Changelog Report

Timeframe: 30 days, Total Commits: 11 Total Number of Files Changed: 25

DateAuthorFile/Message
2005-05-14 12:39:35Maarten Coene

project.properties v 1.22.2.1

src/java/org/dom4j/xpp/ProxyXmlStartTag.java v 1.8.2.1

src/test/org/dom4j/XMLWriterTest.java v 1.7.2.1

Upgraded to pull-parser version 2.1.10.
2005-05-14 12:38:48Maarten Coene

lib/pull-parser-2.1.10.jar v 1.1

branches: 1.1.2; file pull-parser-2.1.10.jar was initially added on branch DOM4J_1_X_BRANCH.
2005-05-14 12:38:48Maarten Coene

lib/pull-parser-2.1.10.jar v 1.1.2.1

lib/pull-parser-2.jar v 1.1.2.1

Upgraded to pull-parser version 2.1.10.
2005-05-10 19:59:40Maarten Coene

src/java/org/dom4j/io/XMLWriter.java v 1.83.2.2

Hopefully fixed the newLine problem now...
2005-05-05 13:25:20Maarten Coene

src/java/org/dom4j/io/XMLWriter.java v 1.83.2.1

Fixed new-line problem reported by Thomas Fromm
2005-05-05 12:45:25Maarten Coene

src/java/org/dom4j/InvalidXPathException.java v 1.6.2.1

src/java/org/dom4j/xpath/DefaultXPath.java v 1.33.2.1

src/java/org/dom4j/xpath/XPathPattern.java v 1.18.2.1

Improved exception handling.
2005-05-05 12:28:16Maarten Coene

lib/test/junit-3.8.1.jar v 1.1

branches: 1.1.2; file junit-3.8.1.jar was initially added on branch DOM4J_1_X_BRANCH.
2005-05-05 12:28:16Maarten Coene

lib/test/junit-3.8.1.jar v 1.1.2.1

Added junit jar
2005-04-22 18:46:31Maarten Coene

src/java/org/dom4j/DocumentFactory.java v 1.46

src/java/org/dom4j/QName.java v 1.19

src/java/org/dom4j/dom/DOMDocumentFactory.java v 1.21

src/java/org/dom4j/util/PerThreadSingleton.java v 1.3

src/java/org/dom4j/util/SimpleSingleton.java v 1.3

The static method forName(String) from the type Class should be accessed in a static way
2005-04-19 19:52:54Maarten Coene

project.properties v 1.22

branches: 1.22.2; Fixed the xpath tests for the current jaxen CVS sources
2005-04-19 19:52:53Maarten Coene

build.xml v 1.161

project.xml v 1.53

lib/jaxen-1.1-beta-4.jar v 1.4

lib/jaxen-20050419.192021.jar v 1.1

src/test/org/dom4j/XPathExamplesTest.java v 1.5

xml/test/xpath/tests.xml v 1.33

Fixed the xpath tests for the current jaxen CVS sources

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/file-activity-report.html0000644000175000017500000002462110242117703017766 0ustar ebourgebourgdom4j - File Activity Analysis
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
    • Change Log
    • Changes
    • Checkstyle
    • Clover
    • Developer Activity
    • FAQs
    • File Activity
    • JavaDocs
    • JavaDoc Report
    • JavaDoc Warnings Report
    • Metrics
    • Unit Tests
    • Source Xref
    • Test Xref
    • Project License
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Activity by File

Timeframe: 30 days, Total Commits: 11 Total Number of Files Changed: 25

File NameNumber of times changed
lib/pull-parser-2.1.10.jar 2
lib/test/junit-3.8.1.jar 2
project.properties 2
src/java/org/dom4j/io/XMLWriter.java 2
build.xml 1
lib/jaxen-1.1-beta-4.jar 1
lib/jaxen-20050419.192021.jar 1
lib/pull-parser-2.jar 1
project.xml 1
src/java/org/dom4j/DocumentFactory.java 1
src/java/org/dom4j/InvalidXPathException.java 1
src/java/org/dom4j/QName.java 1
src/java/org/dom4j/dom/DOMDocumentFactory.java 1
src/java/org/dom4j/util/PerThreadSingleton.java 1
src/java/org/dom4j/util/SimpleSingleton.java 1
src/java/org/dom4j/xpath/DefaultXPath.java 1
src/java/org/dom4j/xpath/XPathPattern.java 1
src/java/org/dom4j/xpp/ProxyXmlStartTag.java 1
src/test/org/dom4j/XMLWriterTest.java 1
src/test/org/dom4j/XPathExamplesTest.java 1
xml/test/xpath/tests.xml 1

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/benchmarks/0000755000175000017500000000000010242117577015137 5ustar ebourgebourgdom4j-1.6.1/docs/benchmarks/xpath/0000755000175000017500000000000012133227266016261 5ustar ebourgebourgdom4j-1.6.1/docs/benchmarks/xpath/item.xslt0000644000175000017500000000173510242117750020134 0ustar ebourgebourg
dom4j-1.6.1/docs/benchmarks/xpath/PerfDOM4J.java0000644000175000017500000002216610242117763020564 0ustar ebourgebourg import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.XPath; import org.dom4j.io.DOMWriter; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class PerfDOM4J { public static void main(String args[]) { Document doc; try { int numrec = 1; numrec = 10000; System.out.println("\n10000 Elements ------------------"); doc = PerfDOM4J.createDocument(numrec, 20, 1); PerfDOM4J.createW3CDOM(doc); PerfDOM4J.write(doc, "dom4j_" + numrec + ".xml"); // PerfDOM4J.parse(numrec,1); // PerfDOM4J.transform(doc,"item.xslt",1); PerfDOM4J.xpath(doc, "/*/*/Attr1x1", 1); PerfDOM4J.xpath(doc, "/*/*/Attr1x5000", 1); PerfDOM4J.xpath(doc, "/*/*/Attr1x9999", 1); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x1", 1); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x5000", 1); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x9999", 1); PerfDOM4J.xpathNodes(doc, "/*/Item", 3); numrec = 1000; System.out.println("\n1000 Elements -------------------"); doc = PerfDOM4J.createDocument(numrec, 20, 1); PerfDOM4J.createW3CDOM(doc); PerfDOM4J.write(doc, "dom4j_" + numrec + ".xml"); PerfDOM4J.parse(numrec, 3); PerfDOM4J.transform(doc, "item.xslt", 3); PerfDOM4J.xpath(doc, "/*/*/Attr1x1", 3); PerfDOM4J.xpath(doc, "/*/*/Attr1x500", 3); PerfDOM4J.xpath(doc, "/*/*/Attr1x999", 3); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x1", 3); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x500", 3); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x999", 3); PerfDOM4J.xpathNodes(doc, "/*/Item", 10); numrec = 100; System.out.println("\n100 Elements --------------------"); doc = PerfDOM4J.createDocument(numrec, 20, 10); PerfDOM4J.createW3CDOM(doc); PerfDOM4J.write(doc, "dom4j_" + numrec + ".xml"); PerfDOM4J.parse(numrec, 10); PerfDOM4J.transform(doc, "item.xslt", 10); PerfDOM4J.xpath(doc, "/*/*/Attr1x1", 10); PerfDOM4J.xpath(doc, "/*/*/Attr1x50", 10); PerfDOM4J.xpath(doc, "/*/*/Attr1x99", 10); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x1", 10); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x50", 10); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x99", 10); PerfDOM4J.xpathNodes(doc, "/*/Item", 100); numrec = 10; System.out.println("\n10 Elements ---------------------"); doc = PerfDOM4J.createDocument(numrec, 20, 100); PerfDOM4J.createW3CDOM(doc); PerfDOM4J.write(doc, "dom4j_" + numrec + ".xml"); PerfDOM4J.parse(numrec, 100); PerfDOM4J.transform(doc, "item.xslt", 10); PerfDOM4J.xpath(doc, "/*/*/Attr1x5", 1000); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x1", 1000); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x5", 1000); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x9", 1000); PerfDOM4J.xpathNodes(doc, "/*/Item", 1000); numrec = 1; System.out.println("\n1 Element -----------------------"); doc = PerfDOM4J.createDocument(numrec, 20, 100); PerfDOM4J.createW3CDOM(doc); PerfDOM4J.write(doc, "dom4j_" + numrec + ".xml"); PerfDOM4J.parse(numrec, 100); PerfDOM4J.transform(doc, "item.xslt", 10); PerfDOM4J.xpath(doc, "/*/*/Attr1x1", 1000); PerfDOM4J.xpathNodes(doc, "/*/*/Attr1x1", 1000); PerfDOM4J.xpathNodes(doc, "/*/Item", 1000); } catch (IOException ie) { ie.printStackTrace(); } } public static Document createDocument(int iNumRecs, int iNumFlds, int pp) { double start = System.currentTimeMillis(); Document document = null; for (int kk = 0; kk < pp; kk++) { document = DocumentHelper.createDocument(); Element root = document.addElement("ItemResultSet"); for (int ii = 0; ii < iNumRecs; ii++) { Element Record = root.addElement("Item"); for (int jj = 0; jj < iNumFlds; jj++) { Record.addElement("Attr" + jj + "x" + ii).addText( "123456789"); } } } double end = System.currentTimeMillis(); System.err.println("Creation time : " + (end - start) / pp); return document; } public static Document parse(int iNumRecs, int kk) { File file = new File("dom4j_" + iNumRecs + ".xml"); double start = System.currentTimeMillis(); Document document = null; for (int pp = 0; pp < kk; pp++) { try { SAXReader SAXrd = new SAXReader(); SAXrd.read(file); } catch (Exception e) { e.printStackTrace(); } } double end = System.currentTimeMillis(); System.err.println("Parsing time for :" + 1.000 * (end - start) / kk); return document; } public static void createW3CDOM(Document doc) { long start = System.currentTimeMillis(); try { DOMWriter dw = new DOMWriter(); dw.write(doc); } catch (Exception de) { } long end = System.currentTimeMillis(); System.err.println("W3C Creation time for :" + (end - start)); } public static void write(Document document, String name) throws IOException { long start = System.currentTimeMillis(); // lets write to a file try { OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter(name), format); writer.write(document); writer.close(); } catch (IOException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.err.println("DOM4J File write time :" + (end - start) + " " + name); } public static void transform(Document xmlDoc, String xslFile, int kk) { System.err.println("DOM4J start transform "); int ii = 1; try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource( xslFile)); long start = System.currentTimeMillis(); for (ii = 0; ii < kk; ii++) { Source source = new DocumentSource(xmlDoc); DocumentResult result = new DocumentResult(); transformer.transform(source, result); // output the transformed document } long end = System.currentTimeMillis(); System.err .println("DOM4J transform time :" + (end - start) / ii); } catch (Exception e) { e.printStackTrace(); } } public static void xpath(Document document, String xpathExp, int kk) { long start = System.currentTimeMillis(); XPath xpath = document.createXPath(xpathExp); for (int ii = 0; ii < kk; ii++) { Node node = xpath.selectSingleNode(document); if ((node != null) & (ii == 0)) { String val = node.getStringValue(); // System.out.println(val); } } long end = System.currentTimeMillis(); System.err.println("DOM4J xpath time :" + (end - start) / kk); } public static void xpathNodes(Document document, String xpathExp, int kk) { long start = System.currentTimeMillis(); XPath xpath = document.createXPath(xpathExp); for (int ii = 0; ii < kk; ii++) { try { List nodeList = xpath.selectNodes(document); if ((nodeList != null) && (nodeList.size() > 0)) { Node node = (Node) nodeList.get(0); if ((node != null) & (ii == 0)) { String val = node.getStringValue(); // System.out.println(val); } } } catch (Exception e) { e.printStackTrace(); } } long end = System.currentTimeMillis(); System.err.println("DOM4J xpath Nodes time :" + 1.000 * (end - start) / kk); } } dom4j-1.6.1/docs/benchmarks/xpath/index.html0000644000175000017500000013017510242117577020267 0ustar ebourgebourg Dom4J performance versus Xerces

Dom4J performance versus Xerces / Xalan

Martin Bhm, Jean-Jacques Dubray

Eigner Precision Lifecycle Management

www.eigner.com

Introduction

We have created a simple test bed to evaluate the performance of DOM4J versus Xerces/Xalan. These results are intended to give a rough idea rather than exhaustive test suite. In particular we focus our study on XML document which look like database result set. It is pretty clear that performance results may vary greatly based on the topology of your XML.

The test was designed with two topologies in mind: 

a) to have elements only and each element name is unique in the whole document.

<?xml version="1.0" encoding="UTF-8"?>

<ItemResultSet>

<Item>

<Attr0x0>123456789</Attr0x0>

<Attr1x0>123456789</Attr1x0>

<Attr2x0>123456789</Attr2x0>

<Attr3x0>123456789</Attr3x0>

<Attr4x0>123456789</Attr4x0>

<Attr5x0>123456789</Attr5x0>

<Attr6x0>123456789</Attr6x0>

<Attr7x0>123456789</Attr7x0>

<Attr8x0>123456789</Attr8x0>

<Attr9x0>123456789</Attr9x0>

<Attr10x0>123456789</Attr10x0>

<Attr11x0>123456789</Attr11x0>

<Attr12x0>123456789</Attr12x0>

<Attr13x0>123456789</Attr13x0>

...

</Item>

<Item>

<Attr0x1>123456789</Attr0x1>

<Attr1x1>123456789</Attr1x1>

<Attr2x1>123456789</Attr2x1>

...

</ItemResultSet>

b) To use attributes only

<?xml version="1.0" encoding="UTF-8"?>

<ItemResultSet>

<Item guid="0" Attr0="123456789" Attr1="123456789" .../>

<Item guid="1" Attr0="123456789" Attr1="123456789" .../>

</ItemResultSet>

 

 

We have tested for 1000,100,10,1 items the time it takes to:

  • create a document
  • write it to disk
  • reparse it from disk (I don't have a good disk)
  • transform it to some other XML format
  • run a series of XPath statements for both selectNodes and selectSingleNode (where applicable)

    a) 

    /*/*/Attr1x1

    /*/*/Attr1x500

    /*/*/Attr1x999

    /*/*/Item

    b) 

    /*/*[@id="1"]

    /*/*[@id="500"]

    /*/*[@id="999""]

All tests are running on my lapdog (PIII, 500MHz, 512Mb) We allocate a heap size of 256 Mb when we start the test.

 

Results

case a), comparison between Dom4j/Jaxen versus Xerces/Xalan

All times in ms
Create Document Write Document to disk Reparse the document from disk
Items dom4j xalan dom4j xalan dom4j xalan
1000 641.0 571.0 531 852 2020 2664
100 9.0 20.0 60 61 62.99 68.6
10 0.7 1.0 10 10 11.92 14.62
1 0.1 0.0 10 10 8.01 8.31

 

The most surprising result comes from executing XPath statements. Xalan does warn us in the JavaDoc that things could be a little slow.

selectSingleNode()

All times in ms 1000 Items in the document
dom4j Xalan
/*/*/Attr1x1 127 10
/*/*/Attr1x500 20 661
/*/*/Attr1x999 23 1662
100 Items in the document
dom4j  Xalan
/*/*/Attr1x1 2 3.0
/*/*/Attr1x50 3 13.0
/*/*/Attr1x99 2 55.1

 

selectNodes()

All times in ms 1000 Items in the document
dom4j Xalan
/*/*/Attr1x1 16.6 1633
/*/*/Attr1x500 20 1772
/*/*/Attr1x999 20.0 1733
/*/Item 2.0 1742
100 Items in the document
dom4j Xalan
/*/*/Attr1x1 1.0 35.0
/*/*/Attr1x50 2.0 36.1
/*/*/Attr1x99 1.0 49.0
/*/Item 0.2 49.0

 

selectNodes()

All times in ms /*/*/Attr1x500
dom4j  Xalan
1000 20.0 1793
100 2.0 36.1
10 0.1 11.72
1 0.1 4.3

 

case b), we use Dom4j/Jaxen and compare how it behaves with a document that contains only element elements versus document that model the same data as attribute attributes

All times in ms
Create Document Write Document to disk Reparse the document from disk
Items dom4j - elements dom4j - attrs dom4j - elements dom4j - attrs dom4j - elements dom4j - attrs
1000 641.0 100 531 140 2020 207
100 9.0 8.0 60 20 62.99 24
10 0.7 0.9 10 10 11.92 8.31
1 0.1 0.1 10 10 8.01 6.81

 

The most surprising result comes from executing XPath statements. Xalan does warn us in the JavaDoc that things could be a little slow.

selectSingleNode()

All times in ms 1000 Items in the document
Dom4j - elements dom4j - attrs
/*/*/Attr1x1 127 36
/*/*/Attr1x500 20 33
/*/*/Attr1x999 23 37
100 Items in the document
Dom4j - elements dom4j - attrs
/*/*/Attr1x1 2 4
/*/*/Attr1x50 3 4
/*/*/Attr1x99 2 4

 

selectNodes()

All times in ms 1000 Items in the document
dom4j - elements dom4j - attrs
/*/*/Attr1x1 16.6 36.6
/*/*/Attr1x500 20 36.6
/*/*/Attr1x999 20.0 36.6
/*/Item 2.0 1.7
100 Items in the document
Dom4j - elements dom4j - attrs
/*/*/Attr1x1 1.0 3.0
/*/*/Attr1x50 2.0 4.1
/*/*/Attr1x99 1.0 4
/*/Item 0.2 0.2

 

selectNodes()

All times in ms /*/*/Attr1x500
dom4j - elements dom4j - attrs
1000 20.0 36.6
100 2.0 4.1
10 0.1 0.4
1 0.1 0.1

 

c) We also run a simple XSLT test which took the first XML formant (elements) and transformed it to the second format (attr) or conversely.

All times in ms. dom4j el -> attr dom4j attr -> el Xalan el -> attr
10000 12558  10044  12338
1000 1181 874 1913
100 98 83 123
10 12 11 20
1 3 4 10

Conclusion

These number suggest one should use the XPathAPI class of Xalan with great caution, if at all

The syntax of Xpath statements must be chosen carefully. Contrary to some belief, and of the topology of our XML format, using /*/* or // was most efficient compared to the absolute path /ItemResultSet/Item

It appears more efficient to use selectNodes with Dom4j even if one needs a single node.

With DOM4J, it is about twice as fast when running XPath against a document which contains elements vs attributes.

In our case, we found that Dom4j is faster than Xalant for XSLT transformations. We do not claim this is  a general result, but rather a datapoint

Resources

Here's the source code and data for these tests. Try them for yourself

PerfDOM4J.java
PerfDOM4JAttr.java
PerfW3C.java
item.xslt
w3c_100.xml

 

 

dom4j-1.6.1/docs/benchmarks/xpath/w3c_100.html0000644000175000017500000041561610242117746020240 0ustar ebourgebourg 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 dom4j-1.6.1/docs/benchmarks/xpath/PerfDOM4JAttr.java0000644000175000017500000002445210242117720021410 0ustar ebourgebourg import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.XPath; import org.dom4j.io.DOMWriter; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class PerfDOM4JAttr { public static void main(String args[]) { Document doc; try { int numrec = 1; numrec = 10000; System.out.println("\n1000 Elements -------------------"); doc = PerfDOM4JAttr.createDocument(numrec, 20, 1); PerfDOM4JAttr.createW3CDOM(doc); PerfDOM4JAttr.write(doc, "DOM4JAttr_" + numrec + ".xml"); PerfDOM4JAttr.parse(numrec, 1); // PerfDOM4JAttr.transform(doc,"item.xslt",1); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"1\"]", 3); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"500\"]", 3); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"999\"]", 3); PerfDOM4JAttr .xpathNodes(doc, "/ItemResultSet/Item[@guid=\"1\"]", 3); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"500\"]", 3); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"999\"]", 3); PerfDOM4JAttr.xpathNodes(doc, "/*/Item", 100); numrec = 1000; System.out.println("\n1000 Elements -------------------"); doc = PerfDOM4JAttr.createDocument(numrec, 20, 1); PerfDOM4JAttr.createW3CDOM(doc); PerfDOM4JAttr.write(doc, "DOM4JAttr_" + numrec + ".xml"); PerfDOM4JAttr.parse(numrec, 3); PerfDOM4JAttr.transform(doc, "item.xslt", 3); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"1\"]", 3); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"500\"]", 3); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"999\"]", 3); PerfDOM4JAttr .xpathNodes(doc, "/ItemResultSet/Item[@guid=\"1\"]", 3); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"500\"]", 3); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"999\"]", 3); PerfDOM4JAttr.xpathNodes(doc, "/*/Item", 100); numrec = 100; System.out.println("\n100 Elements --------------------"); doc = PerfDOM4JAttr.createDocument(numrec, 20, 10); PerfDOM4JAttr.createW3CDOM(doc); PerfDOM4JAttr.write(doc, "DOM4JAttr_" + numrec + ".xml"); PerfDOM4JAttr.parse(numrec, 10); PerfDOM4JAttr.transform(doc, "item.xslt", 10); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"1\"]", 10); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"50\"]", 10); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"99\"]", 10); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"1\"]", 10); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"50\"]", 10); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"99\"]", 10); PerfDOM4JAttr.xpathNodes(doc, "/*/Item", 100); numrec = 10; System.out.println("\n10 Elements ---------------------"); doc = PerfDOM4JAttr.createDocument(numrec, 20, 100); PerfDOM4JAttr.createW3CDOM(doc); PerfDOM4JAttr.write(doc, "DOM4JAttr_" + numrec + ".xml"); PerfDOM4JAttr.parse(numrec, 100); PerfDOM4JAttr.transform(doc, "item.xslt", 10); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"1\"]", 100); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"5\"]", 100); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"9\"]", 100); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"1\"]", 100); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"5\"]", 100); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"9\"]", 100); PerfDOM4JAttr.xpathNodes(doc, "/*/Item", 100); numrec = 1; System.out.println("\n1 Element -----------------------"); doc = PerfDOM4JAttr.createDocument(numrec, 20, 100); PerfDOM4JAttr.createW3CDOM(doc); PerfDOM4JAttr.write(doc, "DOM4JAttr_" + numrec + ".xml"); PerfDOM4JAttr.parse(numrec, 100); PerfDOM4JAttr.transform(doc, "item.xslt", 10); PerfDOM4JAttr.xpath(doc, "/ItemResultSet/Item[@guid=\"1\"]", 100); PerfDOM4JAttr.xpathNodes(doc, "/ItemResultSet/Item[@guid=\"1\"]", 100); PerfDOM4JAttr.xpathNodes(doc, "/*/Item", 100); } catch (IOException ie) { ie.printStackTrace(); } } public static Document createDocument(int iNumRecs, int iNumFlds, int pp) { double start = System.currentTimeMillis(); Document document = null; for (int kk = 0; kk < pp; kk++) { document = DocumentHelper.createDocument(); Element root = document.addElement("ItemResultSet"); for (int ii = 0; ii < iNumRecs; ii++) { Element Record = root.addElement("Item").addAttribute("guid", "" + ii); for (int jj = 0; jj < iNumFlds; jj++) { Record.addAttribute("Attr" + jj, "123456789"); } } } double end = System.currentTimeMillis(); System.err.println("Creation time : " + (end - start) / pp); return document; } public static Document parse(int iNumRecs, int kk) { File file = new File("DOM4JAttr_" + iNumRecs + ".xml"); double start = System.currentTimeMillis(); Document document = null; for (int pp = 0; pp < kk; pp++) { try { SAXReader SAXrd = new SAXReader(); SAXrd.read(file); } catch (Exception e) { e.printStackTrace(); } } double end = System.currentTimeMillis(); System.err.println("Parsing time for :" + 1.000 * (end - start) / kk); return document; } public static void createW3CDOM(Document doc) { long start = System.currentTimeMillis(); try { DOMWriter dw = new DOMWriter(); dw.write(doc); } catch (Exception de) { } long end = System.currentTimeMillis(); System.err.println("W3C Creation time for :" + (end - start)); } public static void write(Document document, String name) throws IOException { long start = System.currentTimeMillis(); // lets write to a file try { OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter(name), format); writer.write(document); writer.close(); } catch (IOException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.err.println("DOM4JAttr File write time :" + (end - start) + " " + name); } public static void transform(Document xmlDoc, String xslFile, int kk) { System.err.println("DOM4JAttr start transform "); int ii = 1; try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource( xslFile)); long start = System.currentTimeMillis(); for (ii = 0; ii < kk; ii++) { Source source = new DocumentSource(xmlDoc); DocumentResult result = new DocumentResult(); transformer.transform(source, result); // output the transformed document } long end = System.currentTimeMillis(); System.err.println("DOM4JAttr transform time :" + (end - start) / ii); } catch (Exception e) { e.printStackTrace(); } } public static void xpath(Document document, String xpathExp, int kk) { long start = System.currentTimeMillis(); XPath xpath = document.createXPath(xpathExp); for (int ii = 0; ii < kk; ii++) { Node node = xpath.selectSingleNode(document); if ((node != null) & (ii == 0)) { String val = node.getStringValue(); // System.out.println("xpath OK:"+val); } } long end = System.currentTimeMillis(); System.err.println("DOM4JAttr xpath time :" + (end - start) / kk); } public static void xpathNodes(Document document, String xpathExp, int kk) { long start = System.currentTimeMillis(); XPath xpath = document.createXPath(xpathExp); for (int ii = 0; ii < kk; ii++) { try { List nodeList = xpath.selectNodes(document); if ((nodeList != null) && (nodeList.size() > 0)) { Node node = (Node) nodeList.get(0); if ((node != null) & (ii == 0)) { String val = node.getStringValue(); // System.out.println("xpathNodes OK:"+val); } } } catch (Exception e) { e.printStackTrace(); } } long end = System.currentTimeMillis(); System.err.println("DOM4JAttr xpath Nodes time :" + 1.000 * (end - start) / kk); } } dom4j-1.6.1/docs/benchmarks/xpath/PerfW3C.java0000644000175000017500000002074310242117723020336 0ustar ebourgebourg import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import org.apache.xerces.dom.DocumentImpl; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.apache.xpath.XPathAPI; import org.dom4j.io.SAXReader; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class PerfW3C { public static void main(String args[]) { Document doc; System.err.println("W3C createDocument:"); int numrec; long start = 0; long end = 0; numrec = 1000; System.out.println("\n1000 Elements ---------------------------------"); doc = PerfW3C.createDocument(numrec, 20, 1); PerfW3C.write(doc, "w3c_" + numrec + ".xml"); PerfW3C.parse(numrec, 1); PerfW3C.transform(doc, "item.xslt", 1); PerfW3C.xpath(doc, "/*/*/Attr1x1", 1); PerfW3C.xpath(doc, "/*/*/Attr1x500", 1); PerfW3C.xpath(doc, "/*/*/Attr1x999", 1); PerfW3C.xpathNodes(doc, "/*/*/Attr1x1", 1); PerfW3C.xpathNodes(doc, "/*/*/Attr1x500", 1); PerfW3C.xpathNodes(doc, "/*/*/Attr1x999", 1); PerfW3C.xpathNodes(doc, "/*/Item", 1); numrec = 100; System.out.println("\n100 Elements ----------------------------------"); doc = PerfW3C.createDocument(numrec, 20, 1); PerfW3C.write(doc, "w3c_" + numrec + ".xml"); PerfW3C.transform(doc, "item.xslt", 10); PerfW3C.parse(numrec, 10); PerfW3C.xpath(doc, "/*/*/Attr0x1", 10); PerfW3C.xpath(doc, "/*/*/Attr0x50", 10); PerfW3C.xpath(doc, "/*/*/Attr0x99", 10); PerfW3C.xpathNodes(doc, "/*/*/Attr0x0", 10); PerfW3C.xpathNodes(doc, "/*/*/Attr1x50", 10); PerfW3C.xpathNodes(doc, "/*/*/Attr1x99", 10); PerfW3C.xpathNodes(doc, "/*/Item", 10); numrec = 10; System.out.println("\n10 Elements -----------------------------------"); doc = PerfW3C.createDocument(numrec, 20, 10); PerfW3C.write(doc, "w3c_" + numrec + ".xml"); PerfW3C.parse(numrec, 50); PerfW3C.transform(doc, "item.xslt", 10); PerfW3C.xpath(doc, "/*/*/Attr5", 100); PerfW3C.xpathNodes(doc, "/*/*/Attr1x5", 100); PerfW3C.xpathNodes(doc, "/*/Item", 100); numrec = 1; System.out.println("\n1 Elements ------------------------------------"); doc = PerfW3C.createDocument(numrec, 20, 10); PerfW3C.write(doc, "w3c_" + numrec + ".xml"); PerfW3C.parse(numrec, 100); PerfW3C.transform(doc, "item.xslt", 10); PerfW3C.xpath(doc, "/*/*/Attr1x0", 100); PerfW3C.xpathNodes(doc, "/*/*/Attr1x0", 100); PerfW3C.xpathNodes(doc, "/*/Item", 100); } public static Document createDocument(int iNumRecs, int iNumFlds, int pp) { double start = System.currentTimeMillis(); Document document = null; for (int kk = 0; kk < pp; kk++) { document = new DocumentImpl(); Element root = document.createElement("ItemResultSet"); // Create // Root // Element document.appendChild(root); for (int ii = 0; ii < iNumRecs; ii++) { Element Record = document.createElement("Item"); root.appendChild(Record); for (int jj = 0; jj < iNumFlds; jj++) { /* * AttrImpl a = * (AttrImpl)document.createAttribute("Attr"+jj); * a.setNodeValue("123456789"); Record.setAttributeNode(a); */ Element field = document.createElement("Attr" + jj + "x" + ii); field.appendChild(document.createTextNode("123456789")); Record.appendChild(field); } } } double end = System.currentTimeMillis(); System.err.println("Creation time :" + (end - start) / pp); return document; } public static void write(Document document, String name) { long start = System.currentTimeMillis(); // lets write to a file OutputFormat format = new OutputFormat(document); // Serialize DOM format.setIndent(2); format.setLineSeparator(System.getProperty("line.separator")); format.setLineWidth(80); try { FileWriter writer = new FileWriter(name); BufferedWriter buf = new BufferedWriter(writer); XMLSerializer FileSerial = new XMLSerializer(writer, format); FileSerial.asDOMSerializer(); // As a DOM Serializer FileSerial.serialize(document); } catch (IOException ioe) { ioe.printStackTrace(); } long end = System.currentTimeMillis(); System.err.println("W3C File write time :" + (end - start) + " " + name); } public static Document parse(int iNumRecs, int kk) { File file = new File("dom4j_" + iNumRecs + ".xml"); double start = System.currentTimeMillis(); Document document = null; for (int pp = 0; pp < kk; pp++) { try { SAXReader SAXrd = new SAXReader(); SAXrd.read(file); } catch (Exception e) { e.printStackTrace(); } } double end = System.currentTimeMillis(); // System.err.println("DOM4J createDocument:" + "Num Rec. = " + iNumRecs // + " Num. Fld.=" + iNumFlds); System.err.println("Parsing time for :" + iNumRecs + " " + (end - start) / kk); return document; } public static void transform(Document xmlDoc, String xslFile, int kk) { int ii = 1; try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource( xslFile)); long start = System.currentTimeMillis(); for (ii = 0; ii < kk; ii++) { DOMSource source = new DOMSource(xmlDoc); DOMResult result = new DOMResult(); transformer.transform(source, result); } long end = System.currentTimeMillis(); System.err.println("W3C transform time :" + (end - start) / ii); } catch (Exception e) { e.printStackTrace(); } } public static void xpath(Document document, String xpathExp, int pp) { long start = System.currentTimeMillis(); for (int ii = 0; ii < pp; ii++) { try { Node node = XPathAPI.selectSingleNode(document, xpathExp); if ((node != null) & (ii == 0)) { String val = node.getNodeName(); // System.out.println(val); } } catch (Exception e) { e.printStackTrace(); } } long end = System.currentTimeMillis(); System.err.println("W3C xpath time :" + 1.000 * (end - start) / pp); } public static void xpathNodes(Document document, String xpathExp, int pp) { long start = System.currentTimeMillis(); for (int ii = 0; ii < pp; ii++) { try { NodeList nodeList = XPathAPI.selectNodeList(document, xpathExp); if ((nodeList != null) && (nodeList.getLength() > 0)) { Node node = nodeList.item(0); if ((node != null) & (ii == 0)) { String val = node.getNodeName(); // System.out.println(val); } } } catch (Exception e) { e.printStackTrace(); } } long end = System.currentTimeMillis(); System.err.println("W3C xpathNodes time :" + 1.000 * (end - start) / pp); } } dom4j-1.6.1/docs/downloads.html0000644000175000017500000001015610242117723015676 0ustar ebourgebourgdom4j - Downloads
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Downloads

You must define the maven.xdoc.distributionUrlproperty if you wish to generate the download report.


2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/xref/0000755000175000017500000000000012133227266013764 5ustar ebourgebourgdom4j-1.6.1/docs/xref/overview-frame.html0000644000175000017500000000465610242117706017617 0ustar ebourgebourg dom4j 1.6.1 Reference

All Classes

Packages

  • org.dom4j
  • org.dom4j.bean
  • org.dom4j.datatype
  • org.dom4j.dom
  • org.dom4j.dtd
  • org.dom4j.io
  • org.dom4j.jaxb
  • org.dom4j.rule
  • org.dom4j.rule.pattern
  • org.dom4j.swing
  • org.dom4j.tree
  • org.dom4j.util
  • org.dom4j.xpath
  • org.dom4j.xpp
dom4j-1.6.1/docs/xref/allclasses-frame.html0000644000175000017500000005461410242117615020075 0ustar ebourgebourg All Classes

All Classes

  • AbstractAttribute
  • AbstractBranch
  • AbstractCDATA
  • AbstractCharacterData
  • AbstractComment
  • AbstractDocument
  • AbstractDocumentType
  • AbstractElement
  • AbstractEntity
  • AbstractNode
  • AbstractProcessingInstruction
  • AbstractText
  • Action
  • Attribute
  • AttributeDecl
  • AttributeHelper
  • BackedList
  • BaseElement
  • BeanAttribute
  • BeanAttributeList
  • BeanDocumentFactory
  • BeanElement
  • BeanMetaData
  • Branch
  • BranchTreeNode
  • CDATA
  • CharacterData
  • Comment
  • ConcurrentReaderHashMap
  • ContentListFacade
  • DOMAttribute
  • DOMAttributeNodeMap
  • DOMCDATA
  • DOMComment
  • DOMDocument
  • DOMDocumentFactory
  • DOMDocumentType
  • DOMElement
  • DOMEntityReference
  • DOMNamespace
  • DOMNodeHelper
  • DOMProcessingInstruction
  • DOMReader
  • DOMText
  • DOMWriter
  • DatatypeAttribute
  • DatatypeDocumentFactory
  • DatatypeElement
  • DatatypeElementFactory
  • DefaultAttribute
  • DefaultCDATA
  • DefaultComment
  • DefaultDocument
  • DefaultDocumentType
  • DefaultElement
  • DefaultEntity
  • DefaultNamespace
  • DefaultNamespaceContext
  • DefaultPattern
  • DefaultProcessingInstruction
  • DefaultText
  • DefaultXPath
  • DispatchHandler
  • Document
  • DocumentException
  • DocumentFactory
  • DocumentHelper
  • DocumentInputSource
  • DocumentResult
  • DocumentSource
  • DocumentTreeModel
  • DocumentType
  • Element
  • ElementDecl
  • ElementHandler
  • ElementIterator
  • ElementModifier
  • ElementNameIterator
  • ElementPath
  • ElementQNameIterator
  • ElementStack
  • Entity
  • ExternalEntityDecl
  • FilterIterator
  • FlyweightAttribute
  • FlyweightCDATA
  • FlyweightComment
  • FlyweightEntity
  • FlyweightProcessingInstruction
  • FlyweightText
  • HTMLWriter
  • IllegalAddException
  • IndexedDocumentFactory
  • IndexedElement
  • InternalEntityDecl
  • InvalidSchemaException
  • InvalidXPathException
  • JAXBModifier
  • JAXBObjectHandler
  • JAXBObjectModifier
  • JAXBReader
  • JAXBRuntimeException
  • JAXBSupport
  • JAXBWriter
  • JAXPHelper
  • LeafTreeNode
  • Mode
  • NamedTypeResolver
  • Namespace
  • NamespaceCache
  • NamespaceStack
  • Node
  • NodeComparator
  • NodeFilter
  • NodeTypePattern
  • NonLazyDocumentFactory
  • NonLazyElement
  • NullAction
  • OutputFormat
  • Pattern
  • PerThreadSingleton
  • ProcessingInstruction
  • ProxyDocumentFactory
  • ProxyXmlStartTag
  • PruningDispatchHandler
  • PruningElementStack
  • QName
  • QNameCache
  • Rule
  • RuleManager
  • RuleSet
  • SAXContentHandler
  • SAXEventRecorder
  • SAXHelper
  • SAXModifier
  • SAXModifyContentHandler
  • SAXModifyElementHandler
  • SAXModifyException
  • SAXModifyReader
  • SAXReader
  • SAXValidator
  • SAXWriter
  • STAXEventReader
  • STAXEventWriter
  • SchemaParser
  • SimpleSingleton
  • SingleIterator
  • SingletonStrategy
  • Stylesheet
  • Text
  • UserDataAttribute
  • UserDataDocumentFactory
  • UserDataElement
  • Visitor
  • VisitorSupport
  • XMLErrorHandler
  • XMLResult
  • XMLTableColumnDefinition
  • XMLTableDefinition
  • XMLTableModel
  • XMLWriter
  • XPP3Reader
  • XPPReader
  • XPath
  • XPathException
  • XPathPattern
dom4j-1.6.1/docs/xref/stylesheet.css0000644000175000017500000000243410242117717016670 0ustar ebourgebourg/* Javadoc style sheet */ /* Define colors, fonts and other style attributes here to override the defaults */ body { background-color: #fff; font-family: Arial, Helvetica, sans-serif; } a:link { color: #00f; } a:visited { color: #00a; } a:active, a:hover { color: #f30 !important; } ul, li { list-style-type:none ; margin:0; padding:0; } table td{ padding: 3px; border: 1px solid #000; } table{ width:100%; border: 1px solid #000; border-collapse: collapse; } div.overview { background-color:#ddd; padding: 4px 4px 4px 0; } div.overview li, div.framenoframe li { display: inline; } div.framenoframe { text-align: center; font-size: x-small; } div.framenoframe li { margin: 0 3px 0 3px; } div.overview li { margin:3px 3px 0 3px; padding: 4px; } li.selected { background-color:#888; color: #fff; font-weight: bold; } table.summary { margin-bottom: 20px; } table.summary td, table.summary th { font-weight: bold; text-align: left; padding: 3px; } table.summary th{ background-color:#036; color: #fff; } table.summary td{ background-color:#eee; border: 1px solid black; } em { color: #A00; } em.comment { color: #390; } .string { color: #009; } div#footer { text-align:center; } #overview { padding:2px; } hr { height: 1px; color: #000; }dom4j-1.6.1/docs/xref/overview-summary.html0000644000175000017500000000765210242117756020226 0ustar ebourgebourg dom4j 1.6.1 Reference
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

dom4j 1.6.1 Reference

Packages
org.dom4j
org.dom4j.bean
org.dom4j.datatype
org.dom4j.dom
org.dom4j.dtd
org.dom4j.io
org.dom4j.jaxb
org.dom4j.rule
org.dom4j.rule.pattern
org.dom4j.swing
org.dom4j.tree
org.dom4j.util
org.dom4j.xpath
org.dom4j.xpp
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref/index.html0000644000175000017500000000134610242117765015766 0ustar ebourgebourg dom4j 1.6.1 Reference <h1>Frame Alert</h1> <p> You don't have frames. Go <a href="overview-summary.html">here</a> </p> dom4j-1.6.1/docs/xref/org/0000755000175000017500000000000010242117544014547 5ustar ebourgebourgdom4j-1.6.1/docs/xref/org/dom4j/0000755000175000017500000000000012133227266015570 5ustar ebourgebourgdom4j-1.6.1/docs/xref/org/dom4j/ElementPath.html0000644000175000017500000002427510242117725020673 0ustar ebourgebourg ElementPath xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  /***
11   * This interface is used by {@link ElementHandler}instances to retrieve
12   * information about the current path hierarchy they are to process. It's
13   * primary use is to retrieve the current {@link Element}being processed.
14   * 
15   * @author <a href="mailto:dwhite@equipecom.com">Dave White </a>
16   * @version $Revision: 1.6 $
17   */
18  public interface ElementPath {
19      /***
20       * DOCUMENT ME!
21       * 
22       * @return the number of elements in the path
23       */
24      int size();
25  
26      /***
27       * DOCUMENT ME!
28       * 
29       * @param depth
30       *            DOCUMENT ME!
31       * 
32       * @return the element at the specified depth index, 0 = root element
33       */
34      Element getElement(int depth);
35  
36      /***
37       * DOCUMENT ME!
38       * 
39       * @return the path as a string
40       */
41      String getPath();
42  
43      /***
44       * DOCUMENT ME!
45       * 
46       * @return the current element
47       */
48      Element getCurrent();
49  
50      /***
51       * Adds the <code>ElementHandler</code> to be called when the specified
52       * path is encounted. The path can be either an absolute path (i.e. prefixed
53       * with "/") or a relative path (i.e. assummed to be a child of the current
54       * path as retrieved by <b>getPath </b>.
55       * 
56       * @param path
57       *            is the path to be handled
58       * @param handler
59       *            is the <code>ElementHandler</code> to be called by the event
60       *            based processor.
61       */
62      void addHandler(String path, ElementHandler handler);
63  
64      /***
65       * Removes the <code>ElementHandler</code> from the event based processor,
66       * for the specified path. The path can be either an absolute path (i.e.
67       * prefixed with "/") or a relative path (i.e. assummed to be a child of the
68       * current path as retrieved by <b>getPath </b>.
69       * 
70       * @param path
71       *            is the path to remove the <code>ElementHandler</code> for.
72       */
73      void removeHandler(String path);
74  }
75  
76  /*
77   * Redistribution and use of this software and associated documentation
78   * ("Software"), with or without modification, are permitted provided that the
79   * following conditions are met:
80   * 
81   * 1. Redistributions of source code must retain copyright statements and
82   * notices. Redistributions must also contain a copy of this document.
83   * 
84   * 2. Redistributions in binary form must reproduce the above copyright notice,
85   * this list of conditions and the following disclaimer in the documentation
86   * and/or other materials provided with the distribution.
87   * 
88   * 3. The name "DOM4J" must not be used to endorse or promote products derived
89   * from this Software without prior written permission of MetaStuff, Ltd. For
90   * written permission, please contact dom4j-info@metastuff.com.
91   * 
92   * 4. Products derived from this Software may not be called "DOM4J" nor may
93   * "DOM4J" appear in their names without prior written permission of MetaStuff,
94   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
95   * 
96   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
97   * 
98   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
99   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
100  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
101  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
102  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
103  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
104  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
105  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
106  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
107  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
108  * POSSIBILITY OF SUCH DAMAGE.
109  * 
110  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
111  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/bean/0000755000175000017500000000000012133227266016475 5ustar ebourgebourgdom4j-1.6.1/docs/xref/org/dom4j/bean/package-summary.html0000644000175000017500000000523210242117742022447 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.bean

Class Summary
BeanAttribute
BeanAttributeList
BeanDocumentFactory
BeanElement
BeanMetaData
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref/org/dom4j/bean/package-frame.html0000644000175000017500000000225010242117747022046 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.bean

org.dom4j.bean

Classes

  • BeanAttribute
  • BeanAttributeList
  • BeanDocumentFactory
  • BeanElement
  • BeanMetaData
dom4j-1.6.1/docs/xref/org/dom4j/bean/BeanElement.html0000644000175000017500000004303410242117752021543 0ustar ebourgebourg BeanElement xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.bean;
9   
10  import java.util.List;
11  
12  import org.dom4j.Attribute;
13  import org.dom4j.DocumentFactory;
14  import org.dom4j.Element;
15  import org.dom4j.Namespace;
16  import org.dom4j.QName;
17  import org.dom4j.tree.DefaultElement;
18  import org.dom4j.tree.NamespaceStack;
19  
20  import org.xml.sax.Attributes;
21  
22  /***
23   * <p>
24   * <code>BeanElement</code> uses a Java Bean to store its attributes.
25   * </p>
26   * 
27   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
28   * @version $Revision: 1.15 $
29   */
30  public class BeanElement extends DefaultElement {
31      /*** The <code>DocumentFactory</code> instance used by default */
32      private static final DocumentFactory DOCUMENT_FACTORY = BeanDocumentFactory
33              .getInstance();
34  
35      /*** The JavaBean which defines my attributes */
36      private Object bean;
37  
38      public BeanElement(String name, Object bean) {
39          this(DOCUMENT_FACTORY.createQName(name), bean);
40      }
41  
42      public BeanElement(String name, Namespace namespace, Object bean) {
43          this(DOCUMENT_FACTORY.createQName(name, namespace), bean);
44      }
45  
46      public BeanElement(QName qname, Object bean) {
47          super(qname);
48          this.bean = bean;
49      }
50  
51      public BeanElement(QName qname) {
52          super(qname);
53      }
54  
55      /***
56       * DOCUMENT ME!
57       * 
58       * @return the JavaBean associated with this element
59       */
60      public Object getData() {
61          return bean;
62      }
63  
64      public void setData(Object data) {
65          this.bean = data;
66  
67          // force the attributeList to be lazily
68          // created next time an attribute related
69          // method is called again.
70          setAttributeList(null);
71      }
72  
73      public Attribute attribute(String name) {
74          return getBeanAttributeList().attribute(name);
75      }
76  
77      public Attribute attribute(QName qname) {
78          return getBeanAttributeList().attribute(qname);
79      }
80  
81      public Element addAttribute(String name, String value) {
82          Attribute attribute = attribute(name);
83  
84          if (attribute != null) {
85              attribute.setValue(value);
86          }
87  
88          return this;
89      }
90  
91      public Element addAttribute(QName qName, String value) {
92          Attribute attribute = attribute(qName);
93  
94          if (attribute != null) {
95              attribute.setValue(value);
96          }
97  
98          return this;
99      }
100 
101     public void setAttributes(List attributes) {
102         throw new UnsupportedOperationException("Not implemented yet.");
103     }
104 
105     // Method overridden from AbstractElement
106     public void setAttributes(Attributes attributes,
107             NamespaceStack namespaceStack, boolean noNamespaceAttributes) {
108         String className = attributes.getValue("class");
109 
110         if (className != null) {
111             try {
112                 Class beanClass = Class.forName(className, true,
113                         BeanElement.class.getClassLoader());
114                 this.setData(beanClass.newInstance());
115 
116                 for (int i = 0; i < attributes.getLength(); i++) {
117                     String attributeName = attributes.getLocalName(i);
118 
119                     if (!"class".equalsIgnoreCase(attributeName)) {
120                         addAttribute(attributeName, attributes.getValue(i));
121                     }
122                 }
123             } catch (Exception ex) {
124                 // What to do here?
125                 ((BeanDocumentFactory) this.getDocumentFactory())
126                         .handleException(ex);
127             }
128         } else {
129             super.setAttributes(attributes, namespaceStack,
130                     noNamespaceAttributes);
131         }
132     }
133 
134     // Implementation methods
135     // -------------------------------------------------------------------------
136     protected DocumentFactory getDocumentFactory() {
137         return DOCUMENT_FACTORY;
138     }
139 
140     protected BeanAttributeList getBeanAttributeList() {
141         return (BeanAttributeList) attributeList();
142     }
143 
144     /***
145      * A Factory Method pattern which lazily creates a List implementation used
146      * to store content
147      * 
148      * @return DOCUMENT ME!
149      */
150     protected List createAttributeList() {
151         return new BeanAttributeList(this);
152     }
153 
154     protected List createAttributeList(int size) {
155         return new BeanAttributeList(this);
156     }
157 }
158 
159 /*
160  * Redistribution and use of this software and associated documentation
161  * ("Software"), with or without modification, are permitted provided that the
162  * following conditions are met:
163  * 
164  * 1. Redistributions of source code must retain copyright statements and
165  * notices. Redistributions must also contain a copy of this document.
166  * 
167  * 2. Redistributions in binary form must reproduce the above copyright notice,
168  * this list of conditions and the following disclaimer in the documentation
169  * and/or other materials provided with the distribution.
170  * 
171  * 3. The name "DOM4J" must not be used to endorse or promote products derived
172  * from this Software without prior written permission of MetaStuff, Ltd. For
173  * written permission, please contact dom4j-info@metastuff.com.
174  * 
175  * 4. Products derived from this Software may not be called "DOM4J" nor may
176  * "DOM4J" appear in their names without prior written permission of MetaStuff,
177  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
178  * 
179  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
180  * 
181  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
182  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
183  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
184  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
185  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
186  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
187  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
188  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
189  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
190  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
191  * POSSIBILITY OF SUCH DAMAGE.
192  * 
193  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
194  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/bean/BeanMetaData.html0000644000175000017500000004321610242117616021633 0ustar ebourgebourg BeanMetaData xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.bean;
9   
10  import java.beans.BeanInfo;
11  import java.beans.IntrospectionException;
12  import java.beans.Introspector;
13  import java.beans.PropertyDescriptor;
14  import java.lang.reflect.Method;
15  import java.util.HashMap;
16  import java.util.Map;
17  
18  import org.dom4j.DocumentFactory;
19  import org.dom4j.QName;
20  
21  /***
22   * <p>
23   * <code>BeanMetaData</code> contains metadata about a bean class.
24   * </p>
25   * 
26   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
27   * @version $Revision: 1.10 $
28   */
29  public class BeanMetaData {
30      /*** Empty arguments for reflection calls */
31      protected static final Object[] NULL_ARGS = {};
32  
33      /*** Singleton cache */
34      private static Map singletonCache = new HashMap();
35  
36      private static final DocumentFactory DOCUMENT_FACTORY = BeanDocumentFactory
37              .getInstance();
38  
39      /*** The class of the bean */
40      private Class beanClass;
41  
42      /*** Property descriptors for the bean */
43      private PropertyDescriptor[] propertyDescriptors;
44  
45      /*** QNames for the attributes */
46      private QName[] qNames;
47  
48      /*** Read methods used for getting properties */
49      private Method[] readMethods;
50  
51      /*** Write methods used for setting properties */
52      private Method[] writeMethods;
53  
54      /*** Index of names and QNames to indices */
55      private Map nameMap = new HashMap();
56  
57      public BeanMetaData(Class beanClass) {
58          this.beanClass = beanClass;
59  
60          if (beanClass != null) {
61              try {
62                  BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
63                  propertyDescriptors = beanInfo.getPropertyDescriptors();
64              } catch (IntrospectionException e) {
65                  handleException(e);
66              }
67          }
68  
69          if (propertyDescriptors == null) {
70              propertyDescriptors = new PropertyDescriptor[0];
71          }
72  
73          int size = propertyDescriptors.length;
74          qNames = new QName[size];
75          readMethods = new Method[size];
76          writeMethods = new Method[size];
77  
78          for (int i = 0; i < size; i++) {
79              PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
80              String name = propertyDescriptor.getName();
81              QName qName = DOCUMENT_FACTORY.createQName(name);
82              qNames[i] = qName;
83              readMethods[i] = propertyDescriptor.getReadMethod();
84              writeMethods[i] = propertyDescriptor.getWriteMethod();
85  
86              Integer index = new Integer(i);
87              nameMap.put(name, index);
88              nameMap.put(qName, index);
89          }
90      }
91  
92      /***
93       * Static helper method to find and cache meta data objects for bean types
94       * 
95       * @param beanClass
96       *            DOCUMENT ME!
97       * 
98       * @return DOCUMENT ME!
99       */
100     public static BeanMetaData get(Class beanClass) {
101         BeanMetaData answer = (BeanMetaData) singletonCache.get(beanClass);
102 
103         if (answer == null) {
104             answer = new BeanMetaData(beanClass);
105             singletonCache.put(beanClass, answer);
106         }
107 
108         return answer;
109     }
110 
111     /***
112      * DOCUMENT ME!
113      * 
114      * @return the number of attribtutes for this bean type
115      */
116     public int attributeCount() {
117         return propertyDescriptors.length;
118     }
119 
120     public BeanAttributeList createAttributeList(BeanElement parent) {
121         return new BeanAttributeList(parent, this);
122     }
123 
124     public QName getQName(int index) {
125         return qNames[index];
126     }
127 
128     public int getIndex(String name) {
129         Integer index = (Integer) nameMap.get(name);
130 
131         return (index != null) ? index.intValue() : (-1);
132     }
133 
134     public int getIndex(QName qName) {
135         Integer index = (Integer) nameMap.get(qName);
136 
137         return (index != null) ? index.intValue() : (-1);
138     }
139 
140     public Object getData(int index, Object bean) {
141         try {
142             Method method = readMethods[index];
143 
144             return method.invoke(bean, NULL_ARGS);
145         } catch (Exception e) {
146             handleException(e);
147 
148             return null;
149         }
150     }
151 
152     public void setData(int index, Object bean, Object data) {
153         try {
154             Method method = writeMethods[index];
155             Object[] args = {data};
156             method.invoke(bean, args);
157         } catch (Exception e) {
158             handleException(e);
159         }
160     }
161 
162     // Implementation methods
163     // -------------------------------------------------------------------------
164     protected void handleException(Exception e) {
165         // ignore introspection exceptions
166     }
167 }
168 
169 /*
170  * Redistribution and use of this software and associated documentation
171  * ("Software"), with or without modification, are permitted provided that the
172  * following conditions are met:
173  * 
174  * 1. Redistributions of source code must retain copyright statements and
175  * notices. Redistributions must also contain a copy of this document.
176  * 
177  * 2. Redistributions in binary form must reproduce the above copyright notice,
178  * this list of conditions and the following disclaimer in the documentation
179  * and/or other materials provided with the distribution.
180  * 
181  * 3. The name "DOM4J" must not be used to endorse or promote products derived
182  * from this Software without prior written permission of MetaStuff, Ltd. For
183  * written permission, please contact dom4j-info@metastuff.com.
184  * 
185  * 4. Products derived from this Software may not be called "DOM4J" nor may
186  * "DOM4J" appear in their names without prior written permission of MetaStuff,
187  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
188  * 
189  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
190  * 
191  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
192  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
193  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
194  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
195  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
196  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
197  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
198  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
199  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
200  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
201  * POSSIBILITY OF SUCH DAMAGE.
202  * 
203  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
204  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/bean/BeanDocumentFactory.html0000644000175000017500000003144710242117760023264 0ustar ebourgebourg BeanDocumentFactory xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.bean;
9   
10  import org.dom4j.Attribute;
11  import org.dom4j.DocumentFactory;
12  import org.dom4j.Element;
13  import org.dom4j.QName;
14  import org.dom4j.tree.DefaultAttribute;
15  
16  import org.xml.sax.Attributes;
17  
18  /***
19   * <p>
20   * <code>BeanDocumentFactory</code> is a factory of DOM4J objects which may be
21   * BeanElements which are backed by JavaBeans and their properties.
22   * </p>
23   * 
24   * <p>
25   * The tree built allows full XPath expressions from anywhere on the tree.
26   * </p>
27   * 
28   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
29   * @version $Revision: 1.14 $
30   */
31  public class BeanDocumentFactory extends DocumentFactory {
32      /*** The Singleton instance */
33      private static BeanDocumentFactory singleton = new BeanDocumentFactory();
34  
35      /***
36       * <p>
37       * Access to the singleton instance of this factory.
38       * </p>
39       * 
40       * @return the default singleon instance
41       */
42      public static DocumentFactory getInstance() {
43          return singleton;
44      }
45  
46      // Factory methods
47      public Element createElement(QName qname) {
48          Object bean = createBean(qname);
49  
50          if (bean == null) {
51              return new BeanElement(qname);
52          } else {
53              return new BeanElement(qname, bean);
54          }
55      }
56  
57      public Element createElement(QName qname, Attributes attributes) {
58          Object bean = createBean(qname, attributes);
59  
60          if (bean == null) {
61              return new BeanElement(qname);
62          } else {
63              return new BeanElement(qname, bean);
64          }
65      }
66  
67      public Attribute createAttribute(Element owner, QName qname, String value) {
68          return new DefaultAttribute(qname, value);
69      }
70  
71      // Implementation methods
72      protected Object createBean(QName qname) {
73          return null;
74      }
75  
76      protected Object createBean(QName qname, Attributes attributes) {
77          String value = attributes.getValue("class");
78  
79          if (value != null) {
80              try {
81                  Class beanClass = Class.forName(value, true,
82                          BeanDocumentFactory.class.getClassLoader());
83  
84                  return beanClass.newInstance();
85              } catch (Exception e) {
86                  handleException(e);
87              }
88          }
89  
90          return null;
91      }
92  
93      protected void handleException(Exception e) {
94          // ignore introspection exceptions
95          System.out.println("#### Warning: couldn't create bean: " + e);
96      }
97  }
98  
99  /*
100  * Redistribution and use of this software and associated documentation
101  * ("Software"), with or without modification, are permitted provided that the
102  * following conditions are met:
103  * 
104  * 1. Redistributions of source code must retain copyright statements and
105  * notices. Redistributions must also contain a copy of this document.
106  * 
107  * 2. Redistributions in binary form must reproduce the above copyright notice,
108  * this list of conditions and the following disclaimer in the documentation
109  * and/or other materials provided with the distribution.
110  * 
111  * 3. The name "DOM4J" must not be used to endorse or promote products derived
112  * from this Software without prior written permission of MetaStuff, Ltd. For
113  * written permission, please contact dom4j-info@metastuff.com.
114  * 
115  * 4. Products derived from this Software may not be called "DOM4J" nor may
116  * "DOM4J" appear in their names without prior written permission of MetaStuff,
117  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
118  * 
119  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
120  * 
121  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
122  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
123  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
124  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
125  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
126  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
127  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
128  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
129  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
130  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
131  * POSSIBILITY OF SUCH DAMAGE.
132  * 
133  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
134  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/bean/BeanAttribute.html0000644000175000017500000002241510242117733022114 0ustar ebourgebourg BeanAttribute xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.bean;
9   
10  import org.dom4j.Element;
11  import org.dom4j.QName;
12  import org.dom4j.tree.AbstractAttribute;
13  
14  /***
15   * <p>
16   * <code>BeanAttribute</code> represents a mutable XML attribute which is
17   * backed by a property of the JavaBean of its parent element.
18   * </p>
19   * 
20   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
21   * @version $Revision: 1.7 $
22   */
23  public class BeanAttribute extends AbstractAttribute {
24      /*** The list of Bean attributes */
25      private final BeanAttributeList beanList;
26  
27      /*** The index in the Bean attribute list */
28      private final int index;
29  
30      public BeanAttribute(BeanAttributeList beanList, int index) {
31          this.beanList = beanList;
32          this.index = index;
33      }
34  
35      public QName getQName() {
36          return beanList.getQName(index);
37      }
38  
39      public Element getParent() {
40          return beanList.getParent();
41      }
42  
43      public String getValue() {
44          Object data = getData();
45  
46          return (data != null) ? data.toString() : null;
47      }
48  
49      public void setValue(String data) {
50          beanList.setData(index, data);
51      }
52  
53      public Object getData() {
54          return beanList.getData(index);
55      }
56  
57      public void setData(Object data) {
58          beanList.setData(index, data);
59      }
60  }
61  
62  /*
63   * Redistribution and use of this software and associated documentation
64   * ("Software"), with or without modification, are permitted provided that the
65   * following conditions are met:
66   * 
67   * 1. Redistributions of source code must retain copyright statements and
68   * notices. Redistributions must also contain a copy of this document.
69   * 
70   * 2. Redistributions in binary form must reproduce the above copyright notice,
71   * this list of conditions and the following disclaimer in the documentation
72   * and/or other materials provided with the distribution.
73   * 
74   * 3. The name "DOM4J" must not be used to endorse or promote products derived
75   * from this Software without prior written permission of MetaStuff, Ltd. For
76   * written permission, please contact dom4j-info@metastuff.com.
77   * 
78   * 4. Products derived from this Software may not be called "DOM4J" nor may
79   * "DOM4J" appear in their names without prior written permission of MetaStuff,
80   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
81   * 
82   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
83   * 
84   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
85   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
86   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
87   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
88   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
89   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
90   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
91   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
92   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
93   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
94   * POSSIBILITY OF SUCH DAMAGE.
95   * 
96   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
97   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/bean/BeanAttributeList.html0000644000175000017500000004174210242117700022746 0ustar ebourgebourg BeanAttributeList xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.bean;
9   
10  import java.util.AbstractList;
11  
12  import org.dom4j.Attribute;
13  import org.dom4j.QName;
14  
15  /***
16   * <p>
17   * <code>BeanAttributeList</code> implements a list of Attributes which are
18   * the properties of a JavaBean.
19   * </p>
20   * 
21   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
22   * @version $Revision: 1.9 $
23   */
24  public class BeanAttributeList extends AbstractList {
25      /*** The BeanElement that this */
26      private BeanElement parent;
27  
28      /*** The BeanElement that this */
29      private BeanMetaData beanMetaData;
30  
31      /*** The attributes */
32      private BeanAttribute[] attributes;
33  
34      public BeanAttributeList(BeanElement parent, BeanMetaData beanMetaData) {
35          this.parent = parent;
36          this.beanMetaData = beanMetaData;
37          this.attributes = new BeanAttribute[beanMetaData.attributeCount()];
38      }
39  
40      public BeanAttributeList(BeanElement parent) {
41          this.parent = parent;
42  
43          Object data = parent.getData();
44          Class beanClass = (data != null) ? data.getClass() : null;
45          this.beanMetaData = BeanMetaData.get(beanClass);
46          this.attributes = new BeanAttribute[beanMetaData.attributeCount()];
47      }
48  
49      public Attribute attribute(String name) {
50          int index = beanMetaData.getIndex(name);
51  
52          return attribute(index);
53      }
54  
55      public Attribute attribute(QName qname) {
56          int index = beanMetaData.getIndex(qname);
57  
58          return attribute(index);
59      }
60  
61      public BeanAttribute attribute(int index) {
62          if ((index >= 0) && (index <= attributes.length)) {
63              BeanAttribute attribute = attributes[index];
64  
65              if (attribute == null) {
66                  attribute = createAttribute(parent, index);
67                  attributes[index] = attribute;
68              }
69  
70              return attribute;
71          }
72  
73          return null;
74      }
75  
76      public BeanElement getParent() {
77          return parent;
78      }
79  
80      public QName getQName(int index) {
81          return beanMetaData.getQName(index);
82      }
83  
84      public Object getData(int index) {
85          return beanMetaData.getData(index, parent.getData());
86      }
87  
88      public void setData(int index, Object data) {
89          beanMetaData.setData(index, parent.getData(), data);
90      }
91  
92      // List interface
93      // -------------------------------------------------------------------------
94      public int size() {
95          return attributes.length;
96      }
97  
98      public Object get(int index) {
99          BeanAttribute attribute = attributes[index];
100 
101         if (attribute == null) {
102             attribute = createAttribute(parent, index);
103             attributes[index] = attribute;
104         }
105 
106         return attribute;
107     }
108 
109     public boolean add(Object object) {
110         throw new UnsupportedOperationException("add(Object) unsupported");
111     }
112 
113     public void add(int index, Object object) {
114         throw new UnsupportedOperationException("add(int,Object) unsupported");
115     }
116 
117     public Object set(int index, Object object) {
118         throw new UnsupportedOperationException("set(int,Object) unsupported");
119     }
120 
121     public boolean remove(Object object) {
122         return false;
123     }
124 
125     public Object remove(int index) {
126         BeanAttribute attribute = (BeanAttribute) get(index);
127         Object oldValue = attribute.getValue();
128         attribute.setValue(null);
129 
130         return oldValue;
131     }
132 
133     public void clear() {
134         for (int i = 0, size = attributes.length; i < size; i++) {
135             BeanAttribute attribute = attributes[i];
136 
137             if (attribute != null) {
138                 attribute.setValue(null);
139             }
140         }
141     }
142 
143     // Implementation methods
144     // -------------------------------------------------------------------------
145     protected BeanAttribute createAttribute(BeanElement element, int index) {
146         return new BeanAttribute(this, index);
147     }
148 }
149 
150 /*
151  * Redistribution and use of this software and associated documentation
152  * ("Software"), with or without modification, are permitted provided that the
153  * following conditions are met:
154  * 
155  * 1. Redistributions of source code must retain copyright statements and
156  * notices. Redistributions must also contain a copy of this document.
157  * 
158  * 2. Redistributions in binary form must reproduce the above copyright notice,
159  * this list of conditions and the following disclaimer in the documentation
160  * and/or other materials provided with the distribution.
161  * 
162  * 3. The name "DOM4J" must not be used to endorse or promote products derived
163  * from this Software without prior written permission of MetaStuff, Ltd. For
164  * written permission, please contact dom4j-info@metastuff.com.
165  * 
166  * 4. Products derived from this Software may not be called "DOM4J" nor may
167  * "DOM4J" appear in their names without prior written permission of MetaStuff,
168  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
169  * 
170  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
171  * 
172  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
173  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
174  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
175  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
176  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
177  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
178  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
179  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
180  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
181  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
182  * POSSIBILITY OF SUCH DAMAGE.
183  * 
184  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
185  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/QName.html0000644000175000017500000006134710242117703017463 0ustar ebourgebourg QName xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import java.io.IOException;
11  import java.io.ObjectInputStream;
12  import java.io.ObjectOutputStream;
13  import java.io.Serializable;
14  
15  import org.dom4j.tree.QNameCache;
16  import org.dom4j.util.SingletonStrategy;
17  
18  /***
19   * <p>
20   * <code>QName</code> represents a qualified name value of an XML element or
21   * attribute. It consists of a local name and a {@link Namespace}instance. This
22   * object is immutable.
23   * </p>
24   * 
25   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
26   */
27  public class QName implements Serializable {
28      /*** The Singleton instance */
29      private static SingletonStrategy singleton = null;
30  
31      static {
32          try {
33              String defaultSingletonClass = "org.dom4j.util.SimpleSingleton";
34              Class clazz = null;
35              try {
36                  String singletonClass = defaultSingletonClass;
37                  singletonClass = System.getProperty(
38                          "org.dom4j.QName.singleton.strategy", singletonClass);
39                  clazz = Class.forName(singletonClass);
40              } catch (Exception exc1) {
41                  try {
42                      String singletonClass = defaultSingletonClass;
43                      clazz = Class.forName(singletonClass);
44                  } catch (Exception exc2) {
45                  }
46              }
47              singleton = (SingletonStrategy) clazz.newInstance();
48              singleton.setSingletonClassName(QNameCache.class.getName());
49          } catch (Exception exc3) {
50          }
51      }
52  
53      /*** The local name of the element or attribute */
54      private String name;
55  
56      /*** The qualified name of the element or attribute */
57      private String qualifiedName;
58  
59      /*** The Namespace of this element or attribute */
60      private transient Namespace namespace;
61  
62      /*** A cached version of the hashcode for efficiency */
63      private int hashCode;
64  
65      /*** The document factory used for this QName if specified or null */
66      private DocumentFactory documentFactory;
67  
68      public QName(String name) {
69          this(name, Namespace.NO_NAMESPACE);
70      }
71  
72      public QName(String name, Namespace namespace) {
73          this.name = (name == null) ? "" : name;
74          this.namespace = (namespace == null) ? Namespace.NO_NAMESPACE
75                  : namespace;
76      }
77  
78      public QName(String name, Namespace namespace, String qualifiedName) {
79          this.name = (name == null) ? "" : name;
80          this.qualifiedName = qualifiedName;
81          this.namespace = (namespace == null) ? Namespace.NO_NAMESPACE
82                  : namespace;
83      }
84  
85      public static QName get(String name) {
86          return getCache().get(name);
87      }
88  
89      public static QName get(String name, Namespace namespace) {
90          return getCache().get(name, namespace);
91      }
92  
93      public static QName get(String name, String prefix, String uri) {
94          if (((prefix == null) || (prefix.length() == 0)) && (uri == null)) {
95              return QName.get(name);
96          } else if ((prefix == null) || (prefix.length() == 0)) {
97              return getCache().get(name, Namespace.get(uri));
98          } else if (uri == null) {
99              return QName.get(name);
100         } else {
101             return getCache().get(name, Namespace.get(prefix, uri));
102         }
103     }
104 
105     public static QName get(String qualifiedName, String uri) {
106         if (uri == null) {
107             return getCache().get(qualifiedName);
108         } else {
109             return getCache().get(qualifiedName, uri);
110         }
111     }
112 
113     public static QName get(String localName, Namespace namespace,
114             String qualifiedName) {
115         return getCache().get(localName, namespace, qualifiedName);
116     }
117 
118     /***
119      * DOCUMENT ME!
120      * 
121      * @return the local name
122      */
123     public String getName() {
124         return name;
125     }
126 
127     /***
128      * DOCUMENT ME!
129      * 
130      * @return the qualified name in the format <code>prefix:localName</code>
131      */
132     public String getQualifiedName() {
133         if (qualifiedName == null) {
134             String prefix = getNamespacePrefix();
135 
136             if ((prefix != null) && (prefix.length() > 0)) {
137                 qualifiedName = prefix + ":" + name;
138             } else {
139                 qualifiedName = name;
140             }
141         }
142 
143         return qualifiedName;
144     }
145 
146     /***
147      * DOCUMENT ME!
148      * 
149      * @return the namespace of this QName
150      */
151     public Namespace getNamespace() {
152         return namespace;
153     }
154 
155     /***
156      * DOCUMENT ME!
157      * 
158      * @return the namespace URI of this QName
159      */
160     public String getNamespacePrefix() {
161         if (namespace == null) {
162             return "";
163         }
164 
165         return namespace.getPrefix();
166     }
167 
168     /***
169      * DOCUMENT ME!
170      * 
171      * @return the namespace URI of this QName
172      */
173     public String getNamespaceURI() {
174         if (namespace == null) {
175             return "";
176         }
177 
178         return namespace.getURI();
179     }
180 
181     /***
182      * DOCUMENT ME!
183      * 
184      * @return the hash code based on the qualified name and the URI of the
185      *         namespace.
186      */
187     public int hashCode() {
188         if (hashCode == 0) {
189             hashCode = getName().hashCode() ^ getNamespaceURI().hashCode();
190 
191             if (hashCode == 0) {
192                 hashCode = 0xbabe;
193             }
194         }
195 
196         return hashCode;
197     }
198 
199     public boolean equals(Object object) {
200         if (this == object) {
201             return true;
202         } else if (object instanceof QName) {
203             QName that = (QName) object;
204 
205             // we cache hash codes so this should be quick
206             if (hashCode() == that.hashCode()) {
207                 return getName().equals(that.getName())
208                         && getNamespaceURI().equals(that.getNamespaceURI());
209             }
210         }
211 
212         return false;
213     }
214 
215     public String toString() {
216         return super.toString() + " [name: " + getName() + " namespace: \""
217                 + getNamespace() + "\"]";
218     }
219 
220     /***
221      * DOCUMENT ME!
222      * 
223      * @return the factory that should be used for Elements of this QName
224      */
225     public DocumentFactory getDocumentFactory() {
226         return documentFactory;
227     }
228 
229     public void setDocumentFactory(DocumentFactory documentFactory) {
230         this.documentFactory = documentFactory;
231     }
232 
233     private void writeObject(ObjectOutputStream out) throws IOException {
234         // We use writeObject() and not writeUTF() to minimize space
235         // This allows for writing pointers to already written strings
236         out.writeObject(namespace.getPrefix());
237         out.writeObject(namespace.getURI());
238 
239         out.defaultWriteObject();
240     }
241 
242     private void readObject(ObjectInputStream in) throws IOException,
243             ClassNotFoundException {
244         String prefix = (String) in.readObject();
245         String uri = (String) in.readObject();
246 
247         in.defaultReadObject();
248 
249         namespace = Namespace.get(prefix, uri);
250     }
251 
252     private static QNameCache getCache() {
253         QNameCache cache = (QNameCache) singleton.instance();
254         return cache;
255     }
256 }
257 
258 
259 
260 /*
261  * Redistribution and use of this software and associated documentation
262  * ("Software"), with or without modification, are permitted provided that the
263  * following conditions are met:
264  * 
265  * 1. Redistributions of source code must retain copyright statements and
266  * notices. Redistributions must also contain a copy of this document.
267  * 
268  * 2. Redistributions in binary form must reproduce the above copyright notice,
269  * this list of conditions and the following disclaimer in the documentation
270  * and/or other materials provided with the distribution.
271  * 
272  * 3. The name "DOM4J" must not be used to endorse or promote products derived
273  * from this Software without prior written permission of MetaStuff, Ltd. For
274  * written permission, please contact dom4j-info@metastuff.com.
275  * 
276  * 4. Products derived from this Software may not be called "DOM4J" nor may
277  * "DOM4J" appear in their names without prior written permission of MetaStuff,
278  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
279  * 
280  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
281  * 
282  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
283  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
284  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
285  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
286  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
287  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
288  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
289  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
290  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
291  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
292  * POSSIBILITY OF SUCH DAMAGE.
293  * 
294  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
295  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/DocumentException.html0000644000175000017500000002573010242117716022117 0ustar ebourgebourg DocumentException xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import java.io.PrintStream;
11  import java.io.PrintWriter;
12  
13  /***
14   * <p>
15   * <code>DocumentException</code> is a nested Exception which may be thrown
16   * during the processing of a DOM4J document.
17   * </p>
18   * 
19   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
20   * @version $Revision: 1.7 $
21   */
22  public class DocumentException extends Exception {
23      /*** A wrapped <code>Throwable</code> */
24      private Throwable nestedException;
25  
26      public DocumentException() {
27          super("Error occurred in DOM4J application.");
28      }
29  
30      public DocumentException(String message) {
31          super(message);
32      }
33  
34      public DocumentException(Throwable nestedException) {
35          super(nestedException.getMessage());
36          this.nestedException = nestedException;
37      }
38  
39      public DocumentException(String message, Throwable nestedException) {
40          super(message);
41          this.nestedException = nestedException;
42      }
43  
44      public Throwable getNestedException() {
45          return nestedException;
46      }
47  
48      public String getMessage() {
49          if (nestedException != null) {
50              return super.getMessage() + " Nested exception: "
51                      + nestedException.getMessage();
52          } else {
53              return super.getMessage();
54          }
55      }
56  
57      public void printStackTrace() {
58          super.printStackTrace();
59  
60          if (nestedException != null) {
61              System.err.print("Nested exception: ");
62              nestedException.printStackTrace();
63          }
64      }
65  
66      public void printStackTrace(PrintStream out) {
67          super.printStackTrace(out);
68  
69          if (nestedException != null) {
70              out.println("Nested exception: ");
71              nestedException.printStackTrace(out);
72          }
73      }
74  
75      public void printStackTrace(PrintWriter writer) {
76          super.printStackTrace(writer);
77  
78          if (nestedException != null) {
79              writer.println("Nested exception: ");
80              nestedException.printStackTrace(writer);
81          }
82      }
83  }
84  
85  /*
86   * Redistribution and use of this software and associated documentation
87   * ("Software"), with or without modification, are permitted provided that the
88   * following conditions are met:
89   * 
90   * 1. Redistributions of source code must retain copyright statements and
91   * notices. Redistributions must also contain a copy of this document.
92   * 
93   * 2. Redistributions in binary form must reproduce the above copyright notice,
94   * this list of conditions and the following disclaimer in the documentation
95   * and/or other materials provided with the distribution.
96   * 
97   * 3. The name "DOM4J" must not be used to endorse or promote products derived
98   * from this Software without prior written permission of MetaStuff, Ltd. For
99   * written permission, please contact dom4j-info@metastuff.com.
100  * 
101  * 4. Products derived from this Software may not be called "DOM4J" nor may
102  * "DOM4J" appear in their names without prior written permission of MetaStuff,
103  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
104  * 
105  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
106  * 
107  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
108  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
109  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
110  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
111  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
112  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
113  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
114  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
115  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
116  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
117  * POSSIBILITY OF SUCH DAMAGE.
118  * 
119  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
120  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/IllegalAddException.html0000644000175000017500000001740510242117700022314 0ustar ebourgebourg IllegalAddException xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  /***
11   * <p>
12   * <code>IllegalAddException</code> is thrown when a node is added incorrectly
13   * to an <code>{@link Element}</code>
14   * </p>
15   * 
16   * @version $Revision: 1.6 $
17   */
18  public class IllegalAddException extends IllegalArgumentException {
19      public IllegalAddException(String reason) {
20          super(reason);
21      }
22  
23      public IllegalAddException(Element parent, Node node, String reason) {
24          super("The node \"" + node.toString()
25                  + "\" could not be added to the element \""
26                  + parent.getQualifiedName() + "\" because: " + reason);
27      }
28  
29      public IllegalAddException(Branch parent, Node node, String reason) {
30          super("The node \"" + node.toString()
31                  + "\" could not be added to the branch \"" + parent.getName()
32                  + "\" because: " + reason);
33      }
34  }
35  
36  /*
37   * Redistribution and use of this software and associated documentation
38   * ("Software"), with or without modification, are permitted provided that the
39   * following conditions are met:
40   * 
41   * 1. Redistributions of source code must retain copyright statements and
42   * notices. Redistributions must also contain a copy of this document.
43   * 
44   * 2. Redistributions in binary form must reproduce the above copyright notice,
45   * this list of conditions and the following disclaimer in the documentation
46   * and/or other materials provided with the distribution.
47   * 
48   * 3. The name "DOM4J" must not be used to endorse or promote products derived
49   * from this Software without prior written permission of MetaStuff, Ltd. For
50   * written permission, please contact dom4j-info@metastuff.com.
51   * 
52   * 4. Products derived from this Software may not be called "DOM4J" nor may
53   * "DOM4J" appear in their names without prior written permission of MetaStuff,
54   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
55   * 
56   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
57   * 
58   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
59   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
62   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
63   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
64   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
65   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
66   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
67   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
68   * POSSIBILITY OF SUCH DAMAGE.
69   * 
70   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
71   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/NodeFilter.html0000644000175000017500000001617110242117742020513 0ustar ebourgebourg NodeFilter xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  /***
11   * <p>
12   * <code>NodeFilter</code> defines the behavior for a filter or predicate
13   * which acts on a DOM4J Node. Instances can be generated from an {@link
14   * DocumentFactory}.
15   * </p>
16   * 
17   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
18   * @version $Revision: 1.7 $
19   */
20  public interface NodeFilter {
21      /***
22       * <p>
23       * <code>matches</code> returns true if the given node matches the filter
24       * condition.
25       * </p>
26       * 
27       * @param node
28       *            DOCUMENT ME!
29       * 
30       * @return true if this filter matches the given node
31       */
32      boolean matches(Node node);
33  }
34  
35  /*
36   * Redistribution and use of this software and associated documentation
37   * ("Software"), with or without modification, are permitted provided that the
38   * following conditions are met:
39   * 
40   * 1. Redistributions of source code must retain copyright statements and
41   * notices. Redistributions must also contain a copy of this document.
42   * 
43   * 2. Redistributions in binary form must reproduce the above copyright notice,
44   * this list of conditions and the following disclaimer in the documentation
45   * and/or other materials provided with the distribution.
46   * 
47   * 3. The name "DOM4J" must not be used to endorse or promote products derived
48   * from this Software without prior written permission of MetaStuff, Ltd. For
49   * written permission, please contact dom4j-info@metastuff.com.
50   * 
51   * 4. Products derived from this Software may not be called "DOM4J" nor may
52   * "DOM4J" appear in their names without prior written permission of MetaStuff,
53   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
54   * 
55   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
56   * 
57   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
58   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
59   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
60   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
61   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
62   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
63   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
64   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
65   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
66   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
67   * POSSIBILITY OF SUCH DAMAGE.
68   * 
69   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
70   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/0000755000175000017500000000000012133227266016527 5ustar ebourgebourgdom4j-1.6.1/docs/xref/org/dom4j/tree/DefaultDocument.html0000644000175000017500000007420010242117554022500 0ustar ebourgebourg DefaultDocument xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.util.Collections;
11  import java.util.Iterator;
12  import java.util.List;
13  
14  import org.dom4j.Document;
15  import org.dom4j.DocumentFactory;
16  import org.dom4j.DocumentType;
17  import org.dom4j.Element;
18  import org.dom4j.IllegalAddException;
19  import org.dom4j.Node;
20  import org.dom4j.ProcessingInstruction;
21  
22  import org.xml.sax.EntityResolver;
23  
24  /***
25   * <p>
26   * <code>DefaultDocument</code> is the default DOM4J default implementation of
27   * an XML document.
28   * </p>
29   * 
30   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
31   * @version $Revision: 1.34 $
32   */
33  public class DefaultDocument extends AbstractDocument {
34      protected static final List EMPTY_LIST = Collections.EMPTY_LIST;
35  
36      protected static final Iterator EMPTY_ITERATOR = EMPTY_LIST.iterator();
37  
38      /*** The name of the document */
39      private String name;
40  
41      /*** The root element of this document */
42      private Element rootElement;
43  
44      /***
45       * Store the contents of the document as a lazily created <code>List</code>
46       */
47      private List content;
48  
49      /*** The document type for this document */
50      private DocumentType docType;
51  
52      /*** The document factory used by default */
53      private DocumentFactory documentFactory = DocumentFactory.getInstance();
54  
55      /*** The resolver of URIs */
56      private transient EntityResolver entityResolver;
57  
58      public DefaultDocument() {
59      }
60  
61      public DefaultDocument(String name) {
62          this.name = name;
63      }
64  
65      public DefaultDocument(Element rootElement) {
66          this.rootElement = rootElement;
67      }
68  
69      public DefaultDocument(DocumentType docType) {
70          this.docType = docType;
71      }
72  
73      public DefaultDocument(Element rootElement, DocumentType docType) {
74          this.rootElement = rootElement;
75          this.docType = docType;
76      }
77  
78      public DefaultDocument(String name, Element rootElement,
79              DocumentType docType) {
80          this.name = name;
81          this.rootElement = rootElement;
82          this.docType = docType;
83      }
84  
85      public String getName() {
86          return name;
87      }
88  
89      public void setName(String name) {
90          this.name = name;
91      }
92  
93      public Element getRootElement() {
94          return rootElement;
95      }
96  
97      public DocumentType getDocType() {
98          return docType;
99      }
100 
101     public void setDocType(DocumentType docType) {
102         this.docType = docType;
103     }
104 
105     public Document addDocType(String docTypeName, String publicId,
106             String systemId) {
107         setDocType(getDocumentFactory().createDocType(docTypeName, publicId,
108                 systemId));
109 
110         return this;
111     }
112 
113     public String getXMLEncoding() {
114         return encoding;
115     }
116 
117     public EntityResolver getEntityResolver() {
118         return entityResolver;
119     }
120 
121     public void setEntityResolver(EntityResolver entityResolver) {
122         this.entityResolver = entityResolver;
123     }
124 
125     public Object clone() {
126         DefaultDocument document = (DefaultDocument) super.clone();
127         document.rootElement = null;
128         document.content = null;
129         document.appendContent(this);
130 
131         return document;
132     }
133 
134     public List processingInstructions() {
135         List source = contentList();
136         List answer = createResultList();
137         int size = source.size();
138 
139         for (int i = 0; i < size; i++) {
140             Object object = source.get(i);
141 
142             if (object instanceof ProcessingInstruction) {
143                 answer.add(object);
144             }
145         }
146 
147         return answer;
148     }
149 
150     public List processingInstructions(String target) {
151         List source = contentList();
152         List answer = createResultList();
153         int size = source.size();
154 
155         for (int i = 0; i < size; i++) {
156             Object object = source.get(i);
157 
158             if (object instanceof ProcessingInstruction) {
159                 ProcessingInstruction pi = (ProcessingInstruction) object;
160 
161                 if (target.equals(pi.getName())) {
162                     answer.add(pi);
163                 }
164             }
165         }
166 
167         return answer;
168     }
169 
170     public ProcessingInstruction processingInstruction(String target) {
171         List source = contentList();
172         int size = source.size();
173 
174         for (int i = 0; i < size; i++) {
175             Object object = source.get(i);
176 
177             if (object instanceof ProcessingInstruction) {
178                 ProcessingInstruction pi = (ProcessingInstruction) object;
179 
180                 if (target.equals(pi.getName())) {
181                     return pi;
182                 }
183             }
184         }
185 
186         return null;
187     }
188 
189     public boolean removeProcessingInstruction(String target) {
190         List source = contentList();
191 
192         for (Iterator iter = source.iterator(); iter.hasNext();) {
193             Object object = iter.next();
194 
195             if (object instanceof ProcessingInstruction) {
196                 ProcessingInstruction pi = (ProcessingInstruction) object;
197 
198                 if (target.equals(pi.getName())) {
199                     iter.remove();
200 
201                     return true;
202                 }
203             }
204         }
205 
206         return false;
207     }
208 
209     public void setContent(List content) {
210         rootElement = null;
211         contentRemoved();
212 
213         if (content instanceof ContentListFacade) {
214             content = ((ContentListFacade) content).getBackingList();
215         }
216 
217         if (content == null) {
218             this.content = null;
219         } else {
220             int size = content.size();
221             List newContent = createContentList(size);
222 
223             for (int i = 0; i < size; i++) {
224                 Object object = content.get(i);
225 
226                 if (object instanceof Node) {
227                     Node node = (Node) object;
228                     Document doc = node.getDocument();
229 
230                     if ((doc != null) && (doc != this)) {
231                         node = (Node) node.clone();
232                     }
233 
234                     if (node instanceof Element) {
235                         if (rootElement == null) {
236                             rootElement = (Element) node;
237                         } else {
238                             throw new IllegalAddException(
239                                     "A document may only "
240                                             + "contain one root " + "element: "
241                                             + content);
242                         }
243                     }
244 
245                     newContent.add(node);
246                     childAdded(node);
247                 }
248             }
249 
250             this.content = newContent;
251         }
252     }
253 
254     public void clearContent() {
255         contentRemoved();
256         content = null;
257         rootElement = null;
258     }
259 
260     public void setDocumentFactory(DocumentFactory documentFactory) {
261         this.documentFactory = documentFactory;
262     }
263 
264     // Implementation methods
265     // -------------------------------------------------------------------------
266     protected List contentList() {
267         if (content == null) {
268             content = createContentList();
269 
270             if (rootElement != null) {
271                 content.add(rootElement);
272             }
273         }
274 
275         return content;
276     }
277 
278     protected void addNode(Node node) {
279         if (node != null) {
280             Document document = node.getDocument();
281 
282             if ((document != null) && (document != this)) {
283                 // XXX: could clone here
284                 String message = "The Node already has an existing document: "
285                         + document;
286                 throw new IllegalAddException(this, node, message);
287             }
288 
289             contentList().add(node);
290             childAdded(node);
291         }
292     }
293 
294     protected void addNode(int index, Node node) {
295         if (node != null) {
296             Document document = node.getDocument();
297 
298             if ((document != null) && (document != this)) {
299                 // XXX: could clone here
300                 String message = "The Node already has an existing document: "
301                         + document;
302                 throw new IllegalAddException(this, node, message);
303             }
304 
305             contentList().add(index, node);
306             childAdded(node);
307         }
308     }
309 
310     protected boolean removeNode(Node node) {
311         if (node == rootElement) {
312             rootElement = null;
313         }
314 
315         if (contentList().remove(node)) {
316             childRemoved(node);
317 
318             return true;
319         }
320 
321         return false;
322     }
323 
324     protected void rootElementAdded(Element element) {
325         this.rootElement = element;
326         element.setDocument(this);
327     }
328 
329     protected DocumentFactory getDocumentFactory() {
330         return documentFactory;
331     }
332 }
333 
334 /*
335  * Redistribution and use of this software and associated documentation
336  * ("Software"), with or without modification, are permitted provided that the
337  * following conditions are met:
338  * 
339  * 1. Redistributions of source code must retain copyright statements and
340  * notices. Redistributions must also contain a copy of this document.
341  * 
342  * 2. Redistributions in binary form must reproduce the above copyright notice,
343  * this list of conditions and the following disclaimer in the documentation
344  * and/or other materials provided with the distribution.
345  * 
346  * 3. The name "DOM4J" must not be used to endorse or promote products derived
347  * from this Software without prior written permission of MetaStuff, Ltd. For
348  * written permission, please contact dom4j-info@metastuff.com.
349  * 
350  * 4. Products derived from this Software may not be called "DOM4J" nor may
351  * "DOM4J" appear in their names without prior written permission of MetaStuff,
352  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
353  * 
354  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
355  * 
356  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
357  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
358  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
359  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
360  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
361  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
362  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
363  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
364  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
365  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
366  * POSSIBILITY OF SUCH DAMAGE.
367  * 
368  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
369  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/AbstractAttribute.html0000644000175000017500000004043210242117701023036 0ustar ebourgebourg AbstractAttribute xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.io.IOException;
11  import java.io.Writer;
12  
13  import org.dom4j.Attribute;
14  import org.dom4j.Element;
15  import org.dom4j.Namespace;
16  import org.dom4j.Node;
17  import org.dom4j.Visitor;
18  
19  /***
20   * <p>
21   * <code>AbstractNamespace</code> is an abstract base class for tree
22   * implementors to use for implementation inheritence.
23   * </p>
24   * 
25   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
26   * @version $Revision: 1.21 $
27   */
28  public abstract class AbstractAttribute extends AbstractNode implements
29          Attribute {
30      public short getNodeType() {
31          return ATTRIBUTE_NODE;
32      }
33  
34      public void setNamespace(Namespace namespace) {
35          String msg = "This Attribute is read only and cannot be changed";
36          throw new UnsupportedOperationException(msg);
37      }
38  
39      public String getText() {
40          return getValue();
41      }
42  
43      public void setText(String text) {
44          setValue(text);
45      }
46  
47      public void setValue(String value) {
48          String msg = "This Attribute is read only and cannot be changed";
49          throw new UnsupportedOperationException(msg);
50      }
51  
52      public Object getData() {
53          return getValue();
54      }
55  
56      public void setData(Object data) {
57          setValue((data == null) ? null : data.toString());
58      }
59  
60      public String toString() {
61          return super.toString() + " [Attribute: name " + getQualifiedName()
62                  + " value \"" + getValue() + "\"]";
63      }
64  
65      public String asXML() {
66          return getQualifiedName() + "=\"" + getValue() + "\"";
67      }
68  
69      public void write(Writer writer) throws IOException {
70          writer.write(getQualifiedName());
71          writer.write("=\"");
72          writer.write(getValue());
73          writer.write("\"");
74      }
75  
76      public void accept(Visitor visitor) {
77          visitor.visit(this);
78      }
79  
80      // QName methods
81      public Namespace getNamespace() {
82          return getQName().getNamespace();
83      }
84  
85      public String getName() {
86          return getQName().getName();
87      }
88  
89      public String getNamespacePrefix() {
90          return getQName().getNamespacePrefix();
91      }
92  
93      public String getNamespaceURI() {
94          return getQName().getNamespaceURI();
95      }
96  
97      public String getQualifiedName() {
98          return getQName().getQualifiedName();
99      }
100 
101     public String getPath(Element context) {
102         StringBuffer result = new StringBuffer();
103 
104         Element parent = getParent();
105 
106         if ((parent != null) && (parent != context)) {
107             result.append(parent.getPath(context));
108             result.append("/");
109         }
110 
111         result.append("@");
112 
113         String uri = getNamespaceURI();
114         String prefix = getNamespacePrefix();
115 
116         if ((uri == null) || (uri.length() == 0) || (prefix == null)
117                 || (prefix.length() == 0)) {
118             result.append(getName());
119         } else {
120             result.append(getQualifiedName());
121         }
122 
123         return result.toString();
124     }
125 
126     public String getUniquePath(Element context) {
127         StringBuffer result = new StringBuffer();
128 
129         Element parent = getParent();
130 
131         if ((parent != null) && (parent != context)) {
132             result.append(parent.getUniquePath(context));
133             result.append("/");
134         }
135 
136         result.append("@");
137 
138         String uri = getNamespaceURI();
139         String prefix = getNamespacePrefix();
140 
141         if ((uri == null) || (uri.length() == 0) || (prefix == null)
142                 || (prefix.length() == 0)) {
143             result.append(getName());
144         } else {
145             result.append(getQualifiedName());
146         }
147 
148         return result.toString();
149     }
150 
151     protected Node createXPathResult(Element parent) {
152         return new DefaultAttribute(parent, getQName(), getValue());
153     }
154 }
155 
156 /*
157  * Redistribution and use of this software and associated documentation
158  * ("Software"), with or without modification, are permitted provided that the
159  * following conditions are met:
160  * 
161  * 1. Redistributions of source code must retain copyright statements and
162  * notices. Redistributions must also contain a copy of this document.
163  * 
164  * 2. Redistributions in binary form must reproduce the above copyright notice,
165  * this list of conditions and the following disclaimer in the documentation
166  * and/or other materials provided with the distribution.
167  * 
168  * 3. The name "DOM4J" must not be used to endorse or promote products derived
169  * from this Software without prior written permission of MetaStuff, Ltd. For
170  * written permission, please contact dom4j-info@metastuff.com.
171  * 
172  * 4. Products derived from this Software may not be called "DOM4J" nor may
173  * "DOM4J" appear in their names without prior written permission of MetaStuff,
174  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
175  * 
176  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
177  * 
178  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
179  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
180  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
181  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
182  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
183  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
184  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
185  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
186  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
187  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
188  * POSSIBILITY OF SUCH DAMAGE.
189  * 
190  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
191  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/ElementNameIterator.html0000644000175000017500000002102710242117754023322 0ustar ebourgebourg ElementNameIterator xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.util.Iterator;
11  
12  import org.dom4j.Element;
13  
14  /***
15   * <p>
16   * <code>ElementNameIterator</code> is a filtering {@link Iterator}which
17   * filters out objects which do not implement the {@link Element}interface and
18   * are not of the correct element name.
19   * </p>
20   * 
21   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
22   * @version $Revision: 1.11 $
23   * 
24   * @deprecated THIS CLASS WILL BE REMOVED IN dom4j-1.6 !!
25   */
26  public class ElementNameIterator extends FilterIterator {
27      private String name;
28  
29      public ElementNameIterator(Iterator proxy, String name) {
30          super(proxy);
31          this.name = name;
32      }
33  
34      /***
35       * DOCUMENT ME!
36       * 
37       * @param object
38       *            DOCUMENT ME!
39       * 
40       * @return true if the given element implements the {@link Element}
41       *         interface
42       */
43      protected boolean matches(Object object) {
44          if (object instanceof Element) {
45              Element element = (Element) object;
46  
47              return name.equals(element.getName());
48          }
49  
50          return false;
51      }
52  }
53  
54  /*
55   * Redistribution and use of this software and associated documentation
56   * ("Software"), with or without modification, are permitted provided that the
57   * following conditions are met:
58   * 
59   * 1. Redistributions of source code must retain copyright statements and
60   * notices. Redistributions must also contain a copy of this document.
61   * 
62   * 2. Redistributions in binary form must reproduce the above copyright notice,
63   * this list of conditions and the following disclaimer in the documentation
64   * and/or other materials provided with the distribution.
65   * 
66   * 3. The name "DOM4J" must not be used to endorse or promote products derived
67   * from this Software without prior written permission of MetaStuff, Ltd. For
68   * written permission, please contact dom4j-info@metastuff.com.
69   * 
70   * 4. Products derived from this Software may not be called "DOM4J" nor may
71   * "DOM4J" appear in their names without prior written permission of MetaStuff,
72   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
73   * 
74   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
75   * 
76   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
77   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
78   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
79   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
80   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
81   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
82   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
83   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
84   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
85   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
86   * POSSIBILITY OF SUCH DAMAGE.
87   * 
88   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
89   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/BaseElement.html0000644000175000017500000003775710242117753021622 0ustar ebourgebourg BaseElement xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.util.List;
11  
12  import org.dom4j.Branch;
13  import org.dom4j.Document;
14  import org.dom4j.Element;
15  import org.dom4j.Namespace;
16  import org.dom4j.QName;
17  
18  /***
19   * <p>
20   * <code>BaseElement</code> is a useful base class for implemementation
21   * inheritence of an XML element.
22   * </p>
23   * 
24   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
25   * @version $Revision: 1.9 $
26   */
27  public class BaseElement extends AbstractElement {
28      /*** The <code>QName</code> for this element */
29      private QName qname;
30  
31      /***
32       * Stores the parent branch of this node which is either a Document if this
33       * element is the root element in a document, or another Element if it is a
34       * child of the root document, or null if it has not been added to a
35       * document yet.
36       */
37      private Branch parentBranch;
38  
39      /*** List of content nodes. */
40      protected List content;
41  
42      /*** list of attributes */
43      protected List attributes;
44  
45      public BaseElement(String name) {
46          this.qname = getDocumentFactory().createQName(name);
47      }
48  
49      public BaseElement(QName qname) {
50          this.qname = qname;
51      }
52  
53      public BaseElement(String name, Namespace namespace) {
54          this.qname = getDocumentFactory().createQName(name, namespace);
55      }
56  
57      public Element getParent() {
58          Element result = null;
59  
60          if (parentBranch instanceof Element) {
61              result = (Element) parentBranch;
62          }
63  
64          return result;
65      }
66  
67      public void setParent(Element parent) {
68          if (parentBranch instanceof Element || (parent != null)) {
69              parentBranch = parent;
70          }
71      }
72  
73      public Document getDocument() {
74          if (parentBranch instanceof Document) {
75              return (Document) parentBranch;
76          } else if (parentBranch instanceof Element) {
77              Element parent = (Element) parentBranch;
78  
79              return parent.getDocument();
80          }
81  
82          return null;
83      }
84  
85      public void setDocument(Document document) {
86          if (parentBranch instanceof Document || (document != null)) {
87              parentBranch = document;
88          }
89      }
90  
91      public boolean supportsParent() {
92          return true;
93      }
94  
95      public QName getQName() {
96          return qname;
97      }
98  
99      public void setQName(QName name) {
100         this.qname = name;
101     }
102 
103     public void clearContent() {
104         contentList().clear();
105     }
106 
107     public void setContent(List content) {
108         this.content = content;
109 
110         if (content instanceof ContentListFacade) {
111             this.content = ((ContentListFacade) content).getBackingList();
112         }
113     }
114 
115     public void setAttributes(List attributes) {
116         this.attributes = attributes;
117 
118         if (attributes instanceof ContentListFacade) {
119             this.attributes = ((ContentListFacade) attributes).getBackingList();
120         }
121     }
122 
123     // Implementation methods
124     // -------------------------------------------------------------------------
125     protected List contentList() {
126         if (content == null) {
127             content = createContentList();
128         }
129 
130         return content;
131     }
132 
133     protected List attributeList() {
134         if (attributes == null) {
135             attributes = createAttributeList();
136         }
137 
138         return attributes;
139     }
140 
141     protected List attributeList(int size) {
142         if (attributes == null) {
143             attributes = createAttributeList(size);
144         }
145 
146         return attributes;
147     }
148 
149     protected void setAttributeList(List attributeList) {
150         this.attributes = attributeList;
151     }
152 }
153 
154 /*
155  * Redistribution and use of this software and associated documentation
156  * ("Software"), with or without modification, are permitted provided that the
157  * following conditions are met:
158  * 
159  * 1. Redistributions of source code must retain copyright statements and
160  * notices. Redistributions must also contain a copy of this document.
161  * 
162  * 2. Redistributions in binary form must reproduce the above copyright notice,
163  * this list of conditions and the following disclaimer in the documentation
164  * and/or other materials provided with the distribution.
165  * 
166  * 3. The name "DOM4J" must not be used to endorse or promote products derived
167  * from this Software without prior written permission of MetaStuff, Ltd. For
168  * written permission, please contact dom4j-info@metastuff.com.
169  * 
170  * 4. Products derived from this Software may not be called "DOM4J" nor may
171  * "DOM4J" appear in their names without prior written permission of MetaStuff,
172  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
173  * 
174  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
175  * 
176  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
177  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
178  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
179  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
180  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
181  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
182  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
183  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
184  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
185  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
186  * POSSIBILITY OF SUCH DAMAGE.
187  * 
188  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
189  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/AbstractBranch.html0000644000175000017500000011565110242117762022305 0ustar ebourgebourg AbstractBranch xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.util.ArrayList;
11  import java.util.Iterator;
12  import java.util.List;
13  import java.util.StringTokenizer;
14  
15  import org.dom4j.Branch;
16  import org.dom4j.Comment;
17  import org.dom4j.Element;
18  import org.dom4j.IllegalAddException;
19  import org.dom4j.Namespace;
20  import org.dom4j.Node;
21  import org.dom4j.ProcessingInstruction;
22  import org.dom4j.QName;
23  
24  /***
25   * <p>
26   * <code>AbstractBranch</code> is an abstract base class for tree implementors
27   * to use for implementation inheritence.
28   * </p>
29   * 
30   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
31   * @version $Revision: 1.44 $
32   */
33  public abstract class AbstractBranch extends AbstractNode implements Branch {
34      protected static final int DEFAULT_CONTENT_LIST_SIZE = 5;
35  
36      public AbstractBranch() {
37      }
38  
39      public boolean isReadOnly() {
40          return false;
41      }
42  
43      public boolean hasContent() {
44          return nodeCount() > 0;
45      }
46  
47      public List content() {
48          List backingList = contentList();
49  
50          return new ContentListFacade(this, backingList);
51      }
52  
53      public String getText() {
54          List content = contentList();
55  
56          if (content != null) {
57              int size = content.size();
58  
59              if (size >= 1) {
60                  Object first = content.get(0);
61                  String firstText = getContentAsText(first);
62  
63                  if (size == 1) {
64                      // optimised to avoid StringBuffer creation
65                      return firstText;
66                  } else {
67                      StringBuffer buffer = new StringBuffer(firstText);
68  
69                      for (int i = 1; i < size; i++) {
70                          Object node = content.get(i);
71                          buffer.append(getContentAsText(node));
72                      }
73  
74                      return buffer.toString();
75                  }
76              }
77          }
78  
79          return "";
80      }
81  
82      /***
83       * DOCUMENT ME!
84       * 
85       * @param content
86       *            DOCUMENT ME!
87       * 
88       * @return the text value of the given content object as text which returns
89       *         the text value of CDATA, Entity or Text nodes
90       */
91      protected String getContentAsText(Object content) {
92          if (content instanceof Node) {
93              Node node = (Node) content;
94  
95              switch (node.getNodeType()) {
96                  case CDATA_SECTION_NODE:
97  
98                  // case ENTITY_NODE:
99                  case ENTITY_REFERENCE_NODE:
100                 case TEXT_NODE:
101                     return node.getText();
102 
103                 default:
104                     break;
105             }
106         } else if (content instanceof String) {
107             return (String) content;
108         }
109 
110         return "";
111     }
112 
113     /***
114      * DOCUMENT ME!
115      * 
116      * @param content
117      *            DOCUMENT ME!
118      * 
119      * @return the XPath defined string-value of the given content object
120      */
121     protected String getContentAsStringValue(Object content) {
122         if (content instanceof Node) {
123             Node node = (Node) content;
124 
125             switch (node.getNodeType()) {
126                 case CDATA_SECTION_NODE:
127 
128                 // case ENTITY_NODE:
129                 case ENTITY_REFERENCE_NODE:
130                 case TEXT_NODE:
131                 case ELEMENT_NODE:
132                     return node.getStringValue();
133 
134                 default:
135                     break;
136             }
137         } else if (content instanceof String) {
138             return (String) content;
139         }
140 
141         return "";
142     }
143 
144     public String getTextTrim() {
145         String text = getText();
146 
147         StringBuffer textContent = new StringBuffer();
148         StringTokenizer tokenizer = new StringTokenizer(text);
149 
150         while (tokenizer.hasMoreTokens()) {
151             String str = tokenizer.nextToken();
152             textContent.append(str);
153 
154             if (tokenizer.hasMoreTokens()) {
155                 textContent.append(" "); // separator
156             }
157         }
158 
159         return textContent.toString();
160     }
161 
162     public void setProcessingInstructions(List listOfPIs) {
163         for (Iterator iter = listOfPIs.iterator(); iter.hasNext();) {
164             ProcessingInstruction pi = (ProcessingInstruction) iter.next();
165             addNode(pi);
166         }
167     }
168 
169     public Element addElement(String name) {
170         Element node = getDocumentFactory().createElement(name);
171         add(node);
172 
173         return node;
174     }
175 
176     public Element addElement(String qualifiedName, String namespaceURI) {
177         Element node = getDocumentFactory().createElement(qualifiedName,
178                 namespaceURI);
179         add(node);
180 
181         return node;
182     }
183 
184     public Element addElement(QName qname) {
185         Element node = getDocumentFactory().createElement(qname);
186         add(node);
187 
188         return node;
189     }
190 
191     public Element addElement(String name, String prefix, String uri) {
192         Namespace namespace = Namespace.get(prefix, uri);
193         QName qName = getDocumentFactory().createQName(name, namespace);
194 
195         return addElement(qName);
196     }
197 
198     // polymorphic node methods
199     public void add(Node node) {
200         switch (node.getNodeType()) {
201             case ELEMENT_NODE:
202                 add((Element) node);
203 
204                 break;
205 
206             case COMMENT_NODE:
207                 add((Comment) node);
208 
209                 break;
210 
211             case PROCESSING_INSTRUCTION_NODE:
212                 add((ProcessingInstruction) node);
213 
214                 break;
215 
216             default:
217                 invalidNodeTypeAddException(node);
218         }
219     }
220 
221     public boolean remove(Node node) {
222         switch (node.getNodeType()) {
223             case ELEMENT_NODE:
224                 return remove((Element) node);
225 
226             case COMMENT_NODE:
227                 return remove((Comment) node);
228 
229             case PROCESSING_INSTRUCTION_NODE:
230                 return remove((ProcessingInstruction) node);
231 
232             default:
233                 invalidNodeTypeAddException(node);
234 
235                 return false;
236         }
237     }
238 
239     // typesafe versions using node classes
240     public void add(Comment comment) {
241         addNode(comment);
242     }
243 
244     public void add(Element element) {
245         addNode(element);
246     }
247 
248     public void add(ProcessingInstruction pi) {
249         addNode(pi);
250     }
251 
252     public boolean remove(Comment comment) {
253         return removeNode(comment);
254     }
255 
256     public boolean remove(Element element) {
257         return removeNode(element);
258     }
259 
260     public boolean remove(ProcessingInstruction pi) {
261         return removeNode(pi);
262     }
263 
264     public Element elementByID(String elementID) {
265         for (int i = 0, size = nodeCount(); i < size; i++) {
266             Node node = node(i);
267 
268             if (node instanceof Element) {
269                 Element element = (Element) node;
270                 String id = elementID(element);
271 
272                 if ((id != null) && id.equals(elementID)) {
273                     return element;
274                 } else {
275                     element = element.elementByID(elementID);
276 
277                     if (element != null) {
278                         return element;
279                     }
280                 }
281             }
282         }
283 
284         return null;
285     }
286 
287     public void appendContent(Branch branch) {
288         for (int i = 0, size = branch.nodeCount(); i < size; i++) {
289             Node node = branch.node(i);
290             add((Node) node.clone());
291         }
292     }
293 
294     public Node node(int index) {
295         Object object = contentList().get(index);
296 
297         if (object instanceof Node) {
298             return (Node) object;
299         }
300 
301         if (object instanceof String) {
302             return getDocumentFactory().createText(object.toString());
303         }
304 
305         return null;
306     }
307 
308     public int nodeCount() {
309         return contentList().size();
310     }
311 
312     public int indexOf(Node node) {
313         return contentList().indexOf(node);
314     }
315 
316     public Iterator nodeIterator() {
317         return contentList().iterator();
318     }
319 
320     // Implementation methods
321 
322     /***
323      * DOCUMENT ME!
324      * 
325      * @param element
326      *            DOCUMENT ME!
327      * 
328      * @return the ID of the given <code>Element</code>
329      */
330     protected String elementID(Element element) {
331         // XXX: there will be other ways of finding the ID
332         // XXX: should probably have an IDResolver or something
333         return element.attributeValue("ID");
334     }
335 
336     /***
337      * DOCUMENT ME!
338      * 
339      * @return the internal List used to manage the content
340      */
341     protected abstract List contentList();
342 
343     /***
344      * A Factory Method pattern which creates a List implementation used to
345      * store content
346      * 
347      * @return DOCUMENT ME!
348      */
349     protected List createContentList() {
350         return new ArrayList(DEFAULT_CONTENT_LIST_SIZE);
351     }
352 
353     /***
354      * A Factory Method pattern which creates a List implementation used to
355      * store content
356      * 
357      * @param size
358      *            DOCUMENT ME!
359      * 
360      * @return DOCUMENT ME!
361      */
362     protected List createContentList(int size) {
363         return new ArrayList(size);
364     }
365 
366     /***
367      * A Factory Method pattern which creates a BackedList implementation used
368      * to store results of a filtered content query.
369      * 
370      * @return DOCUMENT ME!
371      */
372     protected BackedList createResultList() {
373         return new BackedList(this, contentList());
374     }
375 
376     /***
377      * A Factory Method pattern which creates a BackedList implementation which
378      * contains a single result
379      * 
380      * @param result
381      *            DOCUMENT ME!
382      * 
383      * @return DOCUMENT ME!
384      */
385     protected List createSingleResultList(Object result) {
386         BackedList list = new BackedList(this, contentList(), 1);
387         list.addLocal(result);
388 
389         return list;
390     }
391 
392     /***
393      * A Factory Method pattern which creates an empty a BackedList
394      * implementation
395      * 
396      * @return DOCUMENT ME!
397      */
398     protected List createEmptyList() {
399         return new BackedList(this, contentList(), 0);
400     }
401 
402     protected abstract void addNode(Node node);
403 
404     protected abstract void addNode(int index, Node node);
405 
406     protected abstract boolean removeNode(Node node);
407 
408     /***
409      * Called when a new child node has been added to me to allow any parent
410      * relationships to be created or events to be fired.
411      * 
412      * @param node
413      *            DOCUMENT ME!
414      */
415     protected abstract void childAdded(Node node);
416 
417     /***
418      * Called when a child node has been removed to allow any parent
419      * relationships to be deleted or events to be fired.
420      * 
421      * @param node
422      *            DOCUMENT ME!
423      */
424     protected abstract void childRemoved(Node node);
425 
426     /***
427      * Called when the given List content has been removed so each node should
428      * have its parent and document relationships cleared
429      */
430     protected void contentRemoved() {
431         List content = contentList();
432 
433         for (int i = 0, size = content.size(); i < size; i++) {
434             Object object = content.get(i);
435 
436             if (object instanceof Node) {
437                 childRemoved((Node) object);
438             }
439         }
440     }
441 
442     /***
443      * Called when an invalid node has been added. Throws an {@link
444      * IllegalAddException}.
445      * 
446      * @param node
447      *            DOCUMENT ME!
448      * 
449      * @throws IllegalAddException
450      *             DOCUMENT ME!
451      */
452     protected void invalidNodeTypeAddException(Node node) {
453         throw new IllegalAddException("Invalid node type. Cannot add node: "
454                 + node + " to this branch: " + this);
455     }
456 }
457 
458 /*
459  * Redistribution and use of this software and associated documentation
460  * ("Software"), with or without modification, are permitted provided that the
461  * following conditions are met:
462  * 
463  * 1. Redistributions of source code must retain copyright statements and
464  * notices. Redistributions must also contain a copy of this document.
465  * 
466  * 2. Redistributions in binary form must reproduce the above copyright notice,
467  * this list of conditions and the following disclaimer in the documentation
468  * and/or other materials provided with the distribution.
469  * 
470  * 3. The name "DOM4J" must not be used to endorse or promote products derived
471  * from this Software without prior written permission of MetaStuff, Ltd. For
472  * written permission, please contact dom4j-info@metastuff.com.
473  * 
474  * 4. Products derived from this Software may not be called "DOM4J" nor may
475  * "DOM4J" appear in their names without prior written permission of MetaStuff,
476  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
477  * 
478  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
479  * 
480  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
481  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
482  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
483  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
484  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
485  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
486  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
487  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
488  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
489  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
490  * POSSIBILITY OF SUCH DAMAGE.
491  * 
492  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
493  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/FlyweightCDATA.html0000644000175000017500000002073410242117577022124 0ustar ebourgebourg FlyweightCDATA xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import org.dom4j.CDATA;
11  import org.dom4j.Element;
12  import org.dom4j.Node;
13  
14  /***
15   * <p>
16   * <code>FlyweightCDATA</code> is a Flyweight pattern implementation of a
17   * singly linked, read-only XML CDATA.
18   * </p>
19   * 
20   * <p>
21   * This node could be shared across documents and elements though it does not
22   * support the parent relationship.
23   * </p>
24   * 
25   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
26   * @version $Revision: 1.8 $
27   */
28  public class FlyweightCDATA extends AbstractCDATA implements CDATA {
29      /*** Text of the <code>CDATA</code> node */
30      protected String text;
31  
32      /***
33       * DOCUMENT ME!
34       * 
35       * @param text
36       *            is the CDATA text
37       */
38      public FlyweightCDATA(String text) {
39          this.text = text;
40      }
41  
42      public String getText() {
43          return text;
44      }
45  
46      protected Node createXPathResult(Element parent) {
47          return new DefaultCDATA(parent, getText());
48      }
49  }
50  
51  /*
52   * Redistribution and use of this software and associated documentation
53   * ("Software"), with or without modification, are permitted provided that the
54   * following conditions are met:
55   * 
56   * 1. Redistributions of source code must retain copyright statements and
57   * notices. Redistributions must also contain a copy of this document.
58   * 
59   * 2. Redistributions in binary form must reproduce the above copyright notice,
60   * this list of conditions and the following disclaimer in the documentation
61   * and/or other materials provided with the distribution.
62   * 
63   * 3. The name "DOM4J" must not be used to endorse or promote products derived
64   * from this Software without prior written permission of MetaStuff, Ltd. For
65   * written permission, please contact dom4j-info@metastuff.com.
66   * 
67   * 4. Products derived from this Software may not be called "DOM4J" nor may
68   * "DOM4J" appear in their names without prior written permission of MetaStuff,
69   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
70   * 
71   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
72   * 
73   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
74   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
75   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
76   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
77   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
78   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
79   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
80   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
81   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
82   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
83   * POSSIBILITY OF SUCH DAMAGE.
84   * 
85   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
86   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/ElementQNameIterator.html0000644000175000017500000002136710242117734023450 0ustar ebourgebourg ElementQNameIterator xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.util.Iterator;
11  
12  import org.dom4j.Element;
13  import org.dom4j.QName;
14  
15  /***
16   * <p>
17   * <code>ElementQNameIterator</code> is a filtering {@link Iterator}which
18   * filters out objects which do not implement the {@link Element}interface and
19   * are not of the correct fully qualified element name.
20   * </p>
21   * 
22   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
23   * @version $Revision: 1.7 $
24   * 
25   * @deprecated THIS CLASS WILL BE REMOVED IN dom4j-1.6 !!
26   */
27  public class ElementQNameIterator extends FilterIterator {
28      private QName qName;
29  
30      public ElementQNameIterator(Iterator proxy, QName qName) {
31          super(proxy);
32          this.qName = qName;
33      }
34  
35      /***
36       * DOCUMENT ME!
37       * 
38       * @param object
39       *            DOCUMENT ME!
40       * 
41       * @return true if the given element implements the {@link Element}
42       *         interface and matches the given {@link QName}
43       */
44      protected boolean matches(Object object) {
45          if (object instanceof Element) {
46              Element element = (Element) object;
47  
48              return qName.equals(element.getQName());
49          }
50  
51          return false;
52      }
53  }
54  
55  /*
56   * Redistribution and use of this software and associated documentation
57   * ("Software"), with or without modification, are permitted provided that the
58   * following conditions are met:
59   * 
60   * 1. Redistributions of source code must retain copyright statements and
61   * notices. Redistributions must also contain a copy of this document.
62   * 
63   * 2. Redistributions in binary form must reproduce the above copyright notice,
64   * this list of conditions and the following disclaimer in the documentation
65   * and/or other materials provided with the distribution.
66   * 
67   * 3. The name "DOM4J" must not be used to endorse or promote products derived
68   * from this Software without prior written permission of MetaStuff, Ltd. For
69   * written permission, please contact dom4j-info@metastuff.com.
70   * 
71   * 4. Products derived from this Software may not be called "DOM4J" nor may
72   * "DOM4J" appear in their names without prior written permission of MetaStuff,
73   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
74   * 
75   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
76   * 
77   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
78   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
79   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
80   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
81   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
82   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
83   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
84   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
85   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
86   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
87   * POSSIBILITY OF SUCH DAMAGE.
88   * 
89   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
90   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/FlyweightEntity.html0000644000175000017500000003154110242117707022555 0ustar ebourgebourg FlyweightEntity xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import org.dom4j.Element;
11  import org.dom4j.Node;
12  
13  /***
14   * <p>
15   * <code>FlyweightEntity</code> is a Flyweight pattern implementation of a
16   * singly linked, read-only XML entity.
17   * </p>
18   * 
19   * <p>
20   * This node could be shared across documents and elements though it does not
21   * support the parent relationship.
22   * </p>
23   * 
24   * <p>
25   * Often this node needs to be created and then the text content added later
26   * (for example in SAX) so this implementation allows a call to {@link#setText}
27   * providing the entity has no text already.
28   * </p>
29   * 
30   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
31   * @version $Revision: 1.6 $
32   */
33  public class FlyweightEntity extends AbstractEntity {
34      /*** The name of the <code>Entity</code> */
35      protected String name;
36  
37      /*** The text of the <code>Entity</code> */
38      protected String text;
39  
40      /***
41       * A default constructor for implementors to use.
42       */
43      protected FlyweightEntity() {
44      }
45  
46      /***
47       * Creates the <code>Entity</code> with the specified name
48       * 
49       * @param name
50       *            is the name of the entity
51       */
52      public FlyweightEntity(String name) {
53          this.name = name;
54      }
55  
56      /***
57       * Creates the <code>Entity</code> with the specified name and text.
58       * 
59       * @param name
60       *            is the name of the entity
61       * @param text
62       *            is the text of the entity
63       */
64      public FlyweightEntity(String name, String text) {
65          this.name = name;
66          this.text = text;
67      }
68  
69      /***
70       * DOCUMENT ME!
71       * 
72       * @return the name of the entity
73       */
74      public String getName() {
75          return name;
76      }
77  
78      /***
79       * DOCUMENT ME!
80       * 
81       * @return the text of the entity
82       */
83      public String getText() {
84          return text;
85      }
86  
87      /***
88       * sets the value of the entity if it is not defined yet otherwise an
89       * <code>UnsupportedOperationException</code> is thrown as this class is
90       * read only.
91       * 
92       * @param text
93       *            DOCUMENT ME!
94       * 
95       * @throws UnsupportedOperationException
96       *             DOCUMENT ME!
97       */
98      public void setText(String text) {
99          if (this.text != null) {
100             this.text = text;
101         } else {
102             throw new UnsupportedOperationException(
103                     "This Entity is read-only. " + "It cannot be modified");
104         }
105     }
106 
107     protected Node createXPathResult(Element parent) {
108         return new DefaultEntity(parent, getName(), getText());
109     }
110 }
111 
112 /*
113  * Redistribution and use of this software and associated documentation
114  * ("Software"), with or without modification, are permitted provided that the
115  * following conditions are met:
116  * 
117  * 1. Redistributions of source code must retain copyright statements and
118  * notices. Redistributions must also contain a copy of this document.
119  * 
120  * 2. Redistributions in binary form must reproduce the above copyright notice,
121  * this list of conditions and the following disclaimer in the documentation
122  * and/or other materials provided with the distribution.
123  * 
124  * 3. The name "DOM4J" must not be used to endorse or promote products derived
125  * from this Software without prior written permission of MetaStuff, Ltd. For
126  * written permission, please contact dom4j-info@metastuff.com.
127  * 
128  * 4. Products derived from this Software may not be called "DOM4J" nor may
129  * "DOM4J" appear in their names without prior written permission of MetaStuff,
130  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
131  * 
132  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
133  * 
134  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
135  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
136  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
137  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
138  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
139  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
140  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
141  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
142  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
143  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
144  * POSSIBILITY OF SUCH DAMAGE.
145  * 
146  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
147  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/DefaultElement.html0000644000175000017500000024155610242117652022324 0ustar ebourgebourg DefaultElement xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.util.ArrayList;
11  import java.util.Iterator;
12  import java.util.List;
13  
14  import org.dom4j.Attribute;
15  import org.dom4j.Branch;
16  import org.dom4j.Document;
17  import org.dom4j.DocumentFactory;
18  import org.dom4j.Element;
19  import org.dom4j.IllegalAddException;
20  import org.dom4j.Namespace;
21  import org.dom4j.Node;
22  import org.dom4j.ProcessingInstruction;
23  import org.dom4j.QName;
24  
25  /***
26   * <p>
27   * <code>DefaultElement</code> is the default DOM4J default implementation of
28   * an XML element.
29   * </p>
30   * 
31   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
32   * @version $Revision: 1.59 $
33   */
34  public class DefaultElement extends AbstractElement {
35      /*** The <code>DocumentFactory</code> instance used by default */
36      private static final transient DocumentFactory DOCUMENT_FACTORY = 
37              DocumentFactory.getInstance();
38  
39      /*** The <code>QName</code> for this element */
40      private QName qname;
41  
42      /***
43       * Stores the parent branch of this node which is either a Document if this
44       * element is the root element in a document, or another Element if it is a
45       * child of the root document, or null if it has not been added to a
46       * document yet.
47       */
48      private Branch parentBranch;
49  
50      /***
51       * Stores null for no content, a Node for a single content node or a List
52       * for multiple content nodes. The List will be lazily constructed when
53       * required.
54       */
55      private Object content;
56  
57      /*** Lazily constructes list of attributes */
58      private Object attributes;
59  
60      public DefaultElement(String name) {
61          this.qname = DOCUMENT_FACTORY.createQName(name);
62      }
63  
64      public DefaultElement(QName qname) {
65          this.qname = qname;
66      }
67  
68      public DefaultElement(QName qname, int attributeCount) {
69          this.qname = qname;
70  
71          if (attributeCount > 1) {
72              this.attributes = new ArrayList(attributeCount);
73          }
74      }
75  
76      public DefaultElement(String name, Namespace namespace) {
77          this.qname = DOCUMENT_FACTORY.createQName(name, namespace);
78      }
79  
80      public Element getParent() {
81          Element result = null;
82  
83          if (parentBranch instanceof Element) {
84              result = (Element) parentBranch;
85          }
86  
87          return result;
88      }
89  
90      public void setParent(Element parent) {
91          if (parentBranch instanceof Element || (parent != null)) {
92              parentBranch = parent;
93          }
94      }
95  
96      public Document getDocument() {
97          if (parentBranch instanceof Document) {
98              return (Document) parentBranch;
99          } else if (parentBranch instanceof Element) {
100             Element parent = (Element) parentBranch;
101 
102             return parent.getDocument();
103         }
104 
105         return null;
106     }
107 
108     public void setDocument(Document document) {
109         if (parentBranch instanceof Document || (document != null)) {
110             parentBranch = document;
111         }
112     }
113 
114     public boolean supportsParent() {
115         return true;
116     }
117 
118     public QName getQName() {
119         return qname;
120     }
121 
122     public void setQName(QName name) {
123         this.qname = name;
124     }
125 
126     public String getText() {
127         final Object contentShadow = content;
128 
129         if (contentShadow instanceof List) {
130             return super.getText();
131         } else {
132             if (contentShadow != null) {
133                 return getContentAsText(contentShadow);
134             } else {
135                 return "";
136             }
137         }
138     }
139 
140     public String getStringValue() {
141         final Object contentShadow = content;
142 
143         if (contentShadow instanceof List) {
144             List list = (List) contentShadow;
145 
146             int size = list.size();
147 
148             if (size > 0) {
149                 if (size == 1) {
150                     // optimised to avoid StringBuffer creation
151                     return getContentAsStringValue(list.get(0));
152                 } else {
153                     StringBuffer buffer = new StringBuffer();
154 
155                     for (int i = 0; i < size; i++) {
156                         Object node = list.get(i);
157 
158                         String string = getContentAsStringValue(node);
159 
160                         if (string.length() > 0) {
161                             if (USE_STRINGVALUE_SEPARATOR) {
162                                 if (buffer.length() > 0) {
163                                     buffer.append(' ');
164                                 }
165                             }
166 
167                             buffer.append(string);
168                         }
169                     }
170 
171                     return buffer.toString();
172                 }
173             }
174         } else {
175             if (contentShadow != null) {
176                 return getContentAsStringValue(contentShadow);
177             }
178         }
179 
180         return "";
181     }
182 
183     public Object clone() {
184         DefaultElement answer = (DefaultElement) super.clone();
185 
186         if (answer != this) {
187             answer.content = null;
188 
189             answer.attributes = null;
190 
191             answer.appendAttributes(this);
192 
193             answer.appendContent(this);
194         }
195 
196         return answer;
197     }
198 
199     public Namespace getNamespaceForPrefix(String prefix) {
200         if (prefix == null) {
201             prefix = "";
202         }
203 
204         if (prefix.equals(getNamespacePrefix())) {
205             return getNamespace();
206         } else if (prefix.equals("xml")) {
207             return Namespace.XML_NAMESPACE;
208         } else {
209             final Object contentShadow = content;
210 
211             if (contentShadow instanceof List) {
212                 List list = (List) contentShadow;
213 
214                 int size = list.size();
215 
216                 for (int i = 0; i < size; i++) {
217                     Object object = list.get(i);
218 
219                     if (object instanceof Namespace) {
220                         Namespace namespace = (Namespace) object;
221 
222                         if (prefix.equals(namespace.getPrefix())) {
223                             return namespace;
224                         }
225                     }
226                 }
227             } else if (contentShadow instanceof Namespace) {
228                 Namespace namespace = (Namespace) contentShadow;
229 
230                 if (prefix.equals(namespace.getPrefix())) {
231                     return namespace;
232                 }
233             }
234         }
235 
236         Element parent = getParent();
237 
238         if (parent != null) {
239             Namespace answer = parent.getNamespaceForPrefix(prefix);
240 
241             if (answer != null) {
242                 return answer;
243             }
244         }
245 
246         if ((prefix == null) || (prefix.length() <= 0)) {
247             return Namespace.NO_NAMESPACE;
248         }
249 
250         return null;
251     }
252 
253     public Namespace getNamespaceForURI(String uri) {
254         if ((uri == null) || (uri.length() <= 0)) {
255             return Namespace.NO_NAMESPACE;
256         } else if (uri.equals(getNamespaceURI())) {
257             return getNamespace();
258         } else {
259             final Object contentShadow = content;
260 
261             if (contentShadow instanceof List) {
262                 List list = (List) contentShadow;
263 
264                 int size = list.size();
265 
266                 for (int i = 0; i < size; i++) {
267                     Object object = list.get(i);
268 
269                     if (object instanceof Namespace) {
270                         Namespace namespace = (Namespace) object;
271 
272                         if (uri.equals(namespace.getURI())) {
273                             return namespace;
274                         }
275                     }
276                 }
277             } else if (contentShadow instanceof Namespace) {
278                 Namespace namespace = (Namespace) contentShadow;
279 
280                 if (uri.equals(namespace.getURI())) {
281                     return namespace;
282                 }
283             }
284 
285             Element parent = getParent();
286 
287             if (parent != null) {
288                 return parent.getNamespaceForURI(uri);
289             }
290 
291             return null;
292         }
293     }
294 
295     public List declaredNamespaces() {
296         BackedList answer = createResultList();
297 
298         // if (getNamespaceURI().length() > 0) {
299         //
300         // answer.addLocal(getNamespace());
301         //
302         // }
303         final Object contentShadow = content;
304 
305         if (contentShadow instanceof List) {
306             List list = (List) contentShadow;
307 
308             int size = list.size();
309 
310             for (int i = 0; i < size; i++) {
311                 Object object = list.get(i);
312 
313                 if (object instanceof Namespace) {
314                     answer.addLocal(object);
315                 }
316             }
317         } else {
318             if (contentShadow instanceof Namespace) {
319                 answer.addLocal(contentShadow);
320             }
321         }
322 
323         return answer;
324     }
325 
326     public List additionalNamespaces() {
327         final Object contentShadow = content;
328 
329         if (contentShadow instanceof List) {
330             List list = (List) contentShadow;
331 
332             int size = list.size();
333 
334             BackedList answer = createResultList();
335 
336             for (int i = 0; i < size; i++) {
337                 Object object = list.get(i);
338 
339                 if (object instanceof Namespace) {
340                     Namespace namespace = (Namespace) object;
341 
342                     if (!namespace.equals(getNamespace())) {
343                         answer.addLocal(namespace);
344                     }
345                 }
346             }
347 
348             return answer;
349         } else {
350             if (contentShadow instanceof Namespace) {
351                 Namespace namespace = (Namespace) contentShadow;
352 
353                 if (namespace.equals(getNamespace())) {
354                     return createEmptyList();
355                 }
356 
357                 return createSingleResultList(namespace);
358             } else {
359                 return createEmptyList();
360             }
361         }
362     }
363 
364     public List additionalNamespaces(String defaultNamespaceURI) {
365         final Object contentShadow = content;
366 
367         if (contentShadow instanceof List) {
368             List list = (List) contentShadow;
369 
370             BackedList answer = createResultList();
371 
372             int size = list.size();
373 
374             for (int i = 0; i < size; i++) {
375                 Object object = list.get(i);
376 
377                 if (object instanceof Namespace) {
378                     Namespace namespace = (Namespace) object;
379 
380                     if (!defaultNamespaceURI.equals(namespace.getURI())) {
381                         answer.addLocal(namespace);
382                     }
383                 }
384             }
385 
386             return answer;
387         } else {
388             if (contentShadow instanceof Namespace) {
389                 Namespace namespace = (Namespace) contentShadow;
390 
391                 if (!defaultNamespaceURI.equals(namespace.getURI())) {
392                     return createSingleResultList(namespace);
393                 }
394             }
395         }
396 
397         return createEmptyList();
398     }
399 
400     // Processing instruction API
401     public List processingInstructions() {
402         final Object contentShadow = content;
403 
404         if (contentShadow instanceof List) {
405             List list = (List) contentShadow;
406 
407             BackedList answer = createResultList();
408 
409             int size = list.size();
410 
411             for (int i = 0; i < size; i++) {
412                 Object object = list.get(i);
413 
414                 if (object instanceof ProcessingInstruction) {
415                     answer.addLocal(object);
416                 }
417             }
418 
419             return answer;
420         } else {
421             if (contentShadow instanceof ProcessingInstruction) {
422                 return createSingleResultList(contentShadow);
423             }
424 
425             return createEmptyList();
426         }
427     }
428 
429     public List processingInstructions(String target) {
430         final Object shadow = content;
431 
432         if (shadow instanceof List) {
433             List list = (List) shadow;
434 
435             BackedList answer = createResultList();
436 
437             int size = list.size();
438 
439             for (int i = 0; i < size; i++) {
440                 Object object = list.get(i);
441 
442                 if (object instanceof ProcessingInstruction) {
443                     ProcessingInstruction pi = (ProcessingInstruction) object;
444 
445                     if (target.equals(pi.getName())) {
446                         answer.addLocal(pi);
447                     }
448                 }
449             }
450 
451             return answer;
452         } else {
453             if (shadow instanceof ProcessingInstruction) {
454                 ProcessingInstruction pi = (ProcessingInstruction) shadow;
455 
456                 if (target.equals(pi.getName())) {
457                     return createSingleResultList(pi);
458                 }
459             }
460 
461             return createEmptyList();
462         }
463     }
464 
465     public ProcessingInstruction processingInstruction(String target) {
466         final Object shadow = content;
467 
468         if (shadow instanceof List) {
469             List list = (List) shadow;
470 
471             int size = list.size();
472 
473             for (int i = 0; i < size; i++) {
474                 Object object = list.get(i);
475 
476                 if (object instanceof ProcessingInstruction) {
477                     ProcessingInstruction pi = (ProcessingInstruction) object;
478 
479                     if (target.equals(pi.getName())) {
480                         return pi;
481                     }
482                 }
483             }
484         } else {
485             if (shadow instanceof ProcessingInstruction) {
486                 ProcessingInstruction pi = (ProcessingInstruction) shadow;
487 
488                 if (target.equals(pi.getName())) {
489                     return pi;
490                 }
491             }
492         }
493 
494         return null;
495     }
496 
497     public boolean removeProcessingInstruction(String target) {
498         final Object shadow = content;
499 
500         if (shadow instanceof List) {
501             List list = (List) shadow;
502 
503             for (Iterator iter = list.iterator(); iter.hasNext();) {
504                 Object object = iter.next();
505 
506                 if (object instanceof ProcessingInstruction) {
507                     ProcessingInstruction pi = (ProcessingInstruction) object;
508 
509                     if (target.equals(pi.getName())) {
510                         iter.remove();
511 
512                         return true;
513                     }
514                 }
515             }
516         } else {
517             if (shadow instanceof ProcessingInstruction) {
518                 ProcessingInstruction pi = (ProcessingInstruction) shadow;
519 
520                 if (target.equals(pi.getName())) {
521                     this.content = null;
522 
523                     return true;
524                 }
525             }
526         }
527 
528         return false;
529     }
530 
531     public Element element(String name) {
532         final Object contentShadow = content;
533 
534         if (contentShadow instanceof List) {
535             List list = (List) contentShadow;
536 
537             int size = list.size();
538 
539             for (int i = 0; i < size; i++) {
540                 Object object = list.get(i);
541 
542                 if (object instanceof Element) {
543                     Element element = (Element) object;
544 
545                     if (name.equals(element.getName())) {
546                         return element;
547                     }
548                 }
549             }
550         } else {
551             if (contentShadow instanceof Element) {
552                 Element element = (Element) contentShadow;
553 
554                 if (name.equals(element.getName())) {
555                     return element;
556                 }
557             }
558         }
559 
560         return null;
561     }
562 
563     public Element element(QName qName) {
564         final Object contentShadow = content;
565 
566         if (contentShadow instanceof List) {
567             List list = (List) contentShadow;
568 
569             int size = list.size();
570 
571             for (int i = 0; i < size; i++) {
572                 Object object = list.get(i);
573 
574                 if (object instanceof Element) {
575                     Element element = (Element) object;
576 
577                     if (qName.equals(element.getQName())) {
578                         return element;
579                     }
580                 }
581             }
582         } else {
583             if (contentShadow instanceof Element) {
584                 Element element = (Element) contentShadow;
585 
586                 if (qName.equals(element.getQName())) {
587                     return element;
588                 }
589             }
590         }
591 
592         return null;
593     }
594 
595     public Element element(String name, Namespace namespace) {
596         return element(getDocumentFactory().createQName(name, namespace));
597     }
598 
599     public void setContent(List content) {
600         contentRemoved();
601 
602         if (content instanceof ContentListFacade) {
603             content = ((ContentListFacade) content).getBackingList();
604         }
605 
606         if (content == null) {
607             this.content = null;
608         } else {
609             int size = content.size();
610 
611             List newContent = createContentList(size);
612 
613             for (int i = 0; i < size; i++) {
614                 Object object = content.get(i);
615 
616                 if (object instanceof Node) {
617                     Node node = (Node) object;
618                     Element parent = node.getParent();
619 
620                     if ((parent != null) && (parent != this)) {
621                         node = (Node) node.clone();
622                     }
623 
624                     newContent.add(node);
625                     childAdded(node);
626                 } else if (object != null) {
627                     String text = object.toString();
628                     Node node = getDocumentFactory().createText(text);
629                     newContent.add(node);
630                     childAdded(node);
631                 }
632             }
633 
634             this.content = newContent;
635         }
636     }
637 
638     public void clearContent() {
639         if (content != null) {
640             contentRemoved();
641 
642             content = null;
643         }
644     }
645 
646     public Node node(int index) {
647         if (index >= 0) {
648             final Object contentShadow = content;
649             Object node;
650 
651             if (contentShadow instanceof List) {
652                 List list = (List) contentShadow;
653 
654                 if (index >= list.size()) {
655                     return null;
656                 }
657 
658                 node = list.get(index);
659             } else {
660                 node = (index == 0) ? contentShadow : null;
661             }
662 
663             if (node != null) {
664                 if (node instanceof Node) {
665                     return (Node) node;
666                 } else {
667                     return new DefaultText(node.toString());
668                 }
669             }
670         }
671 
672         return null;
673     }
674 
675     public int indexOf(Node node) {
676         final Object contentShadow = content;
677 
678         if (contentShadow instanceof List) {
679             List list = (List) contentShadow;
680 
681             return list.indexOf(node);
682         } else {
683             if ((contentShadow != null) && contentShadow.equals(node)) {
684                 return 0;
685             } else {
686                 return -1;
687             }
688         }
689     }
690 
691     public int nodeCount() {
692         final Object contentShadow = content;
693 
694         if (contentShadow instanceof List) {
695             List list = (List) contentShadow;
696 
697             return list.size();
698         } else {
699             return (contentShadow != null) ? 1 : 0;
700         }
701     }
702 
703     public Iterator nodeIterator() {
704         final Object contentShadow = content;
705 
706         if (contentShadow instanceof List) {
707             List list = (List) contentShadow;
708 
709             return list.iterator();
710         } else {
711             if (contentShadow != null) {
712                 return createSingleIterator(contentShadow);
713             } else {
714                 return EMPTY_ITERATOR;
715             }
716         }
717     }
718 
719     public List attributes() {
720         return new ContentListFacade(this, attributeList());
721     }
722 
723     public void setAttributes(List attributes) {
724         if (attributes instanceof ContentListFacade) {
725             attributes = ((ContentListFacade) attributes).getBackingList();
726         }
727 
728         this.attributes = attributes;
729     }
730 
731     public Iterator attributeIterator() {
732         final Object attributesShadow = this.attributes;
733 
734         if (attributesShadow instanceof List) {
735             List list = (List) attributesShadow;
736 
737             return list.iterator();
738         } else if (attributesShadow != null) {
739             return createSingleIterator(attributesShadow);
740         } else {
741             return EMPTY_ITERATOR;
742         }
743     }
744 
745     public Attribute attribute(int index) {
746         final Object attributesShadow = this.attributes;
747 
748         if (attributesShadow instanceof List) {
749             List list = (List) attributesShadow;
750 
751             return (Attribute) list.get(index);
752         } else if ((attributesShadow != null) && (index == 0)) {
753             return (Attribute) attributesShadow;
754         } else {
755             return null;
756         }
757     }
758 
759     public int attributeCount() {
760         final Object attributesShadow = this.attributes;
761 
762         if (attributesShadow instanceof List) {
763             List list = (List) attributesShadow;
764 
765             return list.size();
766         } else {
767             return (attributesShadow != null) ? 1 : 0;
768         }
769     }
770 
771     public Attribute attribute(String name) {
772         final Object attributesShadow = this.attributes;
773 
774         if (attributesShadow instanceof List) {
775             List list = (List) attributesShadow;
776 
777             int size = list.size();
778 
779             for (int i = 0; i < size; i++) {
780                 Attribute attribute = (Attribute) list.get(i);
781 
782                 if (name.equals(attribute.getName())) {
783                     return attribute;
784                 }
785             }
786         } else if (attributesShadow != null) {
787             Attribute attribute = (Attribute) attributesShadow;
788 
789             if (name.equals(attribute.getName())) {
790                 return attribute;
791             }
792         }
793 
794         return null;
795     }
796 
797     public Attribute attribute(QName qName) {
798         final Object attributesShadow = this.attributes;
799 
800         if (attributesShadow instanceof List) {
801             List list = (List) attributesShadow;
802 
803             int size = list.size();
804 
805             for (int i = 0; i < size; i++) {
806                 Attribute attribute = (Attribute) list.get(i);
807 
808                 if (qName.equals(attribute.getQName())) {
809                     return attribute;
810                 }
811             }
812         } else if (attributesShadow != null) {
813             Attribute attribute = (Attribute) attributesShadow;
814 
815             if (qName.equals(attribute.getQName())) {
816                 return attribute;
817             }
818         }
819 
820         return null;
821     }
822 
823     public Attribute attribute(String name, Namespace namespace) {
824         return attribute(getDocumentFactory().createQName(name, namespace));
825     }
826 
827     public void add(Attribute attribute) {
828         if (attribute.getParent() != null) {
829             String message = "The Attribute already has an existing parent \""
830                     + attribute.getParent().getQualifiedName() + "\"";
831 
832             throw new IllegalAddException(this, attribute, message);
833         }
834 
835         if (attribute.getValue() == null) {
836             // try remove a previous attribute with the same
837             // name since adding an attribute with a null value
838             // is equivalent to removing it.
839             Attribute oldAttribute = attribute(attribute.getQName());
840 
841             if (oldAttribute != null) {
842                 remove(oldAttribute);
843             }
844         } else {
845             if (attributes == null) {
846                 attributes = attribute;
847             } else {
848                 attributeList().add(attribute);
849             }
850 
851             childAdded(attribute);
852         }
853     }
854 
855     public boolean remove(Attribute attribute) {
856         boolean answer = false;
857         final Object attributesShadow = this.attributes;
858 
859         if (attributesShadow instanceof List) {
860             List list = (List) attributesShadow;
861 
862             answer = list.remove(attribute);
863 
864             if (!answer) {
865                 // we may have a copy of the attribute
866                 Attribute copy = attribute(attribute.getQName());
867 
868                 if (copy != null) {
869                     list.remove(copy);
870 
871                     answer = true;
872                 }
873             }
874         } else if (attributesShadow != null) {
875             if (attribute.equals(attributesShadow)) {
876                 this.attributes = null;
877 
878                 answer = true;
879             } else {
880                 // we may have a copy of the attribute
881                 Attribute other = (Attribute) attributesShadow;
882 
883                 if (attribute.getQName().equals(other.getQName())) {
884                     attributes = null;
885 
886                     answer = true;
887                 }
888             }
889         }
890 
891         if (answer) {
892             childRemoved(attribute);
893         }
894 
895         return answer;
896     }
897 
898     // Implementation methods
899     // -------------------------------------------------------------------------
900     protected void addNewNode(Node node) {
901         final Object contentShadow = content;
902 
903         if (contentShadow == null) {
904             this.content = node;
905         } else {
906             if (contentShadow instanceof List) {
907                 List list = (List) contentShadow;
908 
909                 list.add(node);
910             } else {
911                 List list = createContentList();
912 
913                 list.add(contentShadow);
914 
915                 list.add(node);
916 
917                 this.content = list;
918             }
919         }
920 
921         childAdded(node);
922     }
923 
924     protected boolean removeNode(Node node) {
925         boolean answer = false;
926         final Object contentShadow = content;
927 
928         if (contentShadow != null) {
929             if (contentShadow == node) {
930                 this.content = null;
931 
932                 answer = true;
933             } else if (contentShadow instanceof List) {
934                 List list = (List) contentShadow;
935 
936                 answer = list.remove(node);
937             }
938         }
939 
940         if (answer) {
941             childRemoved(node);
942         }
943 
944         return answer;
945     }
946 
947     protected List contentList() {
948         final Object contentShadow = content;
949 
950         if (contentShadow instanceof List) {
951             return (List) contentShadow;
952         } else {
953             List list = createContentList();
954 
955             if (contentShadow != null) {
956                 list.add(contentShadow);
957             }
958 
959             this.content = list;
960 
961             return list;
962         }
963     }
964 
965     protected List attributeList() {
966         final Object attributesShadow = this.attributes;
967 
968         if (attributesShadow instanceof List) {
969             return (List) attributesShadow;
970         } else if (attributesShadow != null) {
971             List list = createAttributeList();
972 
973             list.add(attributesShadow);
974 
975             this.attributes = list;
976 
977             return list;
978         } else {
979             List list = createAttributeList();
980 
981             this.attributes = list;
982 
983             return list;
984         }
985     }
986 
987     protected List attributeList(int size) {
988         final Object attributesShadow = this.attributes;
989 
990         if (attributesShadow instanceof List) {
991             return (List) attributesShadow;
992         } else if (attributesShadow != null) {
993             List list = createAttributeList(size);
994 
995             list.add(attributesShadow);
996 
997             this.attributes = list;
998 
999             return list;
1000         } else {
1001             List list = createAttributeList(size);
1002 
1003             this.attributes = list;
1004 
1005             return list;
1006         }
1007     }
1008 
1009     protected void setAttributeList(List attributeList) {
1010         this.attributes = attributeList;
1011     }
1012 
1013     protected DocumentFactory getDocumentFactory() {
1014         DocumentFactory factory = qname.getDocumentFactory();
1015 
1016         return (factory != null) ? factory : DOCUMENT_FACTORY;
1017     }
1018 }
1019 
1020 /*
1021  * Redistribution and use of this software and associated documentation
1022  * ("Software"), with or without modification, are permitted provided that the
1023  * following conditions are met:
1024  * 
1025  * 1. Redistributions of source code must retain copyright statements and
1026  * notices. Redistributions must also contain a copy of this document.
1027  * 
1028  * 2. Redistributions in binary form must reproduce the above copyright notice,
1029  * this list of conditions and the following disclaimer in the documentation
1030  * and/or other materials provided with the distribution.
1031  * 
1032  * 3. The name "DOM4J" must not be used to endorse or promote products derived
1033  * from this Software without prior written permission of MetaStuff, Ltd. For
1034  * written permission, please contact dom4j-info@metastuff.com.
1035  * 
1036  * 4. Products derived from this Software may not be called "DOM4J" nor may
1037  * "DOM4J" appear in their names without prior written permission of MetaStuff,
1038  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
1039  * 
1040  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
1041  * 
1042  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
1043  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1044  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1045  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
1046  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
1047  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
1048  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
1049  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
1050  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
1051  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
1052  * POSSIBILITY OF SUCH DAMAGE.
1053  * 
1054  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
1055  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/AbstractCharacterData.html0000644000175000017500000002062010242117763023566 0ustar ebourgebourg AbstractCharacterData xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import org.dom4j.CharacterData;
11  import org.dom4j.Element;
12  
13  /***
14   * <p>
15   * <code>AbstractCharacterData</code> is an abstract base class for tree
16   * implementors to use for implementation inheritence.
17   * </p>
18   * 
19   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
20   * @version $Revision: 1.12 $
21   */
22  public abstract class AbstractCharacterData extends AbstractNode implements
23          CharacterData {
24      public AbstractCharacterData() {
25      }
26  
27      public String getPath(Element context) {
28          Element parent = getParent();
29  
30          return ((parent != null) && (parent != context)) ? (parent
31                  .getPath(context) + "/text()") : "text()";
32      }
33  
34      public String getUniquePath(Element context) {
35          Element parent = getParent();
36  
37          return ((parent != null) && (parent != context)) ? (parent
38                  .getUniquePath(context) + "/text()") : "text()";
39      }
40  
41      public void appendText(String text) {
42          setText(getText() + text);
43      }
44  }
45  
46  /*
47   * Redistribution and use of this software and associated documentation
48   * ("Software"), with or without modification, are permitted provided that the
49   * following conditions are met:
50   * 
51   * 1. Redistributions of source code must retain copyright statements and
52   * notices. Redistributions must also contain a copy of this document.
53   * 
54   * 2. Redistributions in binary form must reproduce the above copyright notice,
55   * this list of conditions and the following disclaimer in the documentation
56   * and/or other materials provided with the distribution.
57   * 
58   * 3. The name "DOM4J" must not be used to endorse or promote products derived
59   * from this Software without prior written permission of MetaStuff, Ltd. For
60   * written permission, please contact dom4j-info@metastuff.com.
61   * 
62   * 4. Products derived from this Software may not be called "DOM4J" nor may
63   * "DOM4J" appear in their names without prior written permission of MetaStuff,
64   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
65   * 
66   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
67   * 
68   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
69   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
70   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
71   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
72   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
73   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
74   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
75   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
76   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
77   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
78   * POSSIBILITY OF SUCH DAMAGE.
79   * 
80   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
81   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/SingleIterator.html0000644000175000017500000001771610242117737022364 0ustar ebourgebourg SingleIterator xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.util.Iterator;
11  
12  /***
13   * <p>
14   * <code>SingleIterator</code> is an {@link Iterator}over a single object
15   * instance.
16   * </p>
17   * 
18   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
19   * @version $Revision: 1.9 $
20   */
21  public class SingleIterator implements Iterator {
22      private boolean first = true;
23  
24      private Object object;
25  
26      public SingleIterator(Object object) {
27          this.object = object;
28      }
29  
30      public boolean hasNext() {
31          return first;
32      }
33  
34      public Object next() {
35          Object answer = object;
36          object = null;
37          first = false;
38  
39          return answer;
40      }
41  
42      public void remove() {
43          throw new UnsupportedOperationException("remove() is not supported by "
44                  + "this iterator");
45      }
46  }
47  
48  /*
49   * Redistribution and use of this software and associated documentation
50   * ("Software"), with or without modification, are permitted provided that the
51   * following conditions are met:
52   * 
53   * 1. Redistributions of source code must retain copyright statements and
54   * notices. Redistributions must also contain a copy of this document.
55   * 
56   * 2. Redistributions in binary form must reproduce the above copyright notice,
57   * this list of conditions and the following disclaimer in the documentation
58   * and/or other materials provided with the distribution.
59   * 
60   * 3. The name "DOM4J" must not be used to endorse or promote products derived
61   * from this Software without prior written permission of MetaStuff, Ltd. For
62   * written permission, please contact dom4j-info@metastuff.com.
63   * 
64   * 4. Products derived from this Software may not be called "DOM4J" nor may
65   * "DOM4J" appear in their names without prior written permission of MetaStuff,
66   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
67   * 
68   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
69   * 
70   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
71   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
72   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
73   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
74   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
75   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
76   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
77   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
78   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
79   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
80   * POSSIBILITY OF SUCH DAMAGE.
81   * 
82   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
83   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/FilterIterator.html0000644000175000017500000002627710242117757022374 0ustar ebourgebourg FilterIterator xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.util.Iterator;
11  import java.util.NoSuchElementException;
12  
13  /***
14   * <p>
15   * <code>FilterIterator</code> is an abstract base class which is useful for
16   * implementors of {@link Iterator}which filter an existing iterator.
17   * </p>
18   * 
19   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
20   * @version $Revision: 1.10 $
21   * 
22   * @deprecated THIS CLASS WILL BE REMOVED IN dom4j-1.6 !!
23   */
24  public abstract class FilterIterator implements Iterator {
25      protected Iterator proxy;
26  
27      private Object next;
28  
29      private boolean first = true;
30  
31      public FilterIterator(Iterator proxy) {
32          this.proxy = proxy;
33      }
34  
35      public boolean hasNext() {
36          if (first) {
37              next = findNext();
38              first = false;
39          }
40  
41          return next != null;
42      }
43  
44      public Object next() throws NoSuchElementException {
45          if (!hasNext()) {
46              throw new NoSuchElementException();
47          }
48  
49          Object answer = this.next;
50          this.next = findNext();
51  
52          return answer;
53      }
54  
55      /***
56       * Always throws UnsupportedOperationException as this class does look-ahead
57       * with its internal iterator.
58       * 
59       * @throws UnsupportedOperationException
60       *             always
61       */
62      public void remove() {
63          throw new UnsupportedOperationException();
64      }
65  
66      /***
67       * Filter method to perform some matching on the given element.
68       * 
69       * @param element
70       *            DOCUMENT ME!
71       * 
72       * @return true if the given element matches the filter and should be appear
73       *         in the iteration
74       */
75      protected abstract boolean matches(Object element);
76  
77      protected Object findNext() {
78          if (proxy != null) {
79              while (proxy.hasNext()) {
80                  Object nextObject = proxy.next();
81  
82                  if ((nextObject != null) && matches(nextObject)) {
83                      return nextObject;
84                  }
85              }
86  
87              proxy = null;
88          }
89  
90          return null;
91      }
92  }
93  
94  /*
95   * Redistribution and use of this software and associated documentation
96   * ("Software"), with or without modification, are permitted provided that the
97   * following conditions are met:
98   * 
99   * 1. Redistributions of source code must retain copyright statements and
100  * notices. Redistributions must also contain a copy of this document.
101  * 
102  * 2. Redistributions in binary form must reproduce the above copyright notice,
103  * this list of conditions and the following disclaimer in the documentation
104  * and/or other materials provided with the distribution.
105  * 
106  * 3. The name "DOM4J" must not be used to endorse or promote products derived
107  * from this Software without prior written permission of MetaStuff, Ltd. For
108  * written permission, please contact dom4j-info@metastuff.com.
109  * 
110  * 4. Products derived from this Software may not be called "DOM4J" nor may
111  * "DOM4J" appear in their names without prior written permission of MetaStuff,
112  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
113  * 
114  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
115  * 
116  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
117  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
118  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
119  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
120  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
121  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
122  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
123  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
124  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
125  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
126  * POSSIBILITY OF SUCH DAMAGE.
127  * 
128  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
129  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/NamespaceStack.html0000644000175000017500000011646110242117752022305 0ustar ebourgebourg NamespaceStack xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.util.ArrayList;
11  import java.util.HashMap;
12  import java.util.Map;
13  
14  import org.dom4j.DocumentFactory;
15  import org.dom4j.Namespace;
16  import org.dom4j.QName;
17  
18  /***
19   * NamespaceStack implements a stack of namespaces and optionally maintains a
20   * cache of all the fully qualified names (<code>QName</code>) which are in
21   * scope. This is useful when building or navigating a <i>dom4j </i> document.
22   * 
23   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
24   * @version $Revision: 1.13 $
25   */
26  public class NamespaceStack {
27      /*** The factory used to create new <code>Namespace</code> instances */
28      private DocumentFactory documentFactory;
29  
30      /*** The Stack of namespaces */
31      private ArrayList namespaceStack = new ArrayList();
32  
33      /*** The cache of qualifiedNames to QNames per namespace context */
34      private ArrayList namespaceCacheList = new ArrayList();
35  
36      /***
37       * A cache of current namespace context cache of mapping from qualifiedName
38       * to QName
39       */
40      private Map currentNamespaceCache;
41  
42      /***
43       * A cache of mapping from qualifiedName to QName before any namespaces are
44       * declared
45       */
46      private Map rootNamespaceCache = new HashMap();
47  
48      /*** Caches the default namespace defined via xmlns="" */
49      private Namespace defaultNamespace;
50  
51      public NamespaceStack() {
52          this.documentFactory = DocumentFactory.getInstance();
53      }
54  
55      public NamespaceStack(DocumentFactory documentFactory) {
56          this.documentFactory = documentFactory;
57      }
58  
59      /***
60       * Pushes the given namespace onto the stack so that its prefix becomes
61       * available.
62       * 
63       * @param namespace
64       *            is the <code>Namespace</code> to add to the stack.
65       */
66      public void push(Namespace namespace) {
67          namespaceStack.add(namespace);
68          namespaceCacheList.add(null);
69          currentNamespaceCache = null;
70  
71          String prefix = namespace.getPrefix();
72  
73          if ((prefix == null) || (prefix.length() == 0)) {
74              defaultNamespace = namespace;
75          }
76      }
77  
78      /***
79       * Pops the most recently used <code>Namespace</code> from the stack
80       * 
81       * @return Namespace popped from the stack
82       */
83      public Namespace pop() {
84          return remove(namespaceStack.size() - 1);
85      }
86  
87      /***
88       * DOCUMENT ME!
89       * 
90       * @return the number of namespaces on the stackce stack.
91       */
92      public int size() {
93          return namespaceStack.size();
94      }
95  
96      /***
97       * Clears the stack
98       */
99      public void clear() {
100         namespaceStack.clear();
101         namespaceCacheList.clear();
102         rootNamespaceCache.clear();
103         currentNamespaceCache = null;
104     }
105 
106     /***
107      * DOCUMENT ME!
108      * 
109      * @param index
110      *            DOCUMENT ME!
111      * 
112      * @return the namespace at the specified index on the stack
113      */
114     public Namespace getNamespace(int index) {
115         return (Namespace) namespaceStack.get(index);
116     }
117 
118     /***
119      * DOCUMENT ME!
120      * 
121      * @param prefix
122      *            DOCUMENT ME!
123      * 
124      * @return the namespace for the given prefix or null if it could not be
125      *         found.
126      */
127     public Namespace getNamespaceForPrefix(String prefix) {
128         if (prefix == null) {
129             prefix = "";
130         }
131 
132         for (int i = namespaceStack.size() - 1; i >= 0; i--) {
133             Namespace namespace = (Namespace) namespaceStack.get(i);
134 
135             if (prefix.equals(namespace.getPrefix())) {
136                 return namespace;
137             }
138         }
139 
140         return null;
141     }
142 
143     /***
144      * DOCUMENT ME!
145      * 
146      * @param prefix
147      *            DOCUMENT ME!
148      * 
149      * @return the URI for the given prefix or null if it could not be found.
150      */
151     public String getURI(String prefix) {
152         Namespace namespace = getNamespaceForPrefix(prefix);
153 
154         return (namespace != null) ? namespace.getURI() : null;
155     }
156 
157     /***
158      * DOCUMENT ME!
159      * 
160      * @param namespace
161      *            DOCUMENT ME!
162      * 
163      * @return true if the given prefix is in the stack.
164      */
165     public boolean contains(Namespace namespace) {
166         String prefix = namespace.getPrefix();
167         Namespace current = null;
168 
169         if ((prefix == null) || (prefix.length() == 0)) {
170             current = getDefaultNamespace();
171         } else {
172             current = getNamespaceForPrefix(prefix);
173         }
174 
175         if (current == null) {
176             return false;
177         }
178 
179         if (current == namespace) {
180             return true;
181         }
182 
183         return namespace.getURI().equals(current.getURI());
184     }
185 
186     public QName getQName(String namespaceURI, String localName,
187             String qualifiedName) {
188         if (localName == null) {
189             localName = qualifiedName;
190         } else if (qualifiedName == null) {
191             qualifiedName = localName;
192         }
193 
194         if (namespaceURI == null) {
195             namespaceURI = "";
196         }
197 
198         String prefix = "";
199         int index = qualifiedName.indexOf(":");
200 
201         if (index > 0) {
202             prefix = qualifiedName.substring(0, index);
203 
204             if (localName.trim().length() == 0) {
205                 localName = qualifiedName.substring(index + 1);
206             }
207         } else if (localName.trim().length() == 0) {
208             localName = qualifiedName;
209         }
210 
211         Namespace namespace = createNamespace(prefix, namespaceURI);
212 
213         return pushQName(localName, qualifiedName, namespace, prefix);
214     }
215 
216     public QName getAttributeQName(String namespaceURI, String localName,
217             String qualifiedName) {
218         if (qualifiedName == null) {
219             qualifiedName = localName;
220         }
221 
222         Map map = getNamespaceCache();
223         QName answer = (QName) map.get(qualifiedName);
224 
225         if (answer != null) {
226             return answer;
227         }
228 
229         if (localName == null) {
230             localName = qualifiedName;
231         }
232 
233         if (namespaceURI == null) {
234             namespaceURI = "";
235         }
236 
237         Namespace namespace = null;
238         String prefix = "";
239         int index = qualifiedName.indexOf(":");
240 
241         if (index > 0) {
242             prefix = qualifiedName.substring(0, index);
243             namespace = createNamespace(prefix, namespaceURI);
244 
245             if (localName.trim().length() == 0) {
246                 localName = qualifiedName.substring(index + 1);
247             }
248         } else {
249             // attributes with no prefix have no namespace
250             namespace = Namespace.NO_NAMESPACE;
251 
252             if (localName.trim().length() == 0) {
253                 localName = qualifiedName;
254             }
255         }
256 
257         answer = pushQName(localName, qualifiedName, namespace, prefix);
258         map.put(qualifiedName, answer);
259 
260         return answer;
261     }
262 
263     /***
264      * Adds a namepace to the stack with the given prefix and URI
265      * 
266      * @param prefix
267      *            DOCUMENT ME!
268      * @param uri
269      *            DOCUMENT ME!
270      */
271     public void push(String prefix, String uri) {
272         if (uri == null) {
273             uri = "";
274         }
275 
276         Namespace namespace = createNamespace(prefix, uri);
277         push(namespace);
278     }
279 
280     /***
281      * Adds a new namespace to the stack
282      * 
283      * @param prefix
284      *            DOCUMENT ME!
285      * @param uri
286      *            DOCUMENT ME!
287      * 
288      * @return DOCUMENT ME!
289      */
290     public Namespace addNamespace(String prefix, String uri) {
291         Namespace namespace = createNamespace(prefix, uri);
292         push(namespace);
293 
294         return namespace;
295     }
296 
297     /***
298      * Pops a namepace from the stack with the given prefix and URI
299      * 
300      * @param prefix
301      *            DOCUMENT ME!
302      * 
303      * @return DOCUMENT ME!
304      */
305     public Namespace pop(String prefix) {
306         if (prefix == null) {
307             prefix = "";
308         }
309 
310         Namespace namespace = null;
311 
312         for (int i = namespaceStack.size() - 1; i >= 0; i--) {
313             Namespace ns = (Namespace) namespaceStack.get(i);
314 
315             if (prefix.equals(ns.getPrefix())) {
316                 remove(i);
317                 namespace = ns;
318 
319                 break;
320             }
321         }
322 
323         if (namespace == null) {
324             System.out.println("Warning: missing namespace prefix ignored: "
325                     + prefix);
326         }
327 
328         return namespace;
329     }
330 
331     public String toString() {
332         return super.toString() + " Stack: " + namespaceStack.toString();
333     }
334 
335     public DocumentFactory getDocumentFactory() {
336         return documentFactory;
337     }
338 
339     public void setDocumentFactory(DocumentFactory documentFactory) {
340         this.documentFactory = documentFactory;
341     }
342 
343     public Namespace getDefaultNamespace() {
344         if (defaultNamespace == null) {
345             defaultNamespace = findDefaultNamespace();
346         }
347 
348         return defaultNamespace;
349     }
350 
351     // Implementation methods
352     // -------------------------------------------------------------------------
353 
354     /***
355      * Adds the QName to the stack of available QNames
356      * 
357      * @param localName
358      *            DOCUMENT ME!
359      * @param qualifiedName
360      *            DOCUMENT ME!
361      * @param namespace
362      *            DOCUMENT ME!
363      * @param prefix
364      *            DOCUMENT ME!
365      * 
366      * @return DOCUMENT ME!
367      */
368     protected QName pushQName(String localName, String qualifiedName,
369             Namespace namespace, String prefix) {
370         if ((prefix == null) || (prefix.length() == 0)) {
371             this.defaultNamespace = null;
372         }
373 
374         return createQName(localName, qualifiedName, namespace);
375     }
376 
377     /***
378      * Factory method to creeate new QName instances. By default this method
379      * interns the QName
380      * 
381      * @param localName
382      *            DOCUMENT ME!
383      * @param qualifiedName
384      *            DOCUMENT ME!
385      * @param namespace
386      *            DOCUMENT ME!
387      * 
388      * @return DOCUMENT ME!
389      */
390     protected QName createQName(String localName, String qualifiedName,
391             Namespace namespace) {
392         return documentFactory.createQName(localName, namespace);
393     }
394 
395     /***
396      * Factory method to creeate new Namespace instances. By default this method
397      * interns the Namespace
398      * 
399      * @param prefix
400      *            DOCUMENT ME!
401      * @param namespaceURI
402      *            DOCUMENT ME!
403      * 
404      * @return DOCUMENT ME!
405      */
406     protected Namespace createNamespace(String prefix, String namespaceURI) {
407         return documentFactory.createNamespace(prefix, namespaceURI);
408     }
409 
410     /***
411      * Attempts to find the current default namespace on the stack right now or
412      * returns null if one could not be found
413      * 
414      * @return DOCUMENT ME!
415      */
416     protected Namespace findDefaultNamespace() {
417         for (int i = namespaceStack.size() - 1; i >= 0; i--) {
418             Namespace namespace = (Namespace) namespaceStack.get(i);
419 
420             if (namespace != null) {
421                 String prefix = namespace.getPrefix();
422 
423                 if ((prefix == null) || (namespace.getPrefix().length() == 0)) {
424                     return namespace;
425                 }
426             }
427         }
428 
429         return null;
430     }
431 
432     /***
433      * Removes the namespace at the given index of the stack
434      * 
435      * @param index
436      *            DOCUMENT ME!
437      * 
438      * @return DOCUMENT ME!
439      */
440     protected Namespace remove(int index) {
441         Namespace namespace = (Namespace) namespaceStack.remove(index);
442         namespaceCacheList.remove(index);
443         defaultNamespace = null;
444         currentNamespaceCache = null;
445 
446         return namespace;
447     }
448 
449     protected Map getNamespaceCache() {
450         if (currentNamespaceCache == null) {
451             int index = namespaceStack.size() - 1;
452 
453             if (index < 0) {
454                 currentNamespaceCache = rootNamespaceCache;
455             } else {
456                 currentNamespaceCache = (Map) namespaceCacheList.get(index);
457 
458                 if (currentNamespaceCache == null) {
459                     currentNamespaceCache = new HashMap();
460                     namespaceCacheList.set(index, currentNamespaceCache);
461                 }
462             }
463         }
464 
465         return currentNamespaceCache;
466     }
467 }
468 
469 /*
470  * Redistribution and use of this software and associated documentation
471  * ("Software"), with or without modification, are permitted provided that the
472  * following conditions are met:
473  * 
474  * 1. Redistributions of source code must retain copyright statements and
475  * notices. Redistributions must also contain a copy of this document.
476  * 
477  * 2. Redistributions in binary form must reproduce the above copyright notice,
478  * this list of conditions and the following disclaimer in the documentation
479  * and/or other materials provided with the distribution.
480  * 
481  * 3. The name "DOM4J" must not be used to endorse or promote products derived
482  * from this Software without prior written permission of MetaStuff, Ltd. For
483  * written permission, please contact dom4j-info@metastuff.com.
484  * 
485  * 4. Products derived from this Software may not be called "DOM4J" nor may
486  * "DOM4J" appear in their names without prior written permission of MetaStuff,
487  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
488  * 
489  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
490  * 
491  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
492  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
493  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
494  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
495  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
496  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
497  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
498  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
499  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
500  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
501  * POSSIBILITY OF SUCH DAMAGE.
502  * 
503  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
504  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/package-summary.html0000644000175000017500000002117210242117624022501 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.tree

Class Summary
AbstractAttribute
AbstractBranch
AbstractCDATA
AbstractCharacterData
AbstractComment
AbstractDocument
AbstractDocumentType
AbstractElement
AbstractEntity
AbstractNode
AbstractProcessingInstruction
AbstractText
BackedList
BaseElement
ConcurrentReaderHashMap
ContentListFacade
DefaultAttribute
DefaultCDATA
DefaultComment
DefaultDocument
DefaultDocumentType
DefaultElement
DefaultEntity
DefaultNamespace
DefaultProcessingInstruction
DefaultText
ElementIterator
ElementNameIterator
ElementQNameIterator
FilterIterator
FlyweightAttribute
FlyweightCDATA
FlyweightComment
FlyweightEntity
FlyweightProcessingInstruction
FlyweightText
NamespaceCache
NamespaceStack
QNameCache
SingleIterator
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref/org/dom4j/tree/DefaultCDATA.html0000644000175000017500000002312710242117677021546 0ustar ebourgebourg DefaultCDATA xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import org.dom4j.Element;
11  
12  /***
13   * <p>
14   * <code>DefaultCDATA</code> is the default CDATA implementation. It is a
15   * doubly linked node which supports the parent relationship and can be modified
16   * in place.
17   * </p>
18   * 
19   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
20   * @version $Revision: 1.12 $
21   */
22  public class DefaultCDATA extends FlyweightCDATA {
23      /*** The parent of this node */
24      private Element parent;
25  
26      /***
27       * DOCUMENT ME!
28       * 
29       * @param text
30       *            is the CDATA text
31       */
32      public DefaultCDATA(String text) {
33          super(text);
34      }
35  
36      /***
37       * DOCUMENT ME!
38       * 
39       * @param parent
40       *            is the parent element
41       * @param text
42       *            is the CDATA text
43       */
44      public DefaultCDATA(Element parent, String text) {
45          super(text);
46          this.parent = parent;
47      }
48  
49      public void setText(String text) {
50          this.text = text;
51      }
52  
53      public Element getParent() {
54          return parent;
55      }
56  
57      public void setParent(Element parent) {
58          this.parent = parent;
59      }
60  
61      public boolean supportsParent() {
62          return true;
63      }
64  
65      public boolean isReadOnly() {
66          return false;
67      }
68  }
69  
70  /*
71   * Redistribution and use of this software and associated documentation
72   * ("Software"), with or without modification, are permitted provided that the
73   * following conditions are met:
74   * 
75   * 1. Redistributions of source code must retain copyright statements and
76   * notices. Redistributions must also contain a copy of this document.
77   * 
78   * 2. Redistributions in binary form must reproduce the above copyright notice,
79   * this list of conditions and the following disclaimer in the documentation
80   * and/or other materials provided with the distribution.
81   * 
82   * 3. The name "DOM4J" must not be used to endorse or promote products derived
83   * from this Software without prior written permission of MetaStuff, Ltd. For
84   * written permission, please contact dom4j-info@metastuff.com.
85   * 
86   * 4. Products derived from this Software may not be called "DOM4J" nor may
87   * "DOM4J" appear in their names without prior written permission of MetaStuff,
88   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
89   * 
90   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
91   * 
92   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
93   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
95   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
96   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
97   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
98   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
99   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
100  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
102  * POSSIBILITY OF SUCH DAMAGE.
103  * 
104  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
105  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/NamespaceCache.html0000644000175000017500000004467710242117725022254 0ustar ebourgebourg NamespaceCache xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.lang.ref.WeakReference;
11  import java.lang.reflect.Constructor;
12  import java.util.Map;
13  
14  import org.dom4j.Namespace;
15  
16  /***
17   * <p>
18   * <code>NamespaceCache</code> caches instances of
19   * <code>DefaultNamespace</code> for reuse both across documents and within
20   * documents.
21   * </p>
22   * 
23   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
24   * @author Maarten Coene
25   * @author Brett Finnell
26   * @version $Revision: 1.15 $
27   */
28  public class NamespaceCache {
29      private static final String CONCURRENTREADERHASHMAP_CLASS
30              = "EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap";
31  
32      /***
33       * Cache of {@link Map}instances indexed by URI which contain caches of
34       * {@link Namespace}for each prefix
35       */
36      protected static Map cache;
37  
38      /***
39       * Cache of {@link Namespace}instances indexed by URI for default
40       * namespaces with no prefixes
41       */
42      protected static Map noPrefixCache;
43  
44      static {
45          /* Try the java.util.concurrent.ConcurrentHashMap first. */
46          try {
47              Class clazz = Class
48                      .forName("java.util.concurrent.ConcurrentHashMap");
49              Constructor construct = clazz.getConstructor(new Class[] {
50                      Integer.TYPE, Float.TYPE, Integer.TYPE });
51              cache = (Map) construct.newInstance(new Object[] {new Integer(11),
52                      new Float(0.75f), new Integer(1) });
53              noPrefixCache = (Map) construct.newInstance(new Object[] {
54                      new Integer(11), new Float(0.75f), new Integer(1) });
55          } catch (Throwable t1) {
56              /* Try to use the util.concurrent library (if in classpath) */
57              try {
58                  Class clazz = Class.forName(CONCURRENTREADERHASHMAP_CLASS);
59                  cache = (Map) clazz.newInstance();
60                  noPrefixCache = (Map) clazz.newInstance();
61              } catch (Throwable t2) {
62                  /* If previous implementations fail, use internal one */
63                  cache = new ConcurrentReaderHashMap();
64                  noPrefixCache = new ConcurrentReaderHashMap();
65              }
66          }
67      }
68  
69      /***
70       * DOCUMENT ME!
71       * 
72       * @param prefix
73       *            DOCUMENT ME!
74       * @param uri
75       *            DOCUMENT ME!
76       * 
77       * @return the namespace for the given prefix and uri
78       */
79      public Namespace get(String prefix, String uri) {
80          Map uriCache = getURICache(uri);
81          WeakReference ref = (WeakReference) uriCache.get(prefix);
82          Namespace answer = null;
83  
84          if (ref != null) {
85              answer = (Namespace) ref.get();
86          }
87  
88          if (answer == null) {
89              synchronized (uriCache) {
90                  ref = (WeakReference) uriCache.get(prefix);
91  
92                  if (ref != null) {
93                      answer = (Namespace) ref.get();
94                  }
95  
96                  if (answer == null) {
97                      answer = createNamespace(prefix, uri);
98                      uriCache.put(prefix, new WeakReference(answer));
99                  }
100             }
101         }
102 
103         return answer;
104     }
105 
106     /***
107      * DOCUMENT ME!
108      * 
109      * @param uri
110      *            DOCUMENT ME!
111      * 
112      * @return the name model for the given name and namepsace
113      */
114     public Namespace get(String uri) {
115         WeakReference ref = (WeakReference) noPrefixCache.get(uri);
116         Namespace answer = null;
117 
118         if (ref != null) {
119             answer = (Namespace) ref.get();
120         }
121 
122         if (answer == null) {
123             synchronized (noPrefixCache) {
124                 ref = (WeakReference) noPrefixCache.get(uri);
125 
126                 if (ref != null) {
127                     answer = (Namespace) ref.get();
128                 }
129 
130                 if (answer == null) {
131                     answer = createNamespace("", uri);
132                     noPrefixCache.put(uri, new WeakReference(answer));
133                 }
134             }
135         }
136 
137         return answer;
138     }
139 
140     /***
141      * DOCUMENT ME!
142      * 
143      * @param uri
144      *            DOCUMENT ME!
145      * 
146      * @return the cache for the given namespace URI. If one does not currently
147      *         exist it is created.
148      */
149     protected Map getURICache(String uri) {
150         Map answer = (Map) cache.get(uri);
151 
152         if (answer == null) {
153             synchronized (cache) {
154                 answer = (Map) cache.get(uri);
155 
156                 if (answer == null) {
157                     answer = new ConcurrentReaderHashMap();
158                     cache.put(uri, answer);
159                 }
160             }
161         }
162 
163         return answer;
164     }
165 
166     /***
167      * A factory method to create {@link Namespace}instance
168      * 
169      * @param prefix
170      *            DOCUMENT ME!
171      * @param uri
172      *            DOCUMENT ME!
173      * 
174      * @return a newly created {@link Namespace}instance.
175      */
176     protected Namespace createNamespace(String prefix, String uri) {
177         return new Namespace(prefix, uri);
178     }
179 }
180 
181 /*
182  * Redistribution and use of this software and associated documentation
183  * ("Software"), with or without modification, are permitted provided that the
184  * following conditions are met:
185  * 
186  * 1. Redistributions of source code must retain copyright statements and
187  * notices. Redistributions must also contain a copy of this document.
188  * 
189  * 2. Redistributions in binary form must reproduce the above copyright notice,
190  * this list of conditions and the following disclaimer in the documentation
191  * and/or other materials provided with the distribution.
192  * 
193  * 3. The name "DOM4J" must not be used to endorse or promote products derived
194  * from this Software without prior written permission of MetaStuff, Ltd. For
195  * written permission, please contact dom4j-info@metastuff.com.
196  * 
197  * 4. Products derived from this Software may not be called "DOM4J" nor may
198  * "DOM4J" appear in their names without prior written permission of MetaStuff,
199  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
200  * 
201  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
202  * 
203  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
204  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
205  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
206  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
207  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
208  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
209  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
210  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
211  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
212  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
213  * POSSIBILITY OF SUCH DAMAGE.
214  * 
215  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
216  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/FlyweightProcessingInstruction.html0000644000175000017500000003155410242117677025671 0ustar ebourgebourg FlyweightProcessingInstruction xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.util.Collections;
11  import java.util.Map;
12  
13  import org.dom4j.Element;
14  import org.dom4j.Node;
15  
16  /***
17   * <p>
18   * <code>FlyweightProcessingInstruction</code> is a Flyweight pattern
19   * implementation of a singly linked, read-only XML Processing Instruction.
20   * </p>
21   * 
22   * <p>
23   * This node could be shared across documents and elements though it does not
24   * support the parent relationship.
25   * </p>
26   * 
27   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
28   * @version $Revision: 1.7 $
29   */
30  public class FlyweightProcessingInstruction extends
31          AbstractProcessingInstruction {
32      /*** The target of the PI */
33      protected String target;
34  
35      /*** The values for the PI as a String */
36      protected String text;
37  
38      /*** The values for the PI in name/value pairs */
39      protected Map values;
40  
41      /***
42       * A default constructor for implementors to use.
43       */
44      public FlyweightProcessingInstruction() {
45      }
46  
47      /***
48       * <p>
49       * This will create a new PI with the given target and values
50       * </p>
51       * 
52       * @param target
53       *            is the name of the PI
54       * @param values
55       *            is the <code>Map</code> of the values for the PI
56       */
57      public FlyweightProcessingInstruction(String target, Map values) {
58          this.target = target;
59          this.values = values;
60          this.text = toString(values);
61      }
62  
63      /***
64       * <p>
65       * This will create a new PI with the given target and values
66       * </p>
67       * 
68       * @param target
69       *            is the name of the PI
70       * @param text
71       *            is the values for the PI as text
72       */
73      public FlyweightProcessingInstruction(String target, String text) {
74          this.target = target;
75          this.text = text;
76          this.values = parseValues(text);
77      }
78  
79      public String getTarget() {
80          return target;
81      }
82  
83      public void setTarget(String target) {
84          throw new UnsupportedOperationException("This PI is read-only and "
85                  + "cannot be modified");
86      }
87  
88      public String getText() {
89          return text;
90      }
91  
92      public String getValue(String name) {
93          String answer = (String) values.get(name);
94  
95          if (answer == null) {
96              return "";
97          }
98  
99          return answer;
100     }
101 
102     public Map getValues() {
103         return Collections.unmodifiableMap(values);
104     }
105 
106     protected Node createXPathResult(Element parent) {
107         return new DefaultProcessingInstruction(parent, getTarget(), getText());
108     }
109 }
110 
111 /*
112  * Redistribution and use of this software and associated documentation
113  * ("Software"), with or without modification, are permitted provided that the
114  * following conditions are met:
115  * 
116  * 1. Redistributions of source code must retain copyright statements and
117  * notices. Redistributions must also contain a copy of this document.
118  * 
119  * 2. Redistributions in binary form must reproduce the above copyright notice,
120  * this list of conditions and the following disclaimer in the documentation
121  * and/or other materials provided with the distribution.
122  * 
123  * 3. The name "DOM4J" must not be used to endorse or promote products derived
124  * from this Software without prior written permission of MetaStuff, Ltd. For
125  * written permission, please contact dom4j-info@metastuff.com.
126  * 
127  * 4. Products derived from this Software may not be called "DOM4J" nor may
128  * "DOM4J" appear in their names without prior written permission of MetaStuff,
129  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
130  * 
131  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
132  * 
133  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
134  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
135  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
136  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
137  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
138  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
139  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
140  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
141  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
142  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
143  * POSSIBILITY OF SUCH DAMAGE.
144  * 
145  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
146  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/package-frame.html0000644000175000017500000001272510242117662022104 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.tree

org.dom4j.tree

Classes

  • AbstractAttribute
  • AbstractBranch
  • AbstractCDATA
  • AbstractCharacterData
  • AbstractComment
  • AbstractDocument
  • AbstractDocumentType
  • AbstractElement
  • AbstractEntity
  • AbstractNode
  • AbstractProcessingInstruction
  • AbstractText
  • BackedList
  • BaseElement
  • ConcurrentReaderHashMap
  • ContentListFacade
  • DefaultAttribute
  • DefaultCDATA
  • DefaultComment
  • DefaultDocument
  • DefaultDocumentType
  • DefaultElement
  • DefaultEntity
  • DefaultNamespace
  • DefaultProcessingInstruction
  • DefaultText
  • ElementIterator
  • ElementNameIterator
  • ElementQNameIterator
  • FilterIterator
  • FlyweightAttribute
  • FlyweightCDATA
  • FlyweightComment
  • FlyweightEntity
  • FlyweightProcessingInstruction
  • FlyweightText
  • NamespaceCache
  • NamespaceStack
  • QNameCache
  • SingleIterator
dom4j-1.6.1/docs/xref/org/dom4j/tree/FlyweightAttribute.html0000644000175000017500000002571610242117631023247 0ustar ebourgebourg FlyweightAttribute xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import org.dom4j.Namespace;
11  import org.dom4j.QName;
12  
13  /***
14   * <p>
15   * <code>FlyweightAttribute</code> is a Flyweight pattern implementation of a
16   * singly linked, read-only XML Attribute.
17   * </p>
18   * 
19   * <p>
20   * This node could be shared across documents and elements though it does not
21   * support the parent relationship.
22   * </p>
23   * 
24   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
25   * @version $Revision: 1.7 $
26   */
27  public class FlyweightAttribute extends AbstractAttribute {
28      /*** The <code>QName</code> for this element */
29      private QName qname;
30  
31      /*** The value of the <code>Attribute</code> */
32      protected String value;
33  
34      public FlyweightAttribute(QName qname) {
35          this.qname = qname;
36      }
37  
38      public FlyweightAttribute(QName qname, String value) {
39          this.qname = qname;
40          this.value = value;
41      }
42  
43      /***
44       * Creates the <code>Attribute</code> with the specified local name and
45       * value.
46       * 
47       * @param name
48       *            is the name of the attribute
49       * @param value
50       *            is the value of the attribute
51       */
52      public FlyweightAttribute(String name, String value) {
53          this.qname = getDocumentFactory().createQName(name);
54          this.value = value;
55      }
56  
57      /***
58       * Creates the <code>Attribute</code> with the specified local name, value
59       * and <code>Namespace</code>.
60       * 
61       * @param name
62       *            is the name of the attribute
63       * @param value
64       *            is the value of the attribute
65       * @param namespace
66       *            is the namespace of the attribute
67       */
68      public FlyweightAttribute(String name, String value, Namespace namespace) {
69          this.qname = getDocumentFactory().createQName(name, namespace);
70          this.value = value;
71      }
72  
73      public String getValue() {
74          return value;
75      }
76  
77      public QName getQName() {
78          return qname;
79      }
80  }
81  
82  /*
83   * Redistribution and use of this software and associated documentation
84   * ("Software"), with or without modification, are permitted provided that the
85   * following conditions are met:
86   * 
87   * 1. Redistributions of source code must retain copyright statements and
88   * notices. Redistributions must also contain a copy of this document.
89   * 
90   * 2. Redistributions in binary form must reproduce the above copyright notice,
91   * this list of conditions and the following disclaimer in the documentation
92   * and/or other materials provided with the distribution.
93   * 
94   * 3. The name "DOM4J" must not be used to endorse or promote products derived
95   * from this Software without prior written permission of MetaStuff, Ltd. For
96   * written permission, please contact dom4j-info@metastuff.com.
97   * 
98   * 4. Products derived from this Software may not be called "DOM4J" nor may
99   * "DOM4J" appear in their names without prior written permission of MetaStuff,
100  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
101  * 
102  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
103  * 
104  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
105  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
106  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
107  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
108  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
109  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
110  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
111  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
112  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
113  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
114  * POSSIBILITY OF SUCH DAMAGE.
115  * 
116  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
117  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/ContentListFacade.html0000644000175000017500000004114010242117616022743 0ustar ebourgebourg ContentListFacade xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.util.AbstractList;
11  import java.util.Collection;
12  import java.util.Iterator;
13  import java.util.List;
14  
15  import org.dom4j.IllegalAddException;
16  import org.dom4j.Node;
17  
18  /***
19   * <p>
20   * <code>ContentListFacade</code> represents a facade of the content of a
21   * {@link org.dom4j.Branch} which is returned via calls to the {@link
22   * org.dom4j.Branch#content}  method to allow users to modify the content of a
23   * {@link org.dom4j.Branch} directly using the {@link List} interface. This list
24   * is backed by the branch such that changes to the list will be reflected in
25   * the branch and changes to the branch will be reflected in this list.
26   * </p>
27   * 
28   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
29   * @version $Revision: 1.11 $
30   */
31  public class ContentListFacade extends AbstractList {
32      /*** The content of the Branch which is modified if I am modified */
33      private List branchContent;
34  
35      /*** The <code>AbstractBranch</code> instance which owns the content */
36      private AbstractBranch branch;
37  
38      public ContentListFacade(AbstractBranch branch, List branchContent) {
39          this.branch = branch;
40          this.branchContent = branchContent;
41      }
42  
43      public boolean add(Object object) {
44          branch.childAdded(asNode(object));
45  
46          return branchContent.add(object);
47      }
48  
49      public void add(int index, Object object) {
50          branch.childAdded(asNode(object));
51          branchContent.add(index, object);
52      }
53  
54      public Object set(int index, Object object) {
55          branch.childAdded(asNode(object));
56  
57          return branchContent.set(index, object);
58      }
59  
60      public boolean remove(Object object) {
61          branch.childRemoved(asNode(object));
62  
63          return branchContent.remove(object);
64      }
65  
66      public Object remove(int index) {
67          Object object = branchContent.remove(index);
68  
69          if (object != null) {
70              branch.childRemoved(asNode(object));
71          }
72  
73          return object;
74      }
75  
76      public boolean addAll(Collection collection) {
77          int count = branchContent.size();
78  
79          for (Iterator iter = collection.iterator(); iter.hasNext(); count++) {
80              add(iter.next());
81          }
82  
83          return count == branchContent.size();
84      }
85  
86      public boolean addAll(int index, Collection collection) {
87          int count = branchContent.size();
88  
89          for (Iterator iter = collection.iterator(); iter.hasNext(); count--) {
90              add(index++, iter.next());
91          }
92  
93          return count == branchContent.size();
94      }
95  
96      public void clear() {
97          for (Iterator iter = iterator(); iter.hasNext();) {
98              Object object = iter.next();
99              branch.childRemoved(asNode(object));
100         }
101 
102         branchContent.clear();
103     }
104 
105     public boolean removeAll(Collection c) {
106         for (Iterator iter = c.iterator(); iter.hasNext();) {
107             Object object = iter.next();
108             branch.childRemoved(asNode(object));
109         }
110 
111         return branchContent.removeAll(c);
112     }
113 
114     public int size() {
115         return branchContent.size();
116     }
117 
118     public boolean isEmpty() {
119         return branchContent.isEmpty();
120     }
121 
122     public boolean contains(Object o) {
123         return branchContent.contains(o);
124     }
125 
126     public Object[] toArray() {
127         return branchContent.toArray();
128     }
129 
130     public Object[] toArray(Object[] a) {
131         return branchContent.toArray(a);
132     }
133 
134     public boolean containsAll(Collection c) {
135         return branchContent.containsAll(c);
136     }
137 
138     public Object get(int index) {
139         return branchContent.get(index);
140     }
141 
142     public int indexOf(Object o) {
143         return branchContent.indexOf(o);
144     }
145 
146     public int lastIndexOf(Object o) {
147         return branchContent.lastIndexOf(o);
148     }
149 
150     protected Node asNode(Object object) {
151         if (object instanceof Node) {
152             return (Node) object;
153         } else {
154             throw new IllegalAddException(
155                     "This list must contain instances of "
156                             + "Node. Invalid type: " + object);
157         }
158     }
159 
160     protected List getBackingList() {
161         return branchContent;
162     }
163 }
164 
165 /*
166  * Redistribution and use of this software and associated documentation
167  * ("Software"), with or without modification, are permitted provided that the
168  * following conditions are met:
169  * 
170  * 1. Redistributions of source code must retain copyright statements and
171  * notices. Redistributions must also contain a copy of this document.
172  * 
173  * 2. Redistributions in binary form must reproduce the above copyright notice,
174  * this list of conditions and the following disclaimer in the documentation
175  * and/or other materials provided with the distribution.
176  * 
177  * 3. The name "DOM4J" must not be used to endorse or promote products derived
178  * from this Software without prior written permission of MetaStuff, Ltd. For
179  * written permission, please contact dom4j-info@metastuff.com.
180  * 
181  * 4. Products derived from this Software may not be called "DOM4J" nor may
182  * "DOM4J" appear in their names without prior written permission of MetaStuff,
183  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
184  * 
185  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
186  * 
187  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
188  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
189  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
190  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
191  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
192  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
193  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
194  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
195  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
196  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
197  * POSSIBILITY OF SUCH DAMAGE.
198  * 
199  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
200  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/ElementIterator.html0000644000175000017500000001751010242117711022514 0ustar ebourgebourg ElementIterator xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.util.Iterator;
11  
12  import org.dom4j.Element;
13  
14  /***
15   * <p>
16   * <code>ElementIterator</code> is a filtering {@link Iterator}which filters
17   * out objects which do not implement the {@link Element}interface.
18   * </p>
19   * 
20   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
21   * @version $Revision: 1.8 $
22   * 
23   * @deprecated THIS CLASS WILL BE REMOVED IN dom4j-1.6 !!
24   */
25  public class ElementIterator extends FilterIterator {
26      public ElementIterator(Iterator proxy) {
27          super(proxy);
28      }
29  
30      /***
31       * DOCUMENT ME!
32       * 
33       * @param element
34       *            DOCUMENT ME!
35       * 
36       * @return true if the given element implements the {@link Element}
37       *         interface
38       */
39      protected boolean matches(Object element) {
40          return element instanceof Element;
41      }
42  }
43  
44  /*
45   * Redistribution and use of this software and associated documentation
46   * ("Software"), with or without modification, are permitted provided that the
47   * following conditions are met:
48   * 
49   * 1. Redistributions of source code must retain copyright statements and
50   * notices. Redistributions must also contain a copy of this document.
51   * 
52   * 2. Redistributions in binary form must reproduce the above copyright notice,
53   * this list of conditions and the following disclaimer in the documentation
54   * and/or other materials provided with the distribution.
55   * 
56   * 3. The name "DOM4J" must not be used to endorse or promote products derived
57   * from this Software without prior written permission of MetaStuff, Ltd. For
58   * written permission, please contact dom4j-info@metastuff.com.
59   * 
60   * 4. Products derived from this Software may not be called "DOM4J" nor may
61   * "DOM4J" appear in their names without prior written permission of MetaStuff,
62   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
63   * 
64   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
65   * 
66   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
67   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
68   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
69   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
70   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
71   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
72   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
73   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
74   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
75   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
76   * POSSIBILITY OF SUCH DAMAGE.
77   * 
78   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
79   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/QNameCache.html0000644000175000017500000006137710242117706021354 0ustar ebourgebourg QNameCache xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.util.ArrayList;
11  import java.util.Collections;
12  import java.util.HashMap;
13  import java.util.Iterator;
14  import java.util.List;
15  import java.util.Map;
16  import java.util.WeakHashMap;
17  
18  import org.dom4j.DocumentFactory;
19  import org.dom4j.Namespace;
20  import org.dom4j.QName;
21  
22  /***
23   * <p>
24   * <code>QNameCache</code> caches instances of <code>QName</code> for reuse
25   * both across documents and within documents.
26   * </p>< < < < < < < QNameCache.java
27   * 
28   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
29   * @version $Revision: 1.16 $ =======
30   * 
31   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
32   * @version $Revision: 1.16 $ >>>>>>> 1.15
33   */
34  public class QNameCache {
35      /*** Cache of {@link QName}instances with no namespace */
36      protected Map noNamespaceCache = Collections
37              .synchronizedMap(new WeakHashMap());
38  
39      /***
40       * Cache of {@link Map}instances indexed by namespace which contain caches
41       * of {@link QName}for each name
42       */
43      protected Map namespaceCache = Collections
44              .synchronizedMap(new WeakHashMap());
45  
46      /***
47       * The document factory associated with new QNames instances in this cache
48       * or null if no instances should be associated by default
49       */
50      private DocumentFactory documentFactory;
51  
52      public QNameCache() {
53      }
54  
55      public QNameCache(DocumentFactory documentFactory) {
56          this.documentFactory = documentFactory;
57      }
58  
59      /***
60       * Returns a list of all the QName instances currently used
61       * 
62       * @return DOCUMENT ME!
63       */
64      public List getQNames() {
65          List answer = new ArrayList();
66          answer.addAll(noNamespaceCache.values());
67  
68          for (Iterator it = namespaceCache.values().iterator(); it.hasNext();) {
69              Map map = (Map) it.next();
70              answer.addAll(map.values());
71          }
72  
73          return answer;
74      }
75  
76      /***
77       * DOCUMENT ME!
78       * 
79       * @param name
80       *            DOCUMENT ME!
81       * 
82       * @return the QName for the given name and no namepsace
83       */
84      public QName get(String name) {
85          QName answer = null;
86  
87          if (name != null) {
88              answer = (QName) noNamespaceCache.get(name);
89          } else {
90              name = "";
91          }
92  
93          if (answer == null) {
94              answer = createQName(name);
95              answer.setDocumentFactory(documentFactory);
96              noNamespaceCache.put(name, answer);
97          }
98  
99          return answer;
100     }
101 
102     /***
103      * DOCUMENT ME!
104      * 
105      * @param name
106      *            DOCUMENT ME!
107      * @param namespace
108      *            DOCUMENT ME!
109      * 
110      * @return the QName for the given local name and namepsace
111      */
112     public QName get(String name, Namespace namespace) {
113         Map cache = getNamespaceCache(namespace);
114         QName answer = null;
115 
116         if (name != null) {
117             answer = (QName) cache.get(name);
118         } else {
119             name = "";
120         }
121 
122         if (answer == null) {
123             answer = createQName(name, namespace);
124             answer.setDocumentFactory(documentFactory);
125             cache.put(name, answer);
126         }
127 
128         return answer;
129     }
130 
131     /***
132      * DOCUMENT ME!
133      * 
134      * @param localName
135      *            DOCUMENT ME!
136      * @param namespace
137      *            DOCUMENT ME!
138      * @param qName
139      *            DOCUMENT ME!
140      * 
141      * @return the QName for the given local name, qualified name and namepsace
142      */
143     public QName get(String localName, Namespace namespace, String qName) {
144         Map cache = getNamespaceCache(namespace);
145         QName answer = null;
146 
147         if (localName != null) {
148             answer = (QName) cache.get(localName);
149         } else {
150             localName = "";
151         }
152 
153         if (answer == null) {
154             answer = createQName(localName, namespace, qName);
155             answer.setDocumentFactory(documentFactory);
156             cache.put(localName, answer);
157         }
158 
159         return answer;
160     }
161 
162     public QName get(String qualifiedName, String uri) {
163         int index = qualifiedName.indexOf(':');
164 
165         if (index < 0) {
166             return get(qualifiedName, Namespace.get(uri));
167         } else {
168             String name = qualifiedName.substring(index + 1);
169             String prefix = qualifiedName.substring(0, index);
170 
171             return get(name, Namespace.get(prefix, uri));
172         }
173     }
174 
175     /***
176      * DOCUMENT ME!
177      * 
178      * @param qname
179      *            DOCUMENT ME!
180      * 
181      * @return the cached QName instance if there is one or adds the given qname
182      *         to the cache if not
183      */
184     public QName intern(QName qname) {
185         return get(qname.getName(), qname.getNamespace(), qname
186                 .getQualifiedName());
187     }
188 
189     /***
190      * DOCUMENT ME!
191      * 
192      * @param namespace
193      *            DOCUMENT ME!
194      * 
195      * @return the cache for the given namespace. If one does not currently
196      *         exist it is created.
197      */
198     protected Map getNamespaceCache(Namespace namespace) {
199         if (namespace == Namespace.NO_NAMESPACE) {
200             return noNamespaceCache;
201         }
202 
203         Map answer = null;
204 
205         if (namespace != null) {
206             answer = (Map) namespaceCache.get(namespace);
207         }
208 
209         if (answer == null) {
210             answer = createMap();
211             namespaceCache.put(namespace, answer);
212         }
213 
214         return answer;
215     }
216 
217     /***
218      * A factory method
219      * 
220      * @return a newly created {@link Map}instance.
221      */
222     protected Map createMap() {
223         return Collections.synchronizedMap(new HashMap());
224     }
225 
226     /***
227      * Factory method to create a new QName object which can be overloaded to
228      * create derived QName instances
229      * 
230      * @param name
231      *            DOCUMENT ME!
232      * 
233      * @return DOCUMENT ME!
234      */
235     protected QName createQName(String name) {
236         return new QName(name);
237     }
238 
239     /***
240      * Factory method to create a new QName object which can be overloaded to
241      * create derived QName instances
242      * 
243      * @param name
244      *            DOCUMENT ME!
245      * @param namespace
246      *            DOCUMENT ME!
247      * 
248      * @return DOCUMENT ME!
249      */
250     protected QName createQName(String name, Namespace namespace) {
251         return new QName(name, namespace);
252     }
253 
254     /***
255      * Factory method to create a new QName object which can be overloaded to
256      * create derived QName instances
257      * 
258      * @param name
259      *            DOCUMENT ME!
260      * @param namespace
261      *            DOCUMENT ME!
262      * @param qualifiedName
263      *            DOCUMENT ME!
264      * 
265      * @return DOCUMENT ME!
266      */
267     protected QName createQName(String name, Namespace namespace,
268             String qualifiedName) {
269         return new QName(name, namespace, qualifiedName);
270     }
271 }
272 
273 
274 
275 /*
276  * Redistribution and use of this software and associated documentation
277  * ("Software"), with or without modification, are permitted provided that the
278  * following conditions are met:
279  * 
280  * 1. Redistributions of source code must retain copyright statements and
281  * notices. Redistributions must also contain a copy of this document.
282  * 
283  * 2. Redistributions in binary form must reproduce the above copyright notice,
284  * this list of conditions and the following disclaimer in the documentation
285  * and/or other materials provided with the distribution.
286  * 
287  * 3. The name "DOM4J" must not be used to endorse or promote products derived
288  * from this Software without prior written permission of MetaStuff, Ltd. For
289  * written permission, please contact dom4j-info@metastuff.com.
290  * 
291  * 4. Products derived from this Software may not be called "DOM4J" nor may
292  * "DOM4J" appear in their names without prior written permission of MetaStuff,
293  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
294  * 
295  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
296  * 
297  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
298  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
299  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
300  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
301  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
302  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
303  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
304  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
305  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
306  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
307  * POSSIBILITY OF SUCH DAMAGE.
308  * 
309  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
310  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/AbstractElement.html0000644000175000017500000040356510242117757022511 0ustar ebourgebourg AbstractElement xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.io.IOException;
11  import java.io.StringWriter;
12  import java.io.Writer;
13  import java.util.ArrayList;
14  import java.util.Collections;
15  import java.util.Iterator;
16  import java.util.List;
17  import java.util.Map;
18  
19  import org.dom4j.Attribute;
20  import org.dom4j.CDATA;
21  import org.dom4j.CharacterData;
22  import org.dom4j.Comment;
23  import org.dom4j.Document;
24  import org.dom4j.DocumentFactory;
25  import org.dom4j.Element;
26  import org.dom4j.Entity;
27  import org.dom4j.IllegalAddException;
28  import org.dom4j.Namespace;
29  import org.dom4j.Node;
30  import org.dom4j.ProcessingInstruction;
31  import org.dom4j.QName;
32  import org.dom4j.Text;
33  import org.dom4j.Visitor;
34  import org.dom4j.io.OutputFormat;
35  import org.dom4j.io.XMLWriter;
36  
37  import org.xml.sax.Attributes;
38  
39  /***
40   * <p>
41   * <code>AbstractElement</code> is an abstract base class for tree
42   * implementors to use for implementation inheritence.
43   * </p>
44   * 
45   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
46   * @version $Revision: 1.80 $
47   */
48  public abstract class AbstractElement extends AbstractBranch implements
49          org.dom4j.Element {
50      /*** The <code>DocumentFactory</code> instance used by default */
51      private static final DocumentFactory DOCUMENT_FACTORY = DocumentFactory
52              .getInstance();
53  
54      protected static final List EMPTY_LIST = Collections.EMPTY_LIST;
55  
56      protected static final Iterator EMPTY_ITERATOR = EMPTY_LIST.iterator();
57  
58      protected static final boolean VERBOSE_TOSTRING = false;
59  
60      protected static final boolean USE_STRINGVALUE_SEPARATOR = false;
61  
62      public AbstractElement() {
63      }
64  
65      public short getNodeType() {
66          return ELEMENT_NODE;
67      }
68  
69      public boolean isRootElement() {
70          Document document = getDocument();
71  
72          if (document != null) {
73              Element root = document.getRootElement();
74  
75              if (root == this) {
76                  return true;
77              }
78          }
79  
80          return false;
81      }
82  
83      public void setName(String name) {
84          setQName(getDocumentFactory().createQName(name));
85      }
86  
87      public void setNamespace(Namespace namespace) {
88          setQName(getDocumentFactory().createQName(getName(), namespace));
89      }
90  
91      /***
92       * Returns the XPath expression to match this Elements name which is
93       * getQualifiedName() if there is a namespace prefix defined or if no
94       * namespace is present then it is getName() or if a namespace is defined
95       * with no prefix then the expression is [name()='X'] where X = getName().
96       * 
97       * @return DOCUMENT ME!
98       */
99      public String getXPathNameStep() {
100         String uri = getNamespaceURI();
101 
102         if ((uri == null) || (uri.length() == 0)) {
103             return getName();
104         }
105 
106         String prefix = getNamespacePrefix();
107 
108         if ((prefix == null) || (prefix.length() == 0)) {
109             return "*[name()='" + getName() + "']";
110         }
111 
112         return getQualifiedName();
113     }
114 
115     public String getPath(Element context) {
116         if (this == context) {
117             return ".";
118         }
119 
120         Element parent = getParent();
121 
122         if (parent == null) {
123             return "/" + getXPathNameStep();
124         } else if (parent == context) {
125             return getXPathNameStep();
126         }
127 
128         return parent.getPath(context) + "/" + getXPathNameStep();
129     }
130 
131     public String getUniquePath(Element context) {
132         Element parent = getParent();
133 
134         if (parent == null) {
135             return "/" + getXPathNameStep();
136         }
137 
138         StringBuffer buffer = new StringBuffer();
139 
140         if (parent != context) {
141             buffer.append(parent.getUniquePath(context));
142 
143             buffer.append("/");
144         }
145 
146         buffer.append(getXPathNameStep());
147 
148         List mySiblings = parent.elements(getQName());
149 
150         if (mySiblings.size() > 1) {
151             int idx = mySiblings.indexOf(this);
152 
153             if (idx >= 0) {
154                 buffer.append("[");
155 
156                 buffer.append(Integer.toString(++idx));
157 
158                 buffer.append("]");
159             }
160         }
161 
162         return buffer.toString();
163     }
164 
165     public String asXML() {
166         try {
167             StringWriter out = new StringWriter();
168             XMLWriter writer = new XMLWriter(out, new OutputFormat());
169 
170             writer.write(this);
171             writer.flush();
172 
173             return out.toString();
174         } catch (IOException e) {
175             throw new RuntimeException("IOException while generating "
176                     + "textual representation: " + e.getMessage());
177         }
178     }
179 
180     public void write(Writer out) throws IOException {
181         XMLWriter writer = new XMLWriter(out, new OutputFormat());
182         writer.write(this);
183     }
184 
185     /***
186      * <p>
187      * <code>accept</code> method is the <code>Visitor Pattern</code>
188      * method.
189      * </p>
190      * 
191      * @param visitor
192      *            <code>Visitor</code> is the visitor.
193      */
194     public void accept(Visitor visitor) {
195         visitor.visit(this);
196 
197         // visit attributes
198         for (int i = 0, size = attributeCount(); i < size; i++) {
199             Attribute attribute = attribute(i);
200 
201             visitor.visit(attribute);
202         }
203 
204         // visit content
205         for (int i = 0, size = nodeCount(); i < size; i++) {
206             Node node = node(i);
207 
208             node.accept(visitor);
209         }
210     }
211 
212     public String toString() {
213         String uri = getNamespaceURI();
214 
215         if ((uri != null) && (uri.length() > 0)) {
216             if (VERBOSE_TOSTRING) {
217                 return super.toString() + " [Element: <" + getQualifiedName()
218                         + " uri: " + uri + " attributes: " + attributeList()
219                         + " content: " + contentList() + " />]";
220             } else {
221                 return super.toString() + " [Element: <" + getQualifiedName()
222                         + " uri: " + uri + " attributes: " + attributeList()
223                         + "/>]";
224             }
225         } else {
226             if (VERBOSE_TOSTRING) {
227                 return super.toString() + " [Element: <" + getQualifiedName()
228                         + " attributes: " + attributeList() + " content: "
229                         + contentList() + " />]";
230             } else {
231                 return super.toString() + " [Element: <" + getQualifiedName()
232                         + " attributes: " + attributeList() + "/>]";
233             }
234         }
235     }
236 
237     // QName methods
238     // -------------------------------------------------------------------------
239     public Namespace getNamespace() {
240         return getQName().getNamespace();
241     }
242 
243     public String getName() {
244         return getQName().getName();
245     }
246 
247     public String getNamespacePrefix() {
248         return getQName().getNamespacePrefix();
249     }
250 
251     public String getNamespaceURI() {
252         return getQName().getNamespaceURI();
253     }
254 
255     public String getQualifiedName() {
256         return getQName().getQualifiedName();
257     }
258 
259     public Object getData() {
260         return getText();
261     }
262 
263     public void setData(Object data) {
264         // ignore this method
265     }
266 
267     // Node methods
268     // -------------------------------------------------------------------------
269     public Node node(int index) {
270         if (index >= 0) {
271             List list = contentList();
272 
273             if (index >= list.size()) {
274                 return null;
275             }
276 
277             Object node = list.get(index);
278 
279             if (node != null) {
280                 if (node instanceof Node) {
281                     return (Node) node;
282                 } else {
283                     return getDocumentFactory().createText(node.toString());
284                 }
285             }
286         }
287 
288         return null;
289     }
290 
291     public int indexOf(Node node) {
292         return contentList().indexOf(node);
293     }
294 
295     public int nodeCount() {
296         return contentList().size();
297     }
298 
299     public Iterator nodeIterator() {
300         return contentList().iterator();
301     }
302 
303     // Element methods
304     // -------------------------------------------------------------------------
305     public Element element(String name) {
306         List list = contentList();
307 
308         int size = list.size();
309 
310         for (int i = 0; i < size; i++) {
311             Object object = list.get(i);
312 
313             if (object instanceof Element) {
314                 Element element = (Element) object;
315 
316                 if (name.equals(element.getName())) {
317                     return element;
318                 }
319             }
320         }
321 
322         return null;
323     }
324 
325     public Element element(QName qName) {
326         List list = contentList();
327 
328         int size = list.size();
329 
330         for (int i = 0; i < size; i++) {
331             Object object = list.get(i);
332 
333             if (object instanceof Element) {
334                 Element element = (Element) object;
335 
336                 if (qName.equals(element.getQName())) {
337                     return element;
338                 }
339             }
340         }
341 
342         return null;
343     }
344 
345     public Element element(String name, Namespace namespace) {
346         return element(getDocumentFactory().createQName(name, namespace));
347     }
348 
349     public List elements() {
350         List list = contentList();
351 
352         BackedList answer = createResultList();
353 
354         int size = list.size();
355 
356         for (int i = 0; i < size; i++) {
357             Object object = list.get(i);
358 
359             if (object instanceof Element) {
360                 answer.addLocal(object);
361             }
362         }
363 
364         return answer;
365     }
366 
367     public List elements(String name) {
368         List list = contentList();
369 
370         BackedList answer = createResultList();
371 
372         int size = list.size();
373 
374         for (int i = 0; i < size; i++) {
375             Object object = list.get(i);
376 
377             if (object instanceof Element) {
378                 Element element = (Element) object;
379 
380                 if (name.equals(element.getName())) {
381                     answer.addLocal(element);
382                 }
383             }
384         }
385 
386         return answer;
387     }
388 
389     public List elements(QName qName) {
390         List list = contentList();
391 
392         BackedList answer = createResultList();
393 
394         int size = list.size();
395 
396         for (int i = 0; i < size; i++) {
397             Object object = list.get(i);
398 
399             if (object instanceof Element) {
400                 Element element = (Element) object;
401 
402                 if (qName.equals(element.getQName())) {
403                     answer.addLocal(element);
404                 }
405             }
406         }
407 
408         return answer;
409     }
410 
411     public List elements(String name, Namespace namespace) {
412         return elements(getDocumentFactory().createQName(name, namespace));
413     }
414 
415     public Iterator elementIterator() {
416         List list = elements();
417 
418         return list.iterator();
419     }
420 
421     public Iterator elementIterator(String name) {
422         List list = elements(name);
423 
424         return list.iterator();
425     }
426 
427     public Iterator elementIterator(QName qName) {
428         List list = elements(qName);
429 
430         return list.iterator();
431     }
432 
433     public Iterator elementIterator(String name, Namespace ns) {
434         return elementIterator(getDocumentFactory().createQName(name, ns));
435     }
436 
437     // Attribute methods
438     // -------------------------------------------------------------------------
439     public List attributes() {
440         return new ContentListFacade(this, attributeList());
441     }
442 
443     public Iterator attributeIterator() {
444         return attributeList().iterator();
445     }
446 
447     public Attribute attribute(int index) {
448         return (Attribute) attributeList().get(index);
449     }
450 
451     public int attributeCount() {
452         return attributeList().size();
453     }
454 
455     public Attribute attribute(String name) {
456         List list = attributeList();
457 
458         int size = list.size();
459 
460         for (int i = 0; i < size; i++) {
461             Attribute attribute = (Attribute) list.get(i);
462 
463             if (name.equals(attribute.getName())) {
464                 return attribute;
465             }
466         }
467 
468         return null;
469     }
470 
471     public Attribute attribute(QName qName) {
472         List list = attributeList();
473 
474         int size = list.size();
475 
476         for (int i = 0; i < size; i++) {
477             Attribute attribute = (Attribute) list.get(i);
478 
479             if (qName.equals(attribute.getQName())) {
480                 return attribute;
481             }
482         }
483 
484         return null;
485     }
486 
487     public Attribute attribute(String name, Namespace namespace) {
488         return attribute(getDocumentFactory().createQName(name, namespace));
489     }
490 
491     /***
492      * This method provides a more optimal way of setting all the attributes on
493      * an Element particularly for use in {@link org.dom4j.io.SAXReader}.
494      * 
495      * @param attributes
496      *            DOCUMENT ME!
497      * @param namespaceStack
498      *            DOCUMENT ME!
499      * @param noNamespaceAttributes
500      *            DOCUMENT ME!
501      */
502     public void setAttributes(Attributes attributes,
503             NamespaceStack namespaceStack, boolean noNamespaceAttributes) {
504         // now lets add all attribute values
505         int size = attributes.getLength();
506 
507         if (size > 0) {
508             DocumentFactory factory = getDocumentFactory();
509 
510             if (size == 1) {
511                 // allow lazy construction of the List of Attributes
512                 String name = attributes.getQName(0);
513 
514                 if (noNamespaceAttributes || !name.startsWith("xmlns")) {
515                     String attributeURI = attributes.getURI(0);
516 
517                     String attributeLocalName = attributes.getLocalName(0);
518 
519                     String attributeValue = attributes.getValue(0);
520 
521                     QName attributeQName = namespaceStack.getAttributeQName(
522                             attributeURI, attributeLocalName, name);
523 
524                     add(factory.createAttribute(this, attributeQName,
525                             attributeValue));
526                 }
527             } else {
528                 List list = attributeList(size);
529 
530                 list.clear();
531 
532                 for (int i = 0; i < size; i++) {
533                     // optimised to avoid the call to attribute(QName) to
534                     // lookup an attribute for a given QName
535                     String attributeName = attributes.getQName(i);
536 
537                     if (noNamespaceAttributes
538                             || !attributeName.startsWith("xmlns")) {
539                         String attributeURI = attributes.getURI(i);
540 
541                         String attributeLocalName = attributes.getLocalName(i);
542 
543                         String attributeValue = attributes.getValue(i);
544 
545                         QName attributeQName = namespaceStack
546                                 .getAttributeQName(attributeURI,
547                                         attributeLocalName, attributeName);
548 
549                         Attribute attribute = factory.createAttribute(this,
550                                 attributeQName, attributeValue);
551 
552                         list.add(attribute);
553 
554                         childAdded(attribute);
555                     }
556                 }
557             }
558         }
559     }
560 
561     public String attributeValue(String name) {
562         Attribute attrib = attribute(name);
563 
564         if (attrib == null) {
565             return null;
566         } else {
567             return attrib.getValue();
568         }
569     }
570 
571     public String attributeValue(QName qName) {
572         Attribute attrib = attribute(qName);
573 
574         if (attrib == null) {
575             return null;
576         } else {
577             return attrib.getValue();
578         }
579     }
580 
581     public String attributeValue(String name, String defaultValue) {
582         String answer = attributeValue(name);
583 
584         return (answer != null) ? answer : defaultValue;
585     }
586 
587     public String attributeValue(QName qName, String defaultValue) {
588         String answer = attributeValue(qName);
589 
590         return (answer != null) ? answer : defaultValue;
591     }
592 
593     /***
594      * DOCUMENT ME!
595      * 
596      * @param name
597      *            DOCUMENT ME!
598      * @param value
599      *            DOCUMENT ME!
600      * 
601      * @deprecated As of version 0.5. Please use {@link
602      *             #addAttribute(String,String)} instead. WILL BE REMOVED IN
603      *             dom4j-1.6 !!
604      */
605     public void setAttributeValue(String name, String value) {
606         addAttribute(name, value);
607     }
608 
609     /***
610      * DOCUMENT ME!
611      * 
612      * @param qName
613      *            DOCUMENT ME!
614      * @param value
615      *            DOCUMENT ME!
616      * 
617      * @deprecated As of version 0.5. Please use {@link
618      *             #addAttribute(String,String)} instead. WILL BE REMOVED IN
619      *             dom4j-1.6 !!
620      */
621     public void setAttributeValue(QName qName, String value) {
622         addAttribute(qName, value);
623     }
624 
625     public void add(Attribute attribute) {
626         if (attribute.getParent() != null) {
627             String message = "The Attribute already has an existing parent \""
628                     + attribute.getParent().getQualifiedName() + "\"";
629 
630             throw new IllegalAddException(this, attribute, message);
631         }
632 
633         if (attribute.getValue() == null) {
634             // try remove a previous attribute with the same
635             // name since adding an attribute with a null value
636             // is equivalent to removing it.
637             Attribute oldAttribute = attribute(attribute.getQName());
638 
639             if (oldAttribute != null) {
640                 remove(oldAttribute);
641             }
642         } else {
643             attributeList().add(attribute);
644 
645             childAdded(attribute);
646         }
647     }
648 
649     public boolean remove(Attribute attribute) {
650         List list = attributeList();
651 
652         boolean answer = list.remove(attribute);
653 
654         if (answer) {
655             childRemoved(attribute);
656         } else {
657             // we may have a copy of the attribute
658             Attribute copy = attribute(attribute.getQName());
659 
660             if (copy != null) {
661                 list.remove(copy);
662 
663                 answer = true;
664             }
665         }
666 
667         return answer;
668     }
669 
670     // Processing instruction API
671     // -------------------------------------------------------------------------
672     public List processingInstructions() {
673         List list = contentList();
674 
675         BackedList answer = createResultList();
676 
677         int size = list.size();
678 
679         for (int i = 0; i < size; i++) {
680             Object object = list.get(i);
681 
682             if (object instanceof ProcessingInstruction) {
683                 answer.addLocal(object);
684             }
685         }
686 
687         return answer;
688     }
689 
690     public List processingInstructions(String target) {
691         List list = contentList();
692 
693         BackedList answer = createResultList();
694 
695         int size = list.size();
696 
697         for (int i = 0; i < size; i++) {
698             Object object = list.get(i);
699 
700             if (object instanceof ProcessingInstruction) {
701                 ProcessingInstruction pi = (ProcessingInstruction) object;
702 
703                 if (target.equals(pi.getName())) {
704                     answer.addLocal(pi);
705                 }
706             }
707         }
708 
709         return answer;
710     }
711 
712     public ProcessingInstruction processingInstruction(String target) {
713         List list = contentList();
714 
715         int size = list.size();
716 
717         for (int i = 0; i < size; i++) {
718             Object object = list.get(i);
719 
720             if (object instanceof ProcessingInstruction) {
721                 ProcessingInstruction pi = (ProcessingInstruction) object;
722 
723                 if (target.equals(pi.getName())) {
724                     return pi;
725                 }
726             }
727         }
728 
729         return null;
730     }
731 
732     public boolean removeProcessingInstruction(String target) {
733         List list = contentList();
734 
735         for (Iterator iter = list.iterator(); iter.hasNext();) {
736             Object object = iter.next();
737 
738             if (object instanceof ProcessingInstruction) {
739                 ProcessingInstruction pi = (ProcessingInstruction) object;
740 
741                 if (target.equals(pi.getName())) {
742                     iter.remove();
743 
744                     return true;
745                 }
746             }
747         }
748 
749         return false;
750     }
751 
752     // Content Model methods
753     // -------------------------------------------------------------------------
754     public Node getXPathResult(int index) {
755         Node answer = node(index);
756 
757         if ((answer != null) && !answer.supportsParent()) {
758             return answer.asXPathResult(this);
759         }
760 
761         return answer;
762     }
763 
764     public Element addAttribute(String name, String value) {
765         // adding a null value is equivalent to removing the attribute
766         Attribute attribute = attribute(name);
767 
768         if (value != null) {
769             if (attribute == null) {
770                 add(getDocumentFactory().createAttribute(this, name, value));
771             } else if (attribute.isReadOnly()) {
772                 remove(attribute);
773 
774                 add(getDocumentFactory().createAttribute(this, name, value));
775             } else {
776                 attribute.setValue(value);
777             }
778         } else if (attribute != null) {
779             remove(attribute);
780         }
781 
782         return this;
783     }
784 
785     public Element addAttribute(QName qName, String value) {
786         // adding a null value is equivalent to removing the attribute
787         Attribute attribute = attribute(qName);
788 
789         if (value != null) {
790             if (attribute == null) {
791                 add(getDocumentFactory().createAttribute(this, qName, value));
792             } else if (attribute.isReadOnly()) {
793                 remove(attribute);
794 
795                 add(getDocumentFactory().createAttribute(this, qName, value));
796             } else {
797                 attribute.setValue(value);
798             }
799         } else if (attribute != null) {
800             remove(attribute);
801         }
802 
803         return this;
804     }
805 
806     public Element addCDATA(String cdata) {
807         CDATA node = getDocumentFactory().createCDATA(cdata);
808 
809         addNewNode(node);
810 
811         return this;
812     }
813 
814     public Element addComment(String comment) {
815         Comment node = getDocumentFactory().createComment(comment);
816 
817         addNewNode(node);
818 
819         return this;
820     }
821 
822     public Element addElement(String name) {
823         DocumentFactory factory = getDocumentFactory();
824 
825         int index = name.indexOf(":");
826 
827         String prefix = "";
828 
829         String localName = name;
830 
831         Namespace namespace = null;
832 
833         if (index > 0) {
834             prefix = name.substring(0, index);
835 
836             localName = name.substring(index + 1);
837 
838             namespace = getNamespaceForPrefix(prefix);
839 
840             if (namespace == null) {
841                 throw new IllegalAddException("No such namespace prefix: "
842                         + prefix + " is in scope on: " + this
843                         + " so cannot add element: " + name);
844             }
845         } else {
846             namespace = getNamespaceForPrefix("");
847         }
848 
849         Element node;
850 
851         if (namespace != null) {
852             QName qname = factory.createQName(localName, namespace);
853 
854             node = factory.createElement(qname);
855         } else {
856             node = factory.createElement(name);
857         }
858 
859         addNewNode(node);
860 
861         return node;
862     }
863 
864     public Element addEntity(String name, String text) {
865         Entity node = getDocumentFactory().createEntity(name, text);
866 
867         addNewNode(node);
868 
869         return this;
870     }
871 
872     public Element addNamespace(String prefix, String uri) {
873         Namespace node = getDocumentFactory().createNamespace(prefix, uri);
874 
875         addNewNode(node);
876 
877         return this;
878     }
879 
880     public Element addProcessingInstruction(String target, String data) {
881         ProcessingInstruction node = getDocumentFactory()
882                 .createProcessingInstruction(target, data);
883 
884         addNewNode(node);
885 
886         return this;
887     }
888 
889     public Element addProcessingInstruction(String target, Map data) {
890         ProcessingInstruction node = getDocumentFactory()
891                 .createProcessingInstruction(target, data);
892 
893         addNewNode(node);
894 
895         return this;
896     }
897 
898     public Element addText(String text) {
899         Text node = getDocumentFactory().createText(text);
900 
901         addNewNode(node);
902 
903         return this;
904     }
905 
906     // polymorphic node methods
907     public void add(Node node) {
908         switch (node.getNodeType()) {
909             case ELEMENT_NODE:
910                 add((Element) node);
911 
912                 break;
913 
914             case ATTRIBUTE_NODE:
915                 add((Attribute) node);
916 
917                 break;
918 
919             case TEXT_NODE:
920                 add((Text) node);
921 
922                 break;
923 
924             case CDATA_SECTION_NODE:
925                 add((CDATA) node);
926 
927                 break;
928 
929             case ENTITY_REFERENCE_NODE:
930                 add((Entity) node);
931 
932                 break;
933 
934             case PROCESSING_INSTRUCTION_NODE:
935                 add((ProcessingInstruction) node);
936 
937                 break;
938 
939             case COMMENT_NODE:
940                 add((Comment) node);
941 
942                 break;
943 
944             /*
945              * XXXX: to do! case DOCUMENT_TYPE_NODE: add((DocumentType) node);
946              * break;
947              */
948             case NAMESPACE_NODE:
949                 add((Namespace) node);
950 
951                 break;
952 
953             default:
954                 invalidNodeTypeAddException(node);
955         }
956     }
957 
958     public boolean remove(Node node) {
959         switch (node.getNodeType()) {
960             case ELEMENT_NODE:
961                 return remove((Element) node);
962 
963             case ATTRIBUTE_NODE:
964                 return remove((Attribute) node);
965 
966             case TEXT_NODE:
967                 return remove((Text) node);
968 
969             case CDATA_SECTION_NODE:
970                 return remove((CDATA) node);
971 
972             case ENTITY_REFERENCE_NODE:
973                 return remove((Entity) node);
974 
975             case PROCESSING_INSTRUCTION_NODE:
976                 return remove((ProcessingInstruction) node);
977 
978             case COMMENT_NODE:
979                 return remove((Comment) node);
980 
981             /*
982              * case DOCUMENT_TYPE_NODE: return remove((DocumentType) node);
983              */
984             case NAMESPACE_NODE:
985                 return remove((Namespace) node);
986 
987             default:
988                 return false;
989         }
990     }
991 
992     // typesafe versions using node classes
993     public void add(CDATA cdata) {
994         addNode(cdata);
995     }
996 
997     public void add(Comment comment) {
998         addNode(comment);
999     }
1000 
1001     public void add(Element element) {
1002         addNode(element);
1003     }
1004 
1005     public void add(Entity entity) {
1006         addNode(entity);
1007     }
1008 
1009     public void add(Namespace namespace) {
1010         addNode(namespace);
1011     }
1012 
1013     public void add(ProcessingInstruction pi) {
1014         addNode(pi);
1015     }
1016 
1017     public void add(Text text) {
1018         addNode(text);
1019     }
1020 
1021     public boolean remove(CDATA cdata) {
1022         return removeNode(cdata);
1023     }
1024 
1025     public boolean remove(Comment comment) {
1026         return removeNode(comment);
1027     }
1028 
1029     public boolean remove(Element element) {
1030         return removeNode(element);
1031     }
1032 
1033     public boolean remove(Entity entity) {
1034         return removeNode(entity);
1035     }
1036 
1037     public boolean remove(Namespace namespace) {
1038         return removeNode(namespace);
1039     }
1040 
1041     public boolean remove(ProcessingInstruction pi) {
1042         return removeNode(pi);
1043     }
1044 
1045     public boolean remove(Text text) {
1046         return removeNode(text);
1047     }
1048 
1049     // Helper methods
1050     // -------------------------------------------------------------------------
1051     public boolean hasMixedContent() {
1052         List content = contentList();
1053 
1054         if ((content == null) || content.isEmpty() || (content.size() < 2)) {
1055             return false;
1056         }
1057 
1058         Class prevClass = null;
1059 
1060         for (Iterator iter = content.iterator(); iter.hasNext();) {
1061             Object object = iter.next();
1062 
1063             Class newClass = object.getClass();
1064 
1065             if (newClass != prevClass) {
1066                 if (prevClass != null) {
1067                     return true;
1068                 }
1069 
1070                 prevClass = newClass;
1071             }
1072         }
1073 
1074         return false;
1075     }
1076 
1077     public boolean isTextOnly() {
1078         List content = contentList();
1079 
1080         if ((content == null) || content.isEmpty()) {
1081             return true;
1082         }
1083 
1084         for (Iterator iter = content.iterator(); iter.hasNext();) {
1085             Object object = iter.next();
1086 
1087             if (!(object instanceof CharacterData)
1088                     && !(object instanceof String)) {
1089                 return false;
1090             }
1091         }
1092 
1093         return true;
1094     }
1095 
1096     public void setText(String text) {
1097         /* remove all text nodes */
1098         List allContent = contentList();
1099 
1100         if (allContent != null) {
1101             Iterator it = allContent.iterator();
1102 
1103             while (it.hasNext()) {
1104                 Node node = (Node) it.next();
1105 
1106                 switch (node.getNodeType()) {
1107                     case CDATA_SECTION_NODE:
1108 
1109                     // case ENTITY_NODE:
1110                     case ENTITY_REFERENCE_NODE:
1111                     case TEXT_NODE:
1112                         it.remove();
1113 
1114                     default:
1115                         break;
1116                 }
1117             }
1118         }
1119 
1120         addText(text);
1121     }
1122 
1123     public String getStringValue() {
1124         List list = contentList();
1125 
1126         int size = list.size();
1127 
1128         if (size > 0) {
1129             if (size == 1) {
1130                 // optimised to avoid StringBuffer creation
1131                 return getContentAsStringValue(list.get(0));
1132             } else {
1133                 StringBuffer buffer = new StringBuffer();
1134 
1135                 for (int i = 0; i < size; i++) {
1136                     Object node = list.get(i);
1137 
1138                     String string = getContentAsStringValue(node);
1139 
1140                     if (string.length() > 0) {
1141                         if (USE_STRINGVALUE_SEPARATOR) {
1142                             if (buffer.length() > 0) {
1143                                 buffer.append(' ');
1144                             }
1145                         }
1146 
1147                         buffer.append(string);
1148                     }
1149                 }
1150 
1151                 return buffer.toString();
1152             }
1153         }
1154 
1155         return "";
1156     }
1157 
1158     /***
1159      * Puts all <code>Text</code> nodes in the full depth of the sub-tree
1160      * underneath this <code>Node</code>, including attribute nodes, into a
1161      * "normal" form where only structure (e.g., elements, comments, processing
1162      * instructions, CDATA sections, and entity references) separates
1163      * <code>Text</code> nodes, i.e., there are neither adjacent
1164      * <code>Text</code> nodes nor empty <code>Text</code> nodes. This can
1165      * be used to ensure that the DOM view of a document is the same as if it
1166      * were saved and re-loaded, and is useful when operations (such as XPointer
1167      * lookups) that depend on a particular document tree structure are to be
1168      * used.In cases where the document contains <code>CDATASections</code>,
1169      * the normalize operation alone may not be sufficient, since XPointers do
1170      * not differentiate between <code>Text</code> nodes and
1171      * <code>CDATASection</code> nodes.
1172      * 
1173      * @since DOM Level 2
1174      */
1175     public void normalize() {
1176         List content = contentList();
1177 
1178         Text previousText = null;
1179 
1180         int i = 0;
1181 
1182         while (i < content.size()) {
1183             Node node = (Node) content.get(i);
1184 
1185             if (node instanceof Text) {
1186                 Text text = (Text) node;
1187 
1188                 if (previousText != null) {
1189                     previousText.appendText(text.getText());
1190 
1191                     remove(text);
1192                 } else {
1193                     String value = text.getText();
1194 
1195                     // only remove empty Text nodes, not whitespace nodes
1196                     // if ( value == null || value.trim().length() <= 0 ) {
1197                     if ((value == null) || (value.length() <= 0)) {
1198                         remove(text);
1199                     } else {
1200                         previousText = text;
1201 
1202                         i++;
1203                     }
1204                 }
1205             } else {
1206                 if (node instanceof Element) {
1207                     Element element = (Element) node;
1208 
1209                     element.normalize();
1210                 }
1211 
1212                 previousText = null;
1213 
1214                 i++;
1215             }
1216         }
1217     }
1218 
1219     public String elementText(String name) {
1220         Element element = element(name);
1221 
1222         return (element != null) ? element.getText() : null;
1223     }
1224 
1225     public String elementText(QName qName) {
1226         Element element = element(qName);
1227 
1228         return (element != null) ? element.getText() : null;
1229     }
1230 
1231     public String elementTextTrim(String name) {
1232         Element element = element(name);
1233 
1234         return (element != null) ? element.getTextTrim() : null;
1235     }
1236 
1237     public String elementTextTrim(QName qName) {
1238         Element element = element(qName);
1239 
1240         return (element != null) ? element.getTextTrim() : null;
1241     }
1242 
1243     // add to me content from another element
1244     // analagous to the addAll(collection) methods in Java 2 collections
1245     public void appendAttributes(Element element) {
1246         for (int i = 0, size = element.attributeCount(); i < size; i++) {
1247             Attribute attribute = element.attribute(i);
1248 
1249             if (attribute.supportsParent()) {
1250                 addAttribute(attribute.getQName(), attribute.getValue());
1251             } else {
1252                 add(attribute);
1253             }
1254         }
1255     }
1256 
1257     /***
1258      * <p>
1259      * This returns a deep clone of this element. The new element is detached
1260      * from its parent, and getParent() on the clone will return null.
1261      * </p>
1262      * 
1263      * @return the clone of this element
1264      */
1265 
1266     /*
1267      * public Object clone() { Element clone = createElement(getQName());
1268      * clone.appendAttributes(this); clone.appendContent(this); return clone; }
1269      */
1270     public Element createCopy() {
1271         Element clone = createElement(getQName());
1272 
1273         clone.appendAttributes(this);
1274 
1275         clone.appendContent(this);
1276 
1277         return clone;
1278     }
1279 
1280     public Element createCopy(String name) {
1281         Element clone = createElement(name);
1282 
1283         clone.appendAttributes(this);
1284 
1285         clone.appendContent(this);
1286 
1287         return clone;
1288     }
1289 
1290     public Element createCopy(QName qName) {
1291         Element clone = createElement(qName);
1292 
1293         clone.appendAttributes(this);
1294 
1295         clone.appendContent(this);
1296 
1297         return clone;
1298     }
1299 
1300     public QName getQName(String qualifiedName) {
1301         String prefix = "";
1302 
1303         String localName = qualifiedName;
1304 
1305         int index = qualifiedName.indexOf(":");
1306 
1307         if (index > 0) {
1308             prefix = qualifiedName.substring(0, index);
1309 
1310             localName = qualifiedName.substring(index + 1);
1311         }
1312 
1313         Namespace namespace = getNamespaceForPrefix(prefix);
1314 
1315         if (namespace != null) {
1316             return getDocumentFactory().createQName(localName, namespace);
1317         } else {
1318             return getDocumentFactory().createQName(localName);
1319         }
1320     }
1321 
1322     public Namespace getNamespaceForPrefix(String prefix) {
1323         if (prefix == null) {
1324             prefix = "";
1325         }
1326 
1327         if (prefix.equals(getNamespacePrefix())) {
1328             return getNamespace();
1329         } else if (prefix.equals("xml")) {
1330             return Namespace.XML_NAMESPACE;
1331         } else {
1332             List list = contentList();
1333 
1334             int size = list.size();
1335 
1336             for (int i = 0; i < size; i++) {
1337                 Object object = list.get(i);
1338 
1339                 if (object instanceof Namespace) {
1340                     Namespace namespace = (Namespace) object;
1341 
1342                     if (prefix.equals(namespace.getPrefix())) {
1343                         return namespace;
1344                     }
1345                 }
1346             }
1347         }
1348 
1349         Element parent = getParent();
1350 
1351         if (parent != null) {
1352             Namespace answer = parent.getNamespaceForPrefix(prefix);
1353 
1354             if (answer != null) {
1355                 return answer;
1356             }
1357         }
1358 
1359         if ((prefix == null) || (prefix.length() <= 0)) {
1360             return Namespace.NO_NAMESPACE;
1361         }
1362 
1363         return null;
1364     }
1365 
1366     public Namespace getNamespaceForURI(String uri) {
1367         if ((uri == null) || (uri.length() <= 0)) {
1368             return Namespace.NO_NAMESPACE;
1369         } else if (uri.equals(getNamespaceURI())) {
1370             return getNamespace();
1371         } else {
1372             List list = contentList();
1373 
1374             int size = list.size();
1375 
1376             for (int i = 0; i < size; i++) {
1377                 Object object = list.get(i);
1378 
1379                 if (object instanceof Namespace) {
1380                     Namespace namespace = (Namespace) object;
1381 
1382                     if (uri.equals(namespace.getURI())) {
1383                         return namespace;
1384                     }
1385                 }
1386             }
1387 
1388             return null;
1389         }
1390     }
1391 
1392     public List getNamespacesForURI(String uri) {
1393         BackedList answer = createResultList();
1394 
1395         // if (getNamespaceURI().equals(uri)) {
1396         //
1397         // answer.addLocal(getNamespace());
1398         //
1399         // }
1400         List list = contentList();
1401 
1402         int size = list.size();
1403 
1404         for (int i = 0; i < size; i++) {
1405             Object object = list.get(i);
1406 
1407             if ((object instanceof Namespace)
1408                     && ((Namespace) object).getURI().equals(uri)) {
1409                 answer.addLocal(object);
1410             }
1411         }
1412 
1413         return answer;
1414     }
1415 
1416     public List declaredNamespaces() {
1417         BackedList answer = createResultList();
1418 
1419         // if (getNamespaceURI().length() > 0) {
1420         //
1421         // answer.addLocal(getNamespace());
1422         //
1423         // }
1424         //
1425         List list = contentList();
1426 
1427         int size = list.size();
1428 
1429         for (int i = 0; i < size; i++) {
1430             Object object = list.get(i);
1431 
1432             if (object instanceof Namespace) {
1433                 answer.addLocal(object);
1434             }
1435         }
1436 
1437         return answer;
1438     }
1439 
1440     public List additionalNamespaces() {
1441         List list = contentList();
1442 
1443         int size = list.size();
1444 
1445         BackedList answer = createResultList();
1446 
1447         for (int i = 0; i < size; i++) {
1448             Object object = list.get(i);
1449 
1450             if (object instanceof Namespace) {
1451                 Namespace namespace = (Namespace) object;
1452 
1453                 if (!namespace.equals(getNamespace())) {
1454                     answer.addLocal(namespace);
1455                 }
1456             }
1457         }
1458 
1459         return answer;
1460     }
1461 
1462     public List additionalNamespaces(String defaultNamespaceURI) {
1463         List list = contentList();
1464 
1465         BackedList answer = createResultList();
1466 
1467         int size = list.size();
1468 
1469         for (int i = 0; i < size; i++) {
1470             Object object = list.get(i);
1471 
1472             if (object instanceof Namespace) {
1473                 Namespace namespace = (Namespace) object;
1474 
1475                 if (!defaultNamespaceURI.equals(namespace.getURI())) {
1476                     answer.addLocal(namespace);
1477                 }
1478             }
1479         }
1480 
1481         return answer;
1482     }
1483 
1484     // Implementation helper methods
1485     // -------------------------------------------------------------------------
1486 
1487     /***
1488      * Ensures that the list of attributes has the given size
1489      * 
1490      * @param minCapacity
1491      *            DOCUMENT ME!
1492      */
1493     public void ensureAttributesCapacity(int minCapacity) {
1494         if (minCapacity > 1) {
1495             List list = attributeList();
1496 
1497             if (list instanceof ArrayList) {
1498                 ArrayList arrayList = (ArrayList) list;
1499 
1500                 arrayList.ensureCapacity(minCapacity);
1501             }
1502         }
1503     }
1504 
1505     // Implementation methods
1506     // -------------------------------------------------------------------------
1507     protected Element createElement(String name) {
1508         return getDocumentFactory().createElement(name);
1509     }
1510 
1511     protected Element createElement(QName qName) {
1512         return getDocumentFactory().createElement(qName);
1513     }
1514 
1515     protected void addNode(Node node) {
1516         if (node.getParent() != null) {
1517             // XXX: could clone here
1518             String message = "The Node already has an existing parent of \""
1519                     + node.getParent().getQualifiedName() + "\"";
1520 
1521             throw new IllegalAddException(this, node, message);
1522         }
1523 
1524         addNewNode(node);
1525     }
1526 
1527     protected void addNode(int index, Node node) {
1528         if (node.getParent() != null) {
1529             // XXX: could clone here
1530             String message = "The Node already has an existing parent of \""
1531                     + node.getParent().getQualifiedName() + "\"";
1532 
1533             throw new IllegalAddException(this, node, message);
1534         }
1535 
1536         addNewNode(index, node);
1537     }
1538 
1539     /***
1540      * Like addNode() but does not require a parent check
1541      * 
1542      * @param node
1543      *            DOCUMENT ME!
1544      */
1545     protected void addNewNode(Node node) {
1546         contentList().add(node);
1547 
1548         childAdded(node);
1549     }
1550 
1551     protected void addNewNode(int index, Node node) {
1552         contentList().add(index, node);
1553 
1554         childAdded(node);
1555     }
1556 
1557     protected boolean removeNode(Node node) {
1558         boolean answer = contentList().remove(node);
1559 
1560         if (answer) {
1561             childRemoved(node);
1562         }
1563 
1564         return answer;
1565     }
1566 
1567     /***
1568      * Called when a new child node is added to create any parent relationships
1569      * 
1570      * @param node
1571      *            DOCUMENT ME!
1572      */
1573     protected void childAdded(Node node) {
1574         if (node != null) {
1575             node.setParent(this);
1576         }
1577     }
1578 
1579     protected void childRemoved(Node node) {
1580         if (node != null) {
1581             node.setParent(null);
1582 
1583             node.setDocument(null);
1584         }
1585     }
1586 
1587     /***
1588      * DOCUMENT ME!
1589      * 
1590      * @return the internal List used to store attributes or creates one if one
1591      *         is not available
1592      */
1593     protected abstract List attributeList();
1594 
1595     /***
1596      * DOCUMENT ME!
1597      * 
1598      * @param attributeCount
1599      *            DOCUMENT ME!
1600      * 
1601      * @return the internal List used to store attributes or creates one with
1602      *         the specified size if one is not available
1603      */
1604     protected abstract List attributeList(int attributeCount);
1605 
1606     protected DocumentFactory getDocumentFactory() {
1607         QName qName = getQName();
1608 
1609         // QName might be null as we might not have been constructed yet
1610         if (qName != null) {
1611             DocumentFactory factory = qName.getDocumentFactory();
1612 
1613             if (factory != null) {
1614                 return factory;
1615             }
1616         }
1617 
1618         return DOCUMENT_FACTORY;
1619     }
1620 
1621     /***
1622      * A Factory Method pattern which creates a List implementation used to
1623      * store attributes
1624      * 
1625      * @return DOCUMENT ME!
1626      */
1627     protected List createAttributeList() {
1628         return createAttributeList(DEFAULT_CONTENT_LIST_SIZE);
1629     }
1630 
1631     /***
1632      * A Factory Method pattern which creates a List implementation used to
1633      * store attributes
1634      * 
1635      * @param size
1636      *            DOCUMENT ME!
1637      * 
1638      * @return DOCUMENT ME!
1639      */
1640     protected List createAttributeList(int size) {
1641         return new ArrayList(size);
1642     }
1643 
1644     protected Iterator createSingleIterator(Object result) {
1645         return new SingleIterator(result);
1646     }
1647 }
1648 
1649 /*
1650  * Redistribution and use of this software and associated documentation
1651  * ("Software"), with or without modification, are permitted provided that the
1652  * following conditions are met:
1653  * 
1654  * 1. Redistributions of source code must retain copyright statements and
1655  * notices. Redistributions must also contain a copy of this document.
1656  * 
1657  * 2. Redistributions in binary form must reproduce the above copyright notice,
1658  * this list of conditions and the following disclaimer in the documentation
1659  * and/or other materials provided with the distribution.
1660  * 
1661  * 3. The name "DOM4J" must not be used to endorse or promote products derived
1662  * from this Software without prior written permission of MetaStuff, Ltd. For
1663  * written permission, please contact dom4j-info@metastuff.com.
1664  * 
1665  * 4. Products derived from this Software may not be called "DOM4J" nor may
1666  * "DOM4J" appear in their names without prior written permission of MetaStuff,
1667  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
1668  * 
1669  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
1670  * 
1671  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
1672  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1673  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1674  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
1675  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
1676  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
1677  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
1678  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
1679  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
1680  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
1681  * POSSIBILITY OF SUCH DAMAGE.
1682  * 
1683  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
1684  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/AbstractEntity.html0000644000175000017500000002476610242117611022363 0ustar ebourgebourg AbstractEntity xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.io.IOException;
11  import java.io.Writer;
12  
13  import org.dom4j.Element;
14  import org.dom4j.Entity;
15  import org.dom4j.Visitor;
16  
17  /***
18   * <p>
19   * <code>AbstractEntity</code> is an abstract base class for tree implementors
20   * to use for implementation inheritence.
21   * </p>
22   * 
23   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
24   * @version $Revision: 1.15 $
25   */
26  public abstract class AbstractEntity extends AbstractNode implements Entity {
27      public AbstractEntity() {
28      }
29  
30      public short getNodeType() {
31          return ENTITY_REFERENCE_NODE;
32      }
33  
34      public String getPath(Element context) {
35          // From XPaths perspective, entities are included in text
36          Element parent = getParent();
37  
38          return ((parent != null) && (parent != context)) ? (parent
39                  .getPath(context) + "/text()") : "text()";
40      }
41  
42      public String getUniquePath(Element context) {
43          // From XPaths perspective, entities are included in text
44          Element parent = getParent();
45  
46          return ((parent != null) && (parent != context)) ? (parent
47                  .getUniquePath(context) + "/text()") : "text()";
48      }
49  
50      public String toString() {
51          return super.toString() + " [Entity: &" + getName() + ";]";
52      }
53  
54      public String getStringValue() {
55          return "&" + getName() + ";";
56      }
57  
58      public String asXML() {
59          return "&" + getName() + ";";
60      }
61  
62      public void write(Writer writer) throws IOException {
63          writer.write("&");
64          writer.write(getName());
65          writer.write(";");
66      }
67  
68      public void accept(Visitor visitor) {
69          visitor.visit(this);
70      }
71  }
72  
73  /*
74   * Redistribution and use of this software and associated documentation
75   * ("Software"), with or without modification, are permitted provided that the
76   * following conditions are met:
77   * 
78   * 1. Redistributions of source code must retain copyright statements and
79   * notices. Redistributions must also contain a copy of this document.
80   * 
81   * 2. Redistributions in binary form must reproduce the above copyright notice,
82   * this list of conditions and the following disclaimer in the documentation
83   * and/or other materials provided with the distribution.
84   * 
85   * 3. The name "DOM4J" must not be used to endorse or promote products derived
86   * from this Software without prior written permission of MetaStuff, Ltd. For
87   * written permission, please contact dom4j-info@metastuff.com.
88   * 
89   * 4. Products derived from this Software may not be called "DOM4J" nor may
90   * "DOM4J" appear in their names without prior written permission of MetaStuff,
91   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
92   * 
93   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
94   * 
95   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
96   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
97   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
98   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
99   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
100  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
101  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
102  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
103  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
104  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
105  * POSSIBILITY OF SUCH DAMAGE.
106  * 
107  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
108  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/DefaultComment.html0000644000175000017500000002316310242117707022326 0ustar ebourgebourg DefaultComment xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import org.dom4j.Element;
11  
12  /***
13   * <p>
14   * <code>DefaultComment</code> is the default Comment implementation. It is a
15   * doubly linked node which supports the parent relationship and can be modified
16   * in place.
17   * </p>
18   * 
19   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
20   * @version $Revision: 1.11 $
21   */
22  public class DefaultComment extends FlyweightComment {
23      /*** The parent of this node */
24      private Element parent;
25  
26      /***
27       * DOCUMENT ME!
28       * 
29       * @param text
30       *            is the Comment text
31       */
32      public DefaultComment(String text) {
33          super(text);
34      }
35  
36      /***
37       * DOCUMENT ME!
38       * 
39       * @param parent
40       *            is the parent element
41       * @param text
42       *            is the Comment text
43       */
44      public DefaultComment(Element parent, String text) {
45          super(text);
46          this.parent = parent;
47      }
48  
49      public void setText(String text) {
50          this.text = text;
51      }
52  
53      public Element getParent() {
54          return parent;
55      }
56  
57      public void setParent(Element parent) {
58          this.parent = parent;
59      }
60  
61      public boolean supportsParent() {
62          return true;
63      }
64  
65      public boolean isReadOnly() {
66          return false;
67      }
68  }
69  
70  /*
71   * Redistribution and use of this software and associated documentation
72   * ("Software"), with or without modification, are permitted provided that the
73   * following conditions are met:
74   * 
75   * 1. Redistributions of source code must retain copyright statements and
76   * notices. Redistributions must also contain a copy of this document.
77   * 
78   * 2. Redistributions in binary form must reproduce the above copyright notice,
79   * this list of conditions and the following disclaimer in the documentation
80   * and/or other materials provided with the distribution.
81   * 
82   * 3. The name "DOM4J" must not be used to endorse or promote products derived
83   * from this Software without prior written permission of MetaStuff, Ltd. For
84   * written permission, please contact dom4j-info@metastuff.com.
85   * 
86   * 4. Products derived from this Software may not be called "DOM4J" nor may
87   * "DOM4J" appear in their names without prior written permission of MetaStuff,
88   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
89   * 
90   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
91   * 
92   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
93   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
95   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
96   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
97   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
98   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
99   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
100  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
102  * POSSIBILITY OF SUCH DAMAGE.
103  * 
104  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
105  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/DefaultText.html0000644000175000017500000002311110242117721021635 0ustar ebourgebourg DefaultText xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import org.dom4j.Element;
11  
12  /***
13   * <p>
14   * <code>DefaultText</code> is the default Text implementation. It is a doubly
15   * linked node which supports the parent relationship and can be modified in
16   * place.
17   * </p>
18   * 
19   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
20   * @version $Revision: 1.11 $
21   */
22  public class DefaultText extends FlyweightText {
23      /*** The parent of this node */
24      private Element parent;
25  
26      /***
27       * DOCUMENT ME!
28       * 
29       * @param text
30       *            is the Text text
31       */
32      public DefaultText(String text) {
33          super(text);
34      }
35  
36      /***
37       * DOCUMENT ME!
38       * 
39       * @param parent
40       *            is the parent element
41       * @param text
42       *            is the Text text
43       */
44      public DefaultText(Element parent, String text) {
45          super(text);
46          this.parent = parent;
47      }
48  
49      public void setText(String text) {
50          this.text = text;
51      }
52  
53      public Element getParent() {
54          return parent;
55      }
56  
57      public void setParent(Element parent) {
58          this.parent = parent;
59      }
60  
61      public boolean supportsParent() {
62          return true;
63      }
64  
65      public boolean isReadOnly() {
66          return false;
67      }
68  }
69  
70  /*
71   * Redistribution and use of this software and associated documentation
72   * ("Software"), with or without modification, are permitted provided that the
73   * following conditions are met:
74   * 
75   * 1. Redistributions of source code must retain copyright statements and
76   * notices. Redistributions must also contain a copy of this document.
77   * 
78   * 2. Redistributions in binary form must reproduce the above copyright notice,
79   * this list of conditions and the following disclaimer in the documentation
80   * and/or other materials provided with the distribution.
81   * 
82   * 3. The name "DOM4J" must not be used to endorse or promote products derived
83   * from this Software without prior written permission of MetaStuff, Ltd. For
84   * written permission, please contact dom4j-info@metastuff.com.
85   * 
86   * 4. Products derived from this Software may not be called "DOM4J" nor may
87   * "DOM4J" appear in their names without prior written permission of MetaStuff,
88   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
89   * 
90   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
91   * 
92   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
93   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
95   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
96   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
97   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
98   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
99   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
100  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
102  * POSSIBILITY OF SUCH DAMAGE.
103  * 
104  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
105  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/DefaultEntity.html0000644000175000017500000002603510242117722022176 0ustar ebourgebourg DefaultEntity xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import org.dom4j.Element;
11  
12  /***
13   * <p>
14   * <code>DefaultEntity</code> is the default Entity implementation. It is a
15   * doubly linked node which supports the parent relationship and can be modified
16   * in place.
17   * </p>
18   * 
19   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
20   * @version $Revision: 1.11 $
21   */
22  public class DefaultEntity extends FlyweightEntity {
23      /*** The parent of this node */
24      private Element parent;
25  
26      /***
27       * Creates the <code>Entity</code> with the specified name
28       * 
29       * @param name
30       *            is the name of the entity
31       */
32      public DefaultEntity(String name) {
33          super(name);
34      }
35  
36      /***
37       * Creates the <code>Entity</code> with the specified name and text.
38       * 
39       * @param name
40       *            is the name of the entity
41       * @param text
42       *            is the text of the entity
43       */
44      public DefaultEntity(String name, String text) {
45          super(name, text);
46      }
47  
48      /***
49       * Creates the <code>Entity</code> with the specified name and text.
50       * 
51       * @param parent
52       *            is the parent element
53       * @param name
54       *            is the name of the entity
55       * @param text
56       *            is the text of the entity
57       */
58      public DefaultEntity(Element parent, String name, String text) {
59          super(name, text);
60          this.parent = parent;
61      }
62  
63      public void setName(String name) {
64          this.name = name;
65      }
66  
67      public void setText(String text) {
68          this.text = text;
69      }
70  
71      public Element getParent() {
72          return parent;
73      }
74  
75      public void setParent(Element parent) {
76          this.parent = parent;
77      }
78  
79      public boolean supportsParent() {
80          return true;
81      }
82  
83      public boolean isReadOnly() {
84          return false;
85      }
86  }
87  
88  /*
89   * Redistribution and use of this software and associated documentation
90   * ("Software"), with or without modification, are permitted provided that the
91   * following conditions are met:
92   * 
93   * 1. Redistributions of source code must retain copyright statements and
94   * notices. Redistributions must also contain a copy of this document.
95   * 
96   * 2. Redistributions in binary form must reproduce the above copyright notice,
97   * this list of conditions and the following disclaimer in the documentation
98   * and/or other materials provided with the distribution.
99   * 
100  * 3. The name "DOM4J" must not be used to endorse or promote products derived
101  * from this Software without prior written permission of MetaStuff, Ltd. For
102  * written permission, please contact dom4j-info@metastuff.com.
103  * 
104  * 4. Products derived from this Software may not be called "DOM4J" nor may
105  * "DOM4J" appear in their names without prior written permission of MetaStuff,
106  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
107  * 
108  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
109  * 
110  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
111  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
112  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
113  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
114  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
115  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
116  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
117  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
118  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
119  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
120  * POSSIBILITY OF SUCH DAMAGE.
121  * 
122  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
123  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/AbstractCDATA.html0000644000175000017500000002261110242117757021721 0ustar ebourgebourg AbstractCDATA xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.io.IOException;
11  import java.io.StringWriter;
12  import java.io.Writer;
13  
14  import org.dom4j.CDATA;
15  import org.dom4j.Visitor;
16  
17  /***
18   * <p>
19   * <code>AbstractCDATA</code> is an abstract base class for tree implementors
20   * to use for implementation inheritence.
21   * </p>
22   * 
23   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
24   * @version $Revision: 1.12 $
25   */
26  public abstract class AbstractCDATA extends AbstractCharacterData implements
27          CDATA {
28      public AbstractCDATA() {
29      }
30  
31      public short getNodeType() {
32          return CDATA_SECTION_NODE;
33      }
34  
35      public String toString() {
36          return super.toString() + " [CDATA: \"" + getText() + "\"]";
37      }
38  
39      public String asXML() {
40          StringWriter writer = new StringWriter();
41  
42          try {
43              write(writer);
44          } catch (IOException e) {
45              // will not happen since we are using a StringWriter!
46          }
47  
48          return writer.toString();
49      }
50  
51      public void write(Writer writer) throws IOException {
52          writer.write("<![CDATA[");
53  
54          if (getText() != null) {
55              writer.write(getText());
56          }
57  
58          writer.write("]]>");
59      }
60  
61      public void accept(Visitor visitor) {
62          visitor.visit(this);
63      }
64  }
65  
66  /*
67   * Redistribution and use of this software and associated documentation
68   * ("Software"), with or without modification, are permitted provided that the
69   * following conditions are met:
70   * 
71   * 1. Redistributions of source code must retain copyright statements and
72   * notices. Redistributions must also contain a copy of this document.
73   * 
74   * 2. Redistributions in binary form must reproduce the above copyright notice,
75   * this list of conditions and the following disclaimer in the documentation
76   * and/or other materials provided with the distribution.
77   * 
78   * 3. The name "DOM4J" must not be used to endorse or promote products derived
79   * from this Software without prior written permission of MetaStuff, Ltd. For
80   * written permission, please contact dom4j-info@metastuff.com.
81   * 
82   * 4. Products derived from this Software may not be called "DOM4J" nor may
83   * "DOM4J" appear in their names without prior written permission of MetaStuff,
84   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
85   * 
86   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
87   * 
88   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
89   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
90   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
91   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
92   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
93   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
94   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
95   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
96   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
97   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
98   * POSSIBILITY OF SUCH DAMAGE.
99   * 
100  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
101  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/FlyweightText.html0000644000175000017500000002071310242117701022216 0ustar ebourgebourg FlyweightText xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import org.dom4j.Element;
11  import org.dom4j.Node;
12  import org.dom4j.Text;
13  
14  /***
15   * <p>
16   * <code>FlyweightText</code> is a Flyweight pattern implementation of a
17   * singly linked, read-only XML Text.
18   * </p>
19   * 
20   * <p>
21   * This node could be shared across documents and elements though it does not
22   * support the parent relationship.
23   * </p>
24   * 
25   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
26   * @version $Revision: 1.7 $
27   */
28  public class FlyweightText extends AbstractText implements Text {
29      /*** Text of the <code>Text</code> node */
30      protected String text;
31  
32      /***
33       * DOCUMENT ME!
34       * 
35       * @param text
36       *            is the Text text
37       */
38      public FlyweightText(String text) {
39          this.text = text;
40      }
41  
42      public String getText() {
43          return text;
44      }
45  
46      protected Node createXPathResult(Element parent) {
47          return new DefaultText(parent, getText());
48      }
49  }
50  
51  /*
52   * Redistribution and use of this software and associated documentation
53   * ("Software"), with or without modification, are permitted provided that the
54   * following conditions are met:
55   * 
56   * 1. Redistributions of source code must retain copyright statements and
57   * notices. Redistributions must also contain a copy of this document.
58   * 
59   * 2. Redistributions in binary form must reproduce the above copyright notice,
60   * this list of conditions and the following disclaimer in the documentation
61   * and/or other materials provided with the distribution.
62   * 
63   * 3. The name "DOM4J" must not be used to endorse or promote products derived
64   * from this Software without prior written permission of MetaStuff, Ltd. For
65   * written permission, please contact dom4j-info@metastuff.com.
66   * 
67   * 4. Products derived from this Software may not be called "DOM4J" nor may
68   * "DOM4J" appear in their names without prior written permission of MetaStuff,
69   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
70   * 
71   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
72   * 
73   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
74   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
75   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
76   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
77   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
78   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
79   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
80   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
81   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
82   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
83   * POSSIBILITY OF SUCH DAMAGE.
84   * 
85   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
86   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/AbstractText.html0000644000175000017500000002037510242117751022030 0ustar ebourgebourg AbstractText xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.io.IOException;
11  import java.io.Writer;
12  
13  import org.dom4j.Visitor;
14  
15  /***
16   * <p>
17   * <code>AbstractText</code> is an abstract base class for tree implementors
18   * to use for implementation inheritence.
19   * </p>
20   * 
21   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
22   * @version $Revision: 1.10 $
23   */
24  public abstract class AbstractText extends AbstractCharacterData implements
25          org.dom4j.Text {
26      public AbstractText() {
27      }
28  
29      public short getNodeType() {
30          return TEXT_NODE;
31      }
32  
33      public String toString() {
34          return super.toString() + " [Text: \"" + getText() + "\"]";
35      }
36  
37      public String asXML() {
38          return getText();
39      }
40  
41      public void write(Writer writer) throws IOException {
42          writer.write(getText());
43      }
44  
45      public void accept(Visitor visitor) {
46          visitor.visit(this);
47      }
48  }
49  
50  /*
51   * Redistribution and use of this software and associated documentation
52   * ("Software"), with or without modification, are permitted provided that the
53   * following conditions are met:
54   * 
55   * 1. Redistributions of source code must retain copyright statements and
56   * notices. Redistributions must also contain a copy of this document.
57   * 
58   * 2. Redistributions in binary form must reproduce the above copyright notice,
59   * this list of conditions and the following disclaimer in the documentation
60   * and/or other materials provided with the distribution.
61   * 
62   * 3. The name "DOM4J" must not be used to endorse or promote products derived
63   * from this Software without prior written permission of MetaStuff, Ltd. For
64   * written permission, please contact dom4j-info@metastuff.com.
65   * 
66   * 4. Products derived from this Software may not be called "DOM4J" nor may
67   * "DOM4J" appear in their names without prior written permission of MetaStuff,
68   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
69   * 
70   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
71   * 
72   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
73   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
74   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
75   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
76   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
77   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
78   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
79   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
80   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
81   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
82   * POSSIBILITY OF SUCH DAMAGE.
83   * 
84   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
85   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/BackedList.html0000644000175000017500000004331010242117730021414 0ustar ebourgebourg BackedList xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.util.ArrayList;
11  import java.util.Collection;
12  import java.util.Iterator;
13  import java.util.List;
14  
15  import org.dom4j.IllegalAddException;
16  import org.dom4j.Node;
17  
18  /***
19   * <p>
20   * <code>BackedList</code> represents a list of content of a {@link
21   * org.dom4j.Branch}. Changes to the list will be reflected in the branch,
22   * though changes to the branch will not be reflected in this list.
23   * </p>
24   * 
25   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
26   * @version $Revision: 1.14 $
27   */
28  public class BackedList extends ArrayList {
29      /*** The content of the Branch which is modified if I am modified */
30      private List branchContent;
31  
32      /*** The <code>AbstractBranch</code> instance which owns the content */
33      private AbstractBranch branch;
34  
35      public BackedList(AbstractBranch branch, List branchContent) {
36          this(branch, branchContent, branchContent.size());
37      }
38  
39      public BackedList(AbstractBranch branch, List branchContent, int capacity) {
40          super(capacity);
41          this.branch = branch;
42          this.branchContent = branchContent;
43      }
44  
45      public BackedList(AbstractBranch branch, List branchContent,
46              List initialContent) {
47          super(initialContent);
48          this.branch = branch;
49          this.branchContent = branchContent;
50      }
51  
52      public boolean add(Object object) {
53          branch.addNode(asNode(object));
54  
55          return super.add(object);
56      }
57  
58      public void add(int index, Object object) {
59          int size = size();
60  
61          if (index < 0) {
62              throw new IndexOutOfBoundsException("Index value: " + index
63                      + " is less than zero");
64          } else if (index > size) {
65              throw new IndexOutOfBoundsException("Index value: " + index
66                      + " cannot be greater than " + "the size: " + size);
67          }
68  
69          int realIndex;
70  
71          if (size == 0) {
72              realIndex = branchContent.size();
73          } else if (index < size) {
74              realIndex = branchContent.indexOf(get(index));
75          } else {
76              realIndex = branchContent.indexOf(get(size - 1)) + 1;
77          }
78  
79          branch.addNode(realIndex, asNode(object));
80          super.add(index, object);
81      }
82  
83      public Object set(int index, Object object) {
84          int realIndex = branchContent.indexOf(get(index));
85  
86          if (realIndex < 0) {
87              realIndex = (index == 0) ? 0 : Integer.MAX_VALUE;
88          }
89  
90          if (realIndex < branchContent.size()) {
91              branch.removeNode(asNode(get(index)));
92              branch.addNode(realIndex, asNode(object));
93          } else {
94              branch.removeNode(asNode(get(index)));
95              branch.addNode(asNode(object));
96          }
97  
98          branch.childAdded(asNode(object));
99  
100         return super.set(index, object);
101     }
102 
103     public boolean remove(Object object) {
104         branch.removeNode(asNode(object));
105 
106         return super.remove(object);
107     }
108 
109     public Object remove(int index) {
110         Object object = super.remove(index);
111 
112         if (object != null) {
113             branch.removeNode(asNode(object));
114         }
115 
116         return object;
117     }
118 
119     public boolean addAll(Collection collection) {
120         ensureCapacity(size() + collection.size());
121 
122         int count = size();
123 
124         for (Iterator iter = collection.iterator(); iter.hasNext(); count--) {
125             add(iter.next());
126         }
127 
128         return count != 0;
129     }
130 
131     public boolean addAll(int index, Collection collection) {
132         ensureCapacity(size() + collection.size());
133 
134         int count = size();
135 
136         for (Iterator iter = collection.iterator(); iter.hasNext(); count--) {
137             add(index++, iter.next());
138         }
139 
140         return count != 0;
141     }
142 
143     public void clear() {
144         for (Iterator iter = iterator(); iter.hasNext();) {
145             Object object = iter.next();
146             branchContent.remove(object);
147             branch.childRemoved(asNode(object));
148         }
149 
150         super.clear();
151     }
152 
153     /***
154      * Performs a local addition which is not forward through to the Branch or
155      * backing list
156      * 
157      * @param object
158      *            DOCUMENT ME!
159      */
160     public void addLocal(Object object) {
161         super.add(object);
162     }
163 
164     protected Node asNode(Object object) {
165         if (object instanceof Node) {
166             return (Node) object;
167         } else {
168             throw new IllegalAddException("This list must contain instances "
169                     + "of Node. Invalid type: " + object);
170         }
171     }
172 }
173 
174 /*
175  * Redistribution and use of this software and associated documentation
176  * ("Software"), with or without modification, are permitted provided that the
177  * following conditions are met:
178  * 
179  * 1. Redistributions of source code must retain copyright statements and
180  * notices. Redistributions must also contain a copy of this document.
181  * 
182  * 2. Redistributions in binary form must reproduce the above copyright notice,
183  * this list of conditions and the following disclaimer in the documentation
184  * and/or other materials provided with the distribution.
185  * 
186  * 3. The name "DOM4J" must not be used to endorse or promote products derived
187  * from this Software without prior written permission of MetaStuff, Ltd. For
188  * written permission, please contact dom4j-info@metastuff.com.
189  * 
190  * 4. Products derived from this Software may not be called "DOM4J" nor may
191  * "DOM4J" appear in their names without prior written permission of MetaStuff,
192  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
193  * 
194  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
195  * 
196  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
197  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
198  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
199  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
200  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
201  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
202  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
203  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
204  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
205  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
206  * POSSIBILITY OF SUCH DAMAGE.
207  * 
208  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
209  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/DefaultAttribute.html0000644000175000017500000003205710242117746022674 0ustar ebourgebourg DefaultAttribute xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import org.dom4j.Element;
11  import org.dom4j.Namespace;
12  import org.dom4j.QName;
13  
14  /***
15   * <p>
16   * <code>DefaultAttribute</code> implements a doubly linked node which
17   * supports the parent relationship and is mutable.
18   * </p>
19   * 
20   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
21   * @version $Revision: 1.13 $
22   */
23  public class DefaultAttribute extends FlyweightAttribute {
24      /*** The parent of this node */
25      private Element parent;
26  
27      public DefaultAttribute(QName qname) {
28          super(qname);
29      }
30  
31      public DefaultAttribute(QName qname, String value) {
32          super(qname, value);
33      }
34  
35      public DefaultAttribute(Element parent, QName qname, String value) {
36          super(qname, value);
37          this.parent = parent;
38      }
39  
40      /***
41       * Creates the <code>Attribute</code> with the specified local name and
42       * value.
43       * 
44       * @param name
45       *            is the name of the attribute
46       * @param value
47       *            is the value of the attribute
48       */
49      public DefaultAttribute(String name, String value) {
50          super(name, value);
51      }
52  
53      /***
54       * Creates the <code>Attribute</code> with the specified local name, value
55       * and <code>Namespace</code>.
56       * 
57       * @param name
58       *            is the name of the attribute
59       * @param value
60       *            is the value of the attribute
61       * @param namespace
62       *            is the namespace of the attribute
63       */
64      public DefaultAttribute(String name, String value, Namespace namespace) {
65          super(name, value, namespace);
66      }
67  
68      /***
69       * Creates the <code>Attribute</code> with the specified local name, value
70       * and <code>Namespace</code>.
71       * 
72       * @param parent
73       *            is the parent element
74       * @param name
75       *            is the name of the attribute
76       * @param value
77       *            is the value of the attribute
78       * @param namespace
79       *            is the namespace of the attribute
80       */
81      public DefaultAttribute(Element parent, String name, String value,
82              Namespace namespace) {
83          super(name, value, namespace);
84          this.parent = parent;
85      }
86  
87      public void setValue(String value) {
88          this.value = value;
89      }
90  
91      public Element getParent() {
92          return parent;
93      }
94  
95      public void setParent(Element parent) {
96          this.parent = parent;
97      }
98  
99      public boolean supportsParent() {
100         return true;
101     }
102 
103     public boolean isReadOnly() {
104         return false;
105     }
106 }
107 
108 /*
109  * Redistribution and use of this software and associated documentation
110  * ("Software"), with or without modification, are permitted provided that the
111  * following conditions are met:
112  * 
113  * 1. Redistributions of source code must retain copyright statements and
114  * notices. Redistributions must also contain a copy of this document.
115  * 
116  * 2. Redistributions in binary form must reproduce the above copyright notice,
117  * this list of conditions and the following disclaimer in the documentation
118  * and/or other materials provided with the distribution.
119  * 
120  * 3. The name "DOM4J" must not be used to endorse or promote products derived
121  * from this Software without prior written permission of MetaStuff, Ltd. For
122  * written permission, please contact dom4j-info@metastuff.com.
123  * 
124  * 4. Products derived from this Software may not be called "DOM4J" nor may
125  * "DOM4J" appear in their names without prior written permission of MetaStuff,
126  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
127  * 
128  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
129  * 
130  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
131  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
132  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
133  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
134  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
135  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
136  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
137  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
138  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
139  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
140  * POSSIBILITY OF SUCH DAMAGE.
141  * 
142  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
143  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/DefaultNamespace.html0000644000175000017500000003127110242117671022617 0ustar ebourgebourg DefaultNamespace xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import org.dom4j.Element;
11  import org.dom4j.Namespace;
12  
13  /***
14   * <p>
15   * <code>DefaultNamespace</code> implements a doubly linked node which
16   * supports the parent relationship and is mutable. It is useful when returning
17   * results from XPath expressions.
18   * </p>
19   * 
20   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
21   * @version $Revision: 1.16 $
22   */
23  public class DefaultNamespace extends Namespace {
24      /*** The parent of this node */
25      private Element parent;
26  
27      /***
28       * DOCUMENT ME!
29       * 
30       * @param prefix
31       *            is the prefix for this namespace
32       * @param uri
33       *            is the URI for this namespace
34       */
35      public DefaultNamespace(String prefix, String uri) {
36          super(prefix, uri);
37      }
38  
39      /***
40       * DOCUMENT ME!
41       * 
42       * @param parent
43       *            is the parent element
44       * @param prefix
45       *            is the prefix for this namespace
46       * @param uri
47       *            is the URI for this namespace
48       */
49      public DefaultNamespace(Element parent, String prefix, String uri) {
50          super(prefix, uri);
51          this.parent = parent;
52      }
53  
54      /***
55       * DOCUMENT ME!
56       * 
57       * @return the hash code based on the qualified name and the URI of the
58       *         namespace and the hashCode() of the parent element.
59       */
60      protected int createHashCode() {
61          int hashCode = super.createHashCode();
62  
63          if (parent != null) {
64              hashCode ^= parent.hashCode();
65          }
66  
67          return hashCode;
68      }
69  
70      /***
71       * Implements an identity based comparsion using the parent element as well
72       * as the prefix and URI
73       * 
74       * @param object
75       *            DOCUMENT ME!
76       * 
77       * @return DOCUMENT ME!
78       */
79      public boolean equals(Object object) {
80          if (object instanceof DefaultNamespace) {
81              DefaultNamespace that = (DefaultNamespace) object;
82  
83              if (that.parent == parent) {
84                  return super.equals(object);
85              }
86          }
87  
88          return false;
89      }
90  
91      public int hashCode() {
92          return super.hashCode();
93      }
94  
95      public Element getParent() {
96          return parent;
97      }
98  
99      public void setParent(Element parent) {
100         this.parent = parent;
101     }
102 
103     public boolean supportsParent() {
104         return true;
105     }
106     
107     public boolean isReadOnly() {
108         return false;
109     }
110 }
111 
112 /*
113  * Redistribution and use of this software and associated documentation
114  * ("Software"), with or without modification, are permitted provided that the
115  * following conditions are met:
116  * 
117  * 1. Redistributions of source code must retain copyright statements and
118  * notices. Redistributions must also contain a copy of this document.
119  * 
120  * 2. Redistributions in binary form must reproduce the above copyright notice,
121  * this list of conditions and the following disclaimer in the documentation
122  * and/or other materials provided with the distribution.
123  * 
124  * 3. The name "DOM4J" must not be used to endorse or promote products derived
125  * from this Software without prior written permission of MetaStuff, Ltd. For
126  * written permission, please contact dom4j-info@metastuff.com.
127  * 
128  * 4. Products derived from this Software may not be called "DOM4J" nor may
129  * "DOM4J" appear in their names without prior written permission of MetaStuff,
130  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
131  * 
132  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
133  * 
134  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
135  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
136  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
137  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
138  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
139  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
140  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
141  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
142  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
143  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
144  * POSSIBILITY OF SUCH DAMAGE.
145  * 
146  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
147  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/AbstractComment.html0000644000175000017500000002403110242117606022476 0ustar ebourgebourg AbstractComment xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.io.IOException;
11  import java.io.Writer;
12  
13  import org.dom4j.Comment;
14  import org.dom4j.Element;
15  import org.dom4j.Visitor;
16  
17  /***
18   * <p>
19   * <code>AbstractComment</code> is an abstract base class for tree
20   * implementors to use for implementation inheritence.
21   * </p>
22   * 
23   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
24   * @version $Revision: 1.13 $
25   */
26  public abstract class AbstractComment extends AbstractCharacterData implements
27          Comment {
28      public AbstractComment() {
29      }
30  
31      public short getNodeType() {
32          return COMMENT_NODE;
33      }
34  
35      public String getPath(Element context) {
36          Element parent = getParent();
37  
38          return ((parent != null) && (parent != context)) ? (parent
39                  .getPath(context) + "/comment()") : "comment()";
40      }
41  
42      public String getUniquePath(Element context) {
43          Element parent = getParent();
44  
45          return ((parent != null) && (parent != context)) ? (parent
46                  .getUniquePath(context) + "/comment()") : "comment()";
47      }
48  
49      public String toString() {
50          return super.toString() + " [Comment: \"" + getText() + "\"]";
51      }
52  
53      public String asXML() {
54          return "<!--" + getText() + "-->";
55      }
56  
57      public void write(Writer writer) throws IOException {
58          writer.write("<!--");
59          writer.write(getText());
60          writer.write("-->");
61      }
62  
63      public void accept(Visitor visitor) {
64          visitor.visit(this);
65      }
66  }
67  
68  /*
69   * Redistribution and use of this software and associated documentation
70   * ("Software"), with or without modification, are permitted provided that the
71   * following conditions are met:
72   * 
73   * 1. Redistributions of source code must retain copyright statements and
74   * notices. Redistributions must also contain a copy of this document.
75   * 
76   * 2. Redistributions in binary form must reproduce the above copyright notice,
77   * this list of conditions and the following disclaimer in the documentation
78   * and/or other materials provided with the distribution.
79   * 
80   * 3. The name "DOM4J" must not be used to endorse or promote products derived
81   * from this Software without prior written permission of MetaStuff, Ltd. For
82   * written permission, please contact dom4j-info@metastuff.com.
83   * 
84   * 4. Products derived from this Software may not be called "DOM4J" nor may
85   * "DOM4J" appear in their names without prior written permission of MetaStuff,
86   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
87   * 
88   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
89   * 
90   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
91   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
92   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
93   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
94   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
95   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
96   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
97   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
98   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
99   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
100  * POSSIBILITY OF SUCH DAMAGE.
101  * 
102  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
103  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/FlyweightComment.html0000644000175000017500000002077610242117544022712 0ustar ebourgebourg FlyweightComment xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import org.dom4j.Comment;
11  import org.dom4j.Element;
12  import org.dom4j.Node;
13  
14  /***
15   * <p>
16   * <code>FlyweightComment</code> is a Flyweight pattern implementation of a
17   * singly linked, read-only XML Comment.
18   * </p>
19   * 
20   * <p>
21   * This node could be shared across documents and elements though it does not
22   * support the parent relationship.
23   * </p>
24   * 
25   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
26   * @version $Revision: 1.7 $
27   */
28  public class FlyweightComment extends AbstractComment implements Comment {
29      /*** Text of the <code>Comment</code> node */
30      protected String text;
31  
32      /***
33       * DOCUMENT ME!
34       * 
35       * @param text
36       *            is the Comment text
37       */
38      public FlyweightComment(String text) {
39          this.text = text;
40      }
41  
42      public String getText() {
43          return text;
44      }
45  
46      protected Node createXPathResult(Element parent) {
47          return new DefaultComment(parent, getText());
48      }
49  }
50  
51  /*
52   * Redistribution and use of this software and associated documentation
53   * ("Software"), with or without modification, are permitted provided that the
54   * following conditions are met:
55   * 
56   * 1. Redistributions of source code must retain copyright statements and
57   * notices. Redistributions must also contain a copy of this document.
58   * 
59   * 2. Redistributions in binary form must reproduce the above copyright notice,
60   * this list of conditions and the following disclaimer in the documentation
61   * and/or other materials provided with the distribution.
62   * 
63   * 3. The name "DOM4J" must not be used to endorse or promote products derived
64   * from this Software without prior written permission of MetaStuff, Ltd. For
65   * written permission, please contact dom4j-info@metastuff.com.
66   * 
67   * 4. Products derived from this Software may not be called "DOM4J" nor may
68   * "DOM4J" appear in their names without prior written permission of MetaStuff,
69   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
70   * 
71   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
72   * 
73   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
74   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
75   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
76   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
77   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
78   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
79   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
80   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
81   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
82   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
83   * POSSIBILITY OF SUCH DAMAGE.
84   * 
85   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
86   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/AbstractProcessingInstruction.html0000644000175000017500000004664710242117553025474 0ustar ebourgebourg AbstractProcessingInstruction xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.io.IOException;
11  import java.io.Writer;
12  import java.util.HashMap;
13  import java.util.Iterator;
14  import java.util.Map;
15  import java.util.StringTokenizer;
16  
17  import org.dom4j.Element;
18  import org.dom4j.ProcessingInstruction;
19  import org.dom4j.Visitor;
20  
21  /***
22   * <p>
23   * <code>AbstractProcessingInstruction</code> is an abstract base class for
24   * tree implementors to use for implementation inheritence.
25   * </p>
26   * 
27   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
28   * @version $Revision: 1.17 $
29   */
30  public abstract class AbstractProcessingInstruction extends AbstractNode
31          implements ProcessingInstruction {
32      public AbstractProcessingInstruction() {
33      }
34  
35      public short getNodeType() {
36          return PROCESSING_INSTRUCTION_NODE;
37      }
38  
39      public String getPath(Element context) {
40          Element parent = getParent();
41  
42          return ((parent != null) && (parent != context)) ? (parent
43                  .getPath(context) + "/processing-instruction()")
44                  : "processing-instruction()";
45      }
46  
47      public String getUniquePath(Element context) {
48          Element parent = getParent();
49  
50          return ((parent != null) && (parent != context)) ? (parent
51                  .getUniquePath(context) + "/processing-instruction()")
52                  : "processing-instruction()";
53      }
54  
55      public String toString() {
56          return super.toString() + " [ProcessingInstruction: &" + getName()
57                  + ";]";
58      }
59  
60      public String asXML() {
61          return "<?" + getName() + " " + getText() + "?>";
62      }
63  
64      public void write(Writer writer) throws IOException {
65          writer.write("<?");
66          writer.write(getName());
67          writer.write(" ");
68          writer.write(getText());
69          writer.write("?>");
70      }
71  
72      public void accept(Visitor visitor) {
73          visitor.visit(this);
74      }
75  
76      public void setValue(String name, String value) {
77          throw new UnsupportedOperationException("This PI is read-only and "
78                  + "cannot be modified");
79      }
80  
81      public void setValues(Map data) {
82          throw new UnsupportedOperationException("This PI is read-only and "
83                  + "cannot be modified");
84      }
85  
86      public String getName() {
87          return getTarget();
88      }
89  
90      public void setName(String name) {
91          setTarget(name);
92      }
93  
94      public boolean removeValue(String name) {
95          return false;
96      }
97  
98      // Helper methods
99  
100     /***
101      * <p>
102      * This will convert the Map to a string representation.
103      * </p>
104      * 
105      * @param values
106      *            is a <code>Map</code> of PI data to convert
107      * 
108      * @return DOCUMENT ME!
109      */
110     protected String toString(Map values) {
111         StringBuffer buffer = new StringBuffer();
112 
113         for (Iterator iter = values.entrySet().iterator(); iter.hasNext();) {
114             Map.Entry entry = (Map.Entry) iter.next();
115             String name = (String) entry.getKey();
116             String value = (String) entry.getValue();
117 
118             buffer.append(name);
119             buffer.append("=\"");
120             buffer.append(value);
121             buffer.append("\" ");
122         }
123 
124         // remove the last space
125         buffer.setLength(buffer.length() - 1);
126 
127         return buffer.toString();
128     }
129 
130     /***
131      * <p>
132      * Parses the raw data of PI as a <code>Map</code>.
133      * </p>
134      * 
135      * @param text
136      *            <code>String</code> PI data to parse
137      * 
138      * @return DOCUMENT ME!
139      */
140     protected Map parseValues(String text) {
141         Map data = new HashMap();
142 
143         StringTokenizer s = new StringTokenizer(text, " =\'\"", true);
144 
145         while (s.hasMoreTokens()) {
146             String name = getName(s);
147 
148             if (s.hasMoreTokens()) {
149                 String value = getValue(s);
150                 data.put(name, value);
151             }
152         }
153 
154         return data;
155     }
156 
157     private String getName(StringTokenizer tokenizer) {
158         String token = tokenizer.nextToken();
159         StringBuffer name = new StringBuffer(token);
160 
161         while (tokenizer.hasMoreTokens()) {
162             token = tokenizer.nextToken();
163 
164             if (!token.equals("=")) {
165                 name.append(token);
166             } else {
167                 break;
168             }
169         }
170 
171         return name.toString().trim();
172     }
173 
174     private String getValue(StringTokenizer tokenizer) {
175         String token = tokenizer.nextToken();
176         StringBuffer value = new StringBuffer();
177 
178         /* get the quote */
179         while (tokenizer.hasMoreTokens() && !token.equals("\'")
180                 && !token.equals("\"")) {
181             token = tokenizer.nextToken();
182         }
183 
184         String quote = token;
185 
186         while (tokenizer.hasMoreTokens()) {
187             token = tokenizer.nextToken();
188 
189             if (!quote.equals(token)) {
190                 value.append(token);
191             } else {
192                 break;
193             }
194         }
195 
196         return value.toString();
197     }
198 }
199 
200 /*
201  * Redistribution and use of this software and associated documentation
202  * ("Software"), with or without modification, are permitted provided that the
203  * following conditions are met:
204  * 
205  * 1. Redistributions of source code must retain copyright statements and
206  * notices. Redistributions must also contain a copy of this document.
207  * 
208  * 2. Redistributions in binary form must reproduce the above copyright notice,
209  * this list of conditions and the following disclaimer in the documentation
210  * and/or other materials provided with the distribution.
211  * 
212  * 3. The name "DOM4J" must not be used to endorse or promote products derived
213  * from this Software without prior written permission of MetaStuff, Ltd. For
214  * written permission, please contact dom4j-info@metastuff.com.
215  * 
216  * 4. Products derived from this Software may not be called "DOM4J" nor may
217  * "DOM4J" appear in their names without prior written permission of MetaStuff,
218  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
219  * 
220  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
221  * 
222  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
223  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
224  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
225  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
226  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
227  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
228  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
229  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
230  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
231  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
232  * POSSIBILITY OF SUCH DAMAGE.
233  * 
234  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
235  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/AbstractDocumentType.html0000644000175000017500000004147710242117624023531 0ustar ebourgebourg AbstractDocumentType xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.io.IOException;
11  import java.io.Writer;
12  import java.util.Iterator;
13  import java.util.List;
14  
15  import org.dom4j.DocumentType;
16  import org.dom4j.Element;
17  import org.dom4j.Visitor;
18  
19  /***
20   * <p>
21   * <code>AbstractDocumentType</code> is an abstract base class for tree
22   * implementors to use for implementation inheritence.
23   * </p>
24   * 
25   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
26   * @version $Revision: 1.17 $
27   */
28  public abstract class AbstractDocumentType extends AbstractNode implements
29          DocumentType {
30      public AbstractDocumentType() {
31      }
32  
33      public short getNodeType() {
34          return DOCUMENT_TYPE_NODE;
35      }
36  
37      public String getName() {
38          return getElementName();
39      }
40  
41      public void setName(String name) {
42          setElementName(name);
43      }
44  
45      public String getPath(Element context) {
46          // not available in XPath
47          return "";
48      }
49  
50      public String getUniquePath(Element context) {
51          // not available in XPath
52          return "";
53      }
54  
55      /***
56       * Returns the text format of the declarations if applicable, or the empty
57       * String
58       * 
59       * @return DOCUMENT ME!
60       */
61      public String getText() {
62          List list = getInternalDeclarations();
63  
64          if ((list != null) && (list.size() > 0)) {
65              StringBuffer buffer = new StringBuffer();
66              Iterator iter = list.iterator();
67  
68              if (iter.hasNext()) {
69                  Object decl = iter.next();
70                  buffer.append(decl.toString());
71  
72                  while (iter.hasNext()) {
73                      decl = iter.next();
74                      buffer.append("\n");
75                      buffer.append(decl.toString());
76                  }
77              }
78  
79              return buffer.toString();
80          }
81  
82          return "";
83      }
84  
85      public String toString() {
86          return super.toString() + " [DocumentType: " + asXML() + "]";
87      }
88  
89      public String asXML() {
90          StringBuffer buffer = new StringBuffer("<!DOCTYPE ");
91          buffer.append(getElementName());
92  
93          boolean hasPublicID = false;
94          String publicID = getPublicID();
95  
96          if ((publicID != null) && (publicID.length() > 0)) {
97              buffer.append(" PUBLIC \"");
98              buffer.append(publicID);
99              buffer.append("\"");
100             hasPublicID = true;
101         }
102 
103         String systemID = getSystemID();
104 
105         if ((systemID != null) && (systemID.length() > 0)) {
106             if (!hasPublicID) {
107                 buffer.append(" SYSTEM");
108             }
109 
110             buffer.append(" \"");
111             buffer.append(systemID);
112             buffer.append("\"");
113         }
114 
115         buffer.append(">");
116 
117         return buffer.toString();
118     }
119 
120     public void write(Writer writer) throws IOException {
121         writer.write("<!DOCTYPE ");
122         writer.write(getElementName());
123 
124         boolean hasPublicID = false;
125         String publicID = getPublicID();
126 
127         if ((publicID != null) && (publicID.length() > 0)) {
128             writer.write(" PUBLIC \"");
129             writer.write(publicID);
130             writer.write("\"");
131             hasPublicID = true;
132         }
133 
134         String systemID = getSystemID();
135 
136         if ((systemID != null) && (systemID.length() > 0)) {
137             if (!hasPublicID) {
138                 writer.write(" SYSTEM");
139             }
140 
141             writer.write(" \"");
142             writer.write(systemID);
143             writer.write("\"");
144         }
145 
146         List list = getInternalDeclarations();
147 
148         if ((list != null) && (list.size() > 0)) {
149             writer.write(" [");
150 
151             for (Iterator iter = list.iterator(); iter.hasNext();) {
152                 Object decl = iter.next();
153                 writer.write("\n  ");
154                 writer.write(decl.toString());
155             }
156 
157             writer.write("\n]");
158         }
159 
160         writer.write(">");
161     }
162 
163     public void accept(Visitor visitor) {
164         visitor.visit(this);
165     }
166 }
167 
168 /*
169  * Redistribution and use of this software and associated documentation
170  * ("Software"), with or without modification, are permitted provided that the
171  * following conditions are met:
172  * 
173  * 1. Redistributions of source code must retain copyright statements and
174  * notices. Redistributions must also contain a copy of this document.
175  * 
176  * 2. Redistributions in binary form must reproduce the above copyright notice,
177  * this list of conditions and the following disclaimer in the documentation
178  * and/or other materials provided with the distribution.
179  * 
180  * 3. The name "DOM4J" must not be used to endorse or promote products derived
181  * from this Software without prior written permission of MetaStuff, Ltd. For
182  * written permission, please contact dom4j-info@metastuff.com.
183  * 
184  * 4. Products derived from this Software may not be called "DOM4J" nor may
185  * "DOM4J" appear in their names without prior written permission of MetaStuff,
186  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
187  * 
188  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
189  * 
190  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
191  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
192  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
193  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
194  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
195  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
196  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
197  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
198  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
199  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
200  * POSSIBILITY OF SUCH DAMAGE.
201  * 
202  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
203  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/DefaultProcessingInstruction.html0000644000175000017500000003115110242117723025274 0ustar ebourgebourg DefaultProcessingInstruction xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.util.Map;
11  
12  import org.dom4j.Element;
13  
14  /***
15   * <p>
16   * <code>DefaultProcessingInstruction</code> is the default Processing
17   * Instruction implementation. It is a doubly linked node which supports the
18   * parent relationship and can be modified in place.
19   * </p>
20   * 
21   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
22   * @version $Revision: 1.13 $
23   */
24  public class DefaultProcessingInstruction extends
25          org.dom4j.tree.FlyweightProcessingInstruction {
26      /*** The parent of this node */
27      private Element parent;
28  
29      /***
30       * <p>
31       * This will create a new PI with the given target and values
32       * </p>
33       * 
34       * @param target
35       *            is the name of the PI
36       * @param values
37       *            is the <code>Map</code> values for the PI
38       */
39      public DefaultProcessingInstruction(String target, Map values) {
40          super(target, values);
41      }
42  
43      /***
44       * <p>
45       * This will create a new PI with the given target and values
46       * </p>
47       * 
48       * @param target
49       *            is the name of the PI
50       * @param values
51       *            is the values for the PI
52       */
53      public DefaultProcessingInstruction(String target, String values) {
54          super(target, values);
55      }
56  
57      /***
58       * <p>
59       * This will create a new PI with the given target and values
60       * </p>
61       * 
62       * @param parent
63       *            is the parent element
64       * @param target
65       *            is the name of the PI
66       * @param values
67       *            is the values for the PI
68       */
69      public DefaultProcessingInstruction(Element parent, String target,
70              String values) {
71          super(target, values);
72          this.parent = parent;
73      }
74  
75      public void setTarget(String target) {
76          this.target = target;
77      }
78  
79      public void setText(String text) {
80          this.text = text;
81          this.values = parseValues(text);
82      }
83  
84      public void setValues(Map values) {
85          this.values = values;
86          this.text = toString(values);
87      }
88  
89      public void setValue(String name, String value) {
90          values.put(name, value);
91      }
92  
93      public Element getParent() {
94          return parent;
95      }
96  
97      public void setParent(Element parent) {
98          this.parent = parent;
99      }
100 
101     public boolean supportsParent() {
102         return true;
103     }
104 
105     public boolean isReadOnly() {
106         return false;
107     }
108 }
109 
110 /*
111  * Redistribution and use of this software and associated documentation
112  * ("Software"), with or without modification, are permitted provided that the
113  * following conditions are met:
114  * 
115  * 1. Redistributions of source code must retain copyright statements and
116  * notices. Redistributions must also contain a copy of this document.
117  * 
118  * 2. Redistributions in binary form must reproduce the above copyright notice,
119  * this list of conditions and the following disclaimer in the documentation
120  * and/or other materials provided with the distribution.
121  * 
122  * 3. The name "DOM4J" must not be used to endorse or promote products derived
123  * from this Software without prior written permission of MetaStuff, Ltd. For
124  * written permission, please contact dom4j-info@metastuff.com.
125  * 
126  * 4. Products derived from this Software may not be called "DOM4J" nor may
127  * "DOM4J" appear in their names without prior written permission of MetaStuff,
128  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
129  * 
130  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
131  * 
132  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
133  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
134  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
135  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
136  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
137  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
138  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
139  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
140  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
141  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
142  * POSSIBILITY OF SUCH DAMAGE.
143  * 
144  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
145  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/DefaultDocumentType.html0000644000175000017500000003501510242117571023342 0ustar ebourgebourg DefaultDocumentType xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.util.List;
11  
12  /***
13   * <p>
14   * <code>DefaultDocumentType</code> is the DOM4J default implementation of an
15   * XML document type.
16   * </p>
17   * 
18   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
19   * @version $Revision: 1.10 $
20   */
21  public class DefaultDocumentType extends AbstractDocumentType {
22      /*** The root element name of the document typ */
23      protected String elementName;
24  
25      /*** Holds value of property publicID. */
26      private String publicID;
27  
28      /*** Holds value of property systemID. */
29      private String systemID;
30  
31      /*** The internal DTD declarations */
32      private List internalDeclarations;
33  
34      /*** The external DTD declarations */
35      private List externalDeclarations;
36  
37      public DefaultDocumentType() {
38      }
39  
40      /***
41       * <p>
42       * This will create a new <code>DocumentType</code> with a reference to
43       * the external DTD
44       * </p>
45       * 
46       * @param elementName
47       *            is the root element name of the document type
48       * @param systemID
49       *            is the system ID of the external DTD
50       */
51      public DefaultDocumentType(String elementName, String systemID) {
52          this.elementName = elementName;
53          this.systemID = systemID;
54      }
55  
56      /***
57       * <p>
58       * This will create a new <code>DocumentType</code> with a reference to
59       * the external DTD
60       * </p>
61       * 
62       * @param elementName
63       *            is the root element name of the document type
64       * @param publicID
65       *            is the public ID of the DTD
66       * @param systemID
67       *            is the system ID of the DTD
68       */
69      public DefaultDocumentType(String elementName, String publicID,
70              String systemID) {
71          this.elementName = elementName;
72          this.publicID = publicID;
73          this.systemID = systemID;
74      }
75  
76      public String getElementName() {
77          return elementName;
78      }
79  
80      public void setElementName(String elementName) {
81          this.elementName = elementName;
82      }
83  
84      /***
85       * DOCUMENT ME!
86       * 
87       * @return the public ID of the document type
88       */
89      public String getPublicID() {
90          return publicID;
91      }
92  
93      /***
94       * Sets the public ID of the document type
95       * 
96       * @param publicID
97       *            DOCUMENT ME!
98       */
99      public void setPublicID(String publicID) {
100         this.publicID = publicID;
101     }
102 
103     /***
104      * DOCUMENT ME!
105      * 
106      * @return the system ID of the document type
107      */
108     public String getSystemID() {
109         return systemID;
110     }
111 
112     /***
113      * Sets the system ID of the document type
114      * 
115      * @param systemID
116      *            DOCUMENT ME!
117      */
118     public void setSystemID(String systemID) {
119         this.systemID = systemID;
120     }
121 
122     public List getInternalDeclarations() {
123         return internalDeclarations;
124     }
125 
126     public void setInternalDeclarations(List internalDeclarations) {
127         this.internalDeclarations = internalDeclarations;
128     }
129 
130     public List getExternalDeclarations() {
131         return externalDeclarations;
132     }
133 
134     public void setExternalDeclarations(List externalDeclarations) {
135         this.externalDeclarations = externalDeclarations;
136     }
137 }
138 
139 /*
140  * Redistribution and use of this software and associated documentation
141  * ("Software"), with or without modification, are permitted provided that the
142  * following conditions are met:
143  * 
144  * 1. Redistributions of source code must retain copyright statements and
145  * notices. Redistributions must also contain a copy of this document.
146  * 
147  * 2. Redistributions in binary form must reproduce the above copyright notice,
148  * this list of conditions and the following disclaimer in the documentation
149  * and/or other materials provided with the distribution.
150  * 
151  * 3. The name "DOM4J" must not be used to endorse or promote products derived
152  * from this Software without prior written permission of MetaStuff, Ltd. For
153  * written permission, please contact dom4j-info@metastuff.com.
154  * 
155  * 4. Products derived from this Software may not be called "DOM4J" nor may
156  * "DOM4J" appear in their names without prior written permission of MetaStuff,
157  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
158  * 
159  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
160  * 
161  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
162  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
163  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
164  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
165  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
166  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
167  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
168  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
169  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
170  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
171  * POSSIBILITY OF SUCH DAMAGE.
172  * 
173  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
174  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/AbstractNode.html0000644000175000017500000005614010242117702021764 0ustar ebourgebourg AbstractNode xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.io.IOException;
11  import java.io.Serializable;
12  import java.io.Writer;
13  import java.util.List;
14  
15  import org.dom4j.Document;
16  import org.dom4j.DocumentFactory;
17  import org.dom4j.Element;
18  import org.dom4j.Node;
19  import org.dom4j.NodeFilter;
20  import org.dom4j.XPath;
21  import org.dom4j.rule.Pattern;
22  
23  /***
24   * <p>
25   * <code>AbstractNode</code> is an abstract base class for tree implementors
26   * to use for implementation inheritence.
27   * </p>
28   * 
29   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
30   * @version $Revision: 1.31 $
31   */
32  public abstract class AbstractNode implements Node, Cloneable, Serializable {
33      protected static final String[] NODE_TYPE_NAMES = {"Node", "Element",
34              "Attribute", "Text", "CDATA", "Entity", "Entity",
35              "ProcessingInstruction", "Comment", "Document", "DocumentType",
36              "DocumentFragment", "Notation", "Namespace", "Unknown" };
37  
38      /*** The <code>DocumentFactory</code> instance used by default */
39      private static final DocumentFactory DOCUMENT_FACTORY = DocumentFactory
40              .getInstance();
41  
42      public AbstractNode() {
43      }
44  
45      public short getNodeType() {
46          return UNKNOWN_NODE;
47      }
48  
49      public String getNodeTypeName() {
50          int type = getNodeType();
51  
52          if ((type < 0) || (type >= NODE_TYPE_NAMES.length)) {
53              return "Unknown";
54          }
55  
56          return NODE_TYPE_NAMES[type];
57      }
58  
59      public Document getDocument() {
60          Element element = getParent();
61  
62          return (element != null) ? element.getDocument() : null;
63      }
64  
65      public void setDocument(Document document) {
66      }
67  
68      public Element getParent() {
69          return null;
70      }
71  
72      public void setParent(Element parent) {
73      }
74  
75      public boolean supportsParent() {
76          return false;
77      }
78  
79      public boolean isReadOnly() {
80          return true;
81      }
82  
83      public boolean hasContent() {
84          return false;
85      }
86  
87      public String getPath() {
88          return getPath(null);
89      }
90  
91      public String getUniquePath() {
92          return getUniquePath(null);
93      }
94  
95      public Object clone() {
96          if (isReadOnly()) {
97              return this;
98          } else {
99              try {
100                 Node answer = (Node) super.clone();
101                 answer.setParent(null);
102                 answer.setDocument(null);
103 
104                 return answer;
105             } catch (CloneNotSupportedException e) {
106                 // should never happen
107                 throw new RuntimeException("This should never happen. Caught: "
108                         + e);
109             }
110         }
111     }
112 
113     public Node detach() {
114         Element parent = getParent();
115 
116         if (parent != null) {
117             parent.remove(this);
118         } else {
119             Document document = getDocument();
120 
121             if (document != null) {
122                 document.remove(this);
123             }
124         }
125 
126         setParent(null);
127         setDocument(null);
128 
129         return this;
130     }
131 
132     public String getName() {
133         return null;
134     }
135 
136     public void setName(String name) {
137         throw new UnsupportedOperationException("This node cannot be modified");
138     }
139 
140     public String getText() {
141         return null;
142     }
143 
144     public String getStringValue() {
145         return getText();
146     }
147 
148     public void setText(String text) {
149         throw new UnsupportedOperationException("This node cannot be modified");
150     }
151 
152     public void write(Writer writer) throws IOException {
153         writer.write(asXML());
154     }
155 
156     // XPath methods
157     public Object selectObject(String xpathExpression) {
158         XPath xpath = createXPath(xpathExpression);
159 
160         return xpath.evaluate(this);
161     }
162 
163     public List selectNodes(String xpathExpression) {
164         XPath xpath = createXPath(xpathExpression);
165 
166         return xpath.selectNodes(this);
167     }
168 
169     public List selectNodes(String xpathExpression,
170             String comparisonXPathExpression) {
171         return selectNodes(xpathExpression, comparisonXPathExpression, false);
172     }
173 
174     public List selectNodes(String xpathExpression,
175             String comparisonXPathExpression, boolean removeDuplicates) {
176         XPath xpath = createXPath(xpathExpression);
177         XPath sortBy = createXPath(comparisonXPathExpression);
178 
179         return xpath.selectNodes(this, sortBy, removeDuplicates);
180     }
181 
182     public Node selectSingleNode(String xpathExpression) {
183         XPath xpath = createXPath(xpathExpression);
184 
185         return xpath.selectSingleNode(this);
186     }
187 
188     public String valueOf(String xpathExpression) {
189         XPath xpath = createXPath(xpathExpression);
190 
191         return xpath.valueOf(this);
192     }
193 
194     public Number numberValueOf(String xpathExpression) {
195         XPath xpath = createXPath(xpathExpression);
196 
197         return xpath.numberValueOf(this);
198     }
199 
200     public boolean matches(String patternText) {
201         NodeFilter filter = createXPathFilter(patternText);
202 
203         return filter.matches(this);
204     }
205 
206     public XPath createXPath(String xpathExpression) {
207         return getDocumentFactory().createXPath(xpathExpression);
208     }
209 
210     public NodeFilter createXPathFilter(String patternText) {
211         return getDocumentFactory().createXPathFilter(patternText);
212     }
213 
214     public Pattern createPattern(String patternText) {
215         return getDocumentFactory().createPattern(patternText);
216     }
217 
218     public Node asXPathResult(Element parent) {
219         if (supportsParent()) {
220             return this;
221         }
222 
223         return createXPathResult(parent);
224     }
225 
226     protected DocumentFactory getDocumentFactory() {
227         return DOCUMENT_FACTORY;
228     }
229 
230     protected Node createXPathResult(Element parent) {
231         throw new RuntimeException("asXPathResult() not yet implemented fully "
232                 + "for: " + this);
233     }
234 }
235 
236 /*
237  * Redistribution and use of this software and associated documentation
238  * ("Software"), with or without modification, are permitted provided that the
239  * following conditions are met:
240  * 
241  * 1. Redistributions of source code must retain copyright statements and
242  * notices. Redistributions must also contain a copy of this document.
243  * 
244  * 2. Redistributions in binary form must reproduce the above copyright notice,
245  * this list of conditions and the following disclaimer in the documentation
246  * and/or other materials provided with the distribution.
247  * 
248  * 3. The name "DOM4J" must not be used to endorse or promote products derived
249  * from this Software without prior written permission of MetaStuff, Ltd. For
250  * written permission, please contact dom4j-info@metastuff.com.
251  * 
252  * 4. Products derived from this Software may not be called "DOM4J" nor may
253  * "DOM4J" appear in their names without prior written permission of MetaStuff,
254  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
255  * 
256  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
257  * 
258  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
259  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
260  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
261  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
262  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
263  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
264  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
265  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
266  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
267  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
268  * POSSIBILITY OF SUCH DAMAGE.
269  * 
270  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
271  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/tree/AbstractDocument.html0000644000175000017500000006201610242117712022655 0ustar ebourgebourg AbstractDocument xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.tree;
9   
10  import java.io.IOException;
11  import java.io.StringWriter;
12  import java.io.Writer;
13  import java.util.Iterator;
14  import java.util.List;
15  import java.util.Map;
16  
17  import org.dom4j.Comment;
18  import org.dom4j.Document;
19  import org.dom4j.DocumentType;
20  import org.dom4j.Element;
21  import org.dom4j.IllegalAddException;
22  import org.dom4j.Node;
23  import org.dom4j.ProcessingInstruction;
24  import org.dom4j.QName;
25  import org.dom4j.Text;
26  import org.dom4j.Visitor;
27  import org.dom4j.io.OutputFormat;
28  import org.dom4j.io.XMLWriter;
29  
30  /***
31   * <p>
32   * <code>AbstractDocument</code> is an abstract base class for tree
33   * implementors to use for implementation inheritence.
34   * </p>
35   * 
36   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
37   * @version $Revision: 1.33 $
38   */
39  public abstract class AbstractDocument extends AbstractBranch implements
40          Document {
41  
42      /*** The encoding of this document as stated in the XML declaration */
43      protected String encoding;
44  
45      public AbstractDocument() {
46      }
47  
48      public short getNodeType() {
49          return DOCUMENT_NODE;
50      }
51  
52      public String getPath(Element context) {
53          return "/";
54      }
55  
56      public String getUniquePath(Element context) {
57          return "/";
58      }
59  
60      public Document getDocument() {
61          return this;
62      }
63  
64      public String getXMLEncoding() {
65          return null;
66      }
67  
68      public String getStringValue() {
69          Element root = getRootElement();
70  
71          return (root != null) ? root.getStringValue() : "";
72      }
73  
74      public String asXML() {
75          OutputFormat format = new OutputFormat();
76          format.setEncoding(encoding);
77          
78          try {
79              StringWriter out = new StringWriter();
80              XMLWriter writer = new XMLWriter(out, format);
81              writer.write(this);
82              writer.flush();
83  
84              return out.toString();
85          } catch (IOException e) {
86              throw new RuntimeException("IOException while generating textual "
87                      + "representation: " + e.getMessage());
88          }
89      }
90  
91      public void write(Writer out) throws IOException {
92          OutputFormat format = new OutputFormat();
93          format.setEncoding(encoding);
94          
95          XMLWriter writer = new XMLWriter(out, format);
96          writer.write(this);
97      }
98  
99      /***
100      * <p>
101      * <code>accept</code> method is the <code>Visitor Pattern</code>
102      * method.
103      * </p>
104      * 
105      * @param visitor
106      *            <code>Visitor</code> is the visitor.
107      */
108     public void accept(Visitor visitor) {
109         visitor.visit(this);
110 
111         DocumentType docType = getDocType();
112 
113         if (docType != null) {
114             visitor.visit(docType);
115         }
116 
117         // visit content
118         List content = content();
119 
120         if (content != null) {
121             for (Iterator iter = content.iterator(); iter.hasNext();) {
122                 Object object = iter.next();
123 
124                 if (object instanceof String) {
125                     Text text = getDocumentFactory()
126                             .createText((String) object);
127                     visitor.visit(text);
128                 } else {
129                     Node node = (Node) object;
130                     node.accept(visitor);
131                 }
132             }
133         }
134     }
135 
136     public String toString() {
137         return super.toString() + " [Document: name " + getName() + "]";
138     }
139 
140     public void normalize() {
141         Element element = getRootElement();
142 
143         if (element != null) {
144             element.normalize();
145         }
146     }
147 
148     public Document addComment(String comment) {
149         Comment node = getDocumentFactory().createComment(comment);
150         add(node);
151 
152         return this;
153     }
154 
155     public Document addProcessingInstruction(String target, String data) {
156         ProcessingInstruction node = getDocumentFactory()
157                 .createProcessingInstruction(target, data);
158         add(node);
159 
160         return this;
161     }
162 
163     public Document addProcessingInstruction(String target, Map data) {
164         ProcessingInstruction node = getDocumentFactory()
165                 .createProcessingInstruction(target, data);
166         add(node);
167 
168         return this;
169     }
170 
171     public Element addElement(String name) {
172         Element element = getDocumentFactory().createElement(name);
173         add(element);
174 
175         return element;
176     }
177 
178     public Element addElement(String qualifiedName, String namespaceURI) {
179         Element element = getDocumentFactory().createElement(qualifiedName,
180                 namespaceURI);
181         add(element);
182 
183         return element;
184     }
185 
186     public Element addElement(QName qName) {
187         Element element = getDocumentFactory().createElement(qName);
188         add(element);
189 
190         return element;
191     }
192 
193     public void setRootElement(Element rootElement) {
194         clearContent();
195 
196         if (rootElement != null) {
197             super.add(rootElement);
198             rootElementAdded(rootElement);
199         }
200     }
201 
202     public void add(Element element) {
203         checkAddElementAllowed(element);
204         super.add(element);
205         rootElementAdded(element);
206     }
207 
208     public boolean remove(Element element) {
209         boolean answer = super.remove(element);
210         Element root = getRootElement();
211 
212         if ((root != null) && answer) {
213             setRootElement(null);
214         }
215 
216         element.setDocument(null);
217 
218         return answer;
219     }
220 
221     public Node asXPathResult(Element parent) {
222         return this;
223     }
224 
225     protected void childAdded(Node node) {
226         if (node != null) {
227             node.setDocument(this);
228         }
229     }
230 
231     protected void childRemoved(Node node) {
232         if (node != null) {
233             node.setDocument(null);
234         }
235     }
236 
237     protected void checkAddElementAllowed(Element element) {
238         Element root = getRootElement();
239 
240         if (root != null) {
241             throw new IllegalAddException(this, element,
242                     "Cannot add another element to this "
243                             + "Document as it already has a root "
244                             + "element of: " + root.getQualifiedName());
245         }
246     }
247 
248     /***
249      * Called to set the root element variable
250      * 
251      * @param rootElement
252      *            DOCUMENT ME!
253      */
254     protected abstract void rootElementAdded(Element rootElement);
255 
256     public void setXMLEncoding(String enc) {
257         this.encoding = enc;
258     }
259 }
260 
261 /*
262  * Redistribution and use of this software and associated documentation
263  * ("Software"), with or without modification, are permitted provided that the
264  * following conditions are met:
265  * 
266  * 1. Redistributions of source code must retain copyright statements and
267  * notices. Redistributions must also contain a copy of this document.
268  * 
269  * 2. Redistributions in binary form must reproduce the above copyright notice,
270  * this list of conditions and the following disclaimer in the documentation
271  * and/or other materials provided with the distribution.
272  * 
273  * 3. The name "DOM4J" must not be used to endorse or promote products derived
274  * from this Software without prior written permission of MetaStuff, Ltd. For
275  * written permission, please contact dom4j-info@metastuff.com.
276  * 
277  * 4. Products derived from this Software may not be called "DOM4J" nor may
278  * "DOM4J" appear in their names without prior written permission of MetaStuff,
279  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
280  * 
281  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
282  * 
283  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
284  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
285  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
286  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
287  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
288  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
289  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
290  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
291  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
292  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
293  * POSSIBILITY OF SUCH DAMAGE.
294  * 
295  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
296  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/swing/0000755000175000017500000000000012133227266016717 5ustar ebourgebourgdom4j-1.6.1/docs/xref/org/dom4j/swing/XMLTableModel.html0000644000175000017500000004222310242117705022174 0ustar ebourgebourg XMLTableModel xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.swing;
9   
10  import java.util.List;
11  
12  import javax.swing.table.AbstractTableModel;
13  
14  import org.dom4j.Document;
15  import org.dom4j.Element;
16  import org.dom4j.XPath;
17  
18  /***
19   * <p>
20   * <code>XMLTableDefinition</code> repro.
21   * </p>
22   * 
23   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
24   * @version $Revision: 1.8 $
25   */
26  public class XMLTableModel extends AbstractTableModel {
27      /*** Holds value of property definition. */
28      private XMLTableDefinition definition;
29  
30      /*** Holds value of property source. */
31      private Object source;
32  
33      /*** The rows evaluated from the row XPath expression */
34      private List rows;
35  
36      /***
37       * Creates a TableModel from an XML table definition document and an XML
38       * source
39       * 
40       * @param tableDefinition
41       *            DOCUMENT ME!
42       * @param source
43       *            DOCUMENT ME!
44       */
45      public XMLTableModel(Element tableDefinition, Object source) {
46          this(XMLTableDefinition.load(tableDefinition), source);
47      }
48  
49      /***
50       * Creates a TableModel from an XML table definition document and an XML
51       * source
52       * 
53       * @param tableDefinition
54       *            DOCUMENT ME!
55       * @param source
56       *            DOCUMENT ME!
57       */
58      public XMLTableModel(Document tableDefinition, Object source) {
59          this(XMLTableDefinition.load(tableDefinition), source);
60      }
61  
62      public XMLTableModel(XMLTableDefinition definition, Object source) {
63          this.definition = definition;
64          this.source = source;
65      }
66  
67      public Object getRowValue(int rowIndex) {
68          return getRows().get(rowIndex);
69      }
70  
71      public List getRows() {
72          if (rows == null) {
73              rows = definition.getRowXPath().selectNodes(source);
74          }
75  
76          return rows;
77      }
78  
79      // TableModel interface
80      // -------------------------------------------------------------------------
81      public Class getColumnClass(int columnIndex) {
82          return definition.getColumnClass(columnIndex);
83      }
84  
85      public int getColumnCount() {
86          return definition.getColumnCount();
87      }
88  
89      public String getColumnName(int columnIndex) {
90          XPath xpath = definition.getColumnNameXPath(columnIndex);
91  
92          if (xpath != null) {
93              System.out.println("Evaluating column xpath: " + xpath + " value: "
94                      + xpath.valueOf(source));
95  
96              return xpath.valueOf(source);
97          }
98  
99          return definition.getColumnName(columnIndex);
100     }
101 
102     public Object getValueAt(int rowIndex, int columnIndex) {
103         try {
104             Object row = getRowValue(rowIndex);
105 
106             return definition.getValueAt(row, columnIndex);
107         } catch (Exception e) {
108             handleException(e);
109 
110             return null;
111         }
112     }
113 
114     public int getRowCount() {
115         return getRows().size();
116     }
117 
118     // Properties
119     // -------------------------------------------------------------------------
120 
121     /***
122      * Getter for property definition.
123      * 
124      * @return Value of property definition.
125      */
126     public XMLTableDefinition getDefinition() {
127         return definition;
128     }
129 
130     /***
131      * Setter for property definition.
132      * 
133      * @param definition
134      *            New value of property definition.
135      */
136     public void setDefinition(XMLTableDefinition definition) {
137         this.definition = definition;
138     }
139 
140     /***
141      * Getter for the XML source, which is usually a Node or List of nodes.
142      * 
143      * @return Value of property source.
144      */
145     public Object getSource() {
146         return source;
147     }
148 
149     /***
150      * Setter for the XML source, which is usually a Node or List of nodes.
151      * 
152      * @param source
153      *            New value of property source.
154      */
155     public void setSource(Object source) {
156         this.source = source;
157         this.rows = null;
158     }
159 
160     // Implementation methods
161     // -------------------------------------------------------------------------
162     protected void handleException(Exception e) {
163         // #### should use jakarta commons-logging
164         System.out.println("Caught: " + e);
165     }
166 }
167 
168 /*
169  * Redistribution and use of this software and associated documentation
170  * ("Software"), with or without modification, are permitted provided that the
171  * following conditions are met:
172  * 
173  * 1. Redistributions of source code must retain copyright statements and
174  * notices. Redistributions must also contain a copy of this document.
175  * 
176  * 2. Redistributions in binary form must reproduce the above copyright notice,
177  * this list of conditions and the following disclaimer in the documentation
178  * and/or other materials provided with the distribution.
179  * 
180  * 3. The name "DOM4J" must not be used to endorse or promote products derived
181  * from this Software without prior written permission of MetaStuff, Ltd. For
182  * written permission, please contact dom4j-info@metastuff.com.
183  * 
184  * 4. Products derived from this Software may not be called "DOM4J" nor may
185  * "DOM4J" appear in their names without prior written permission of MetaStuff,
186  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
187  * 
188  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
189  * 
190  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
191  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
192  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
193  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
194  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
195  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
196  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
197  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
198  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
199  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
200  * POSSIBILITY OF SUCH DAMAGE.
201  * 
202  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
203  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/swing/package-summary.html0000644000175000017500000000553510242117715022677 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.swing

Class Summary
BranchTreeNode
DocumentTreeModel
LeafTreeNode
XMLTableColumnDefinition
XMLTableDefinition
XMLTableModel
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref/org/dom4j/swing/DocumentTreeModel.html0000644000175000017500000002226410242117722023164 0ustar ebourgebourg DocumentTreeModel xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.swing;
9   
10  import javax.swing.tree.DefaultTreeModel;
11  
12  import org.dom4j.Document;
13  
14  /***
15   * <p>
16   * <code>DocumentTreeModel</code> implements a Swing TreeModel for a dom4j XML
17   * Document.
18   * </p>
19   * 
20   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
21   * @author Jakob Jenkov
22   * @version $Revision: 1.7 $
23   */
24  public class DocumentTreeModel extends DefaultTreeModel {
25      /*** The document for this model */
26      protected Document document;
27  
28      public DocumentTreeModel(Document document) {
29          super(new BranchTreeNode(document));
30          this.document = document;
31      }
32  
33      // Properties
34      // -------------------------------------------------------------------------
35  
36      /***
37       * DOCUMENT ME!
38       * 
39       * @return the <code>Document</code> instance that this
40       *         <code>TreeModel</code> is based on
41       */
42      public Document getDocument() {
43          return document;
44      }
45  
46      /***
47       * Sets the <code>Document</code> instance that this
48       * <code>TreeModel</code> is based on
49       * 
50       * @param document
51       *            DOCUMENT ME!
52       */
53      public void setDocument(Document document) {
54          this.document = document;
55          setRoot(new BranchTreeNode(document));
56      }
57  }
58  
59  /*
60   * Redistribution and use of this software and associated documentation
61   * ("Software"), with or without modification, are permitted provided that the
62   * following conditions are met:
63   * 
64   * 1. Redistributions of source code must retain copyright statements and
65   * notices. Redistributions must also contain a copy of this document.
66   * 
67   * 2. Redistributions in binary form must reproduce the above copyright notice,
68   * this list of conditions and the following disclaimer in the documentation
69   * and/or other materials provided with the distribution.
70   * 
71   * 3. The name "DOM4J" must not be used to endorse or promote products derived
72   * from this Software without prior written permission of MetaStuff, Ltd. For
73   * written permission, please contact dom4j-info@metastuff.com.
74   * 
75   * 4. Products derived from this Software may not be called "DOM4J" nor may
76   * "DOM4J" appear in their names without prior written permission of MetaStuff,
77   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
78   * 
79   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
80   * 
81   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
82   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
83   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
84   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
85   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
86   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
87   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
88   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
89   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
90   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
91   * POSSIBILITY OF SUCH DAMAGE.
92   * 
93   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
94   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/swing/package-frame.html0000644000175000017500000000247310242117716022273 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.swing

org.dom4j.swing

Classes

  • BranchTreeNode
  • DocumentTreeModel
  • LeafTreeNode
  • XMLTableColumnDefinition
  • XMLTableDefinition
  • XMLTableModel
dom4j-1.6.1/docs/xref/org/dom4j/swing/BranchTreeNode.html0000644000175000017500000004076510242117706022440 0ustar ebourgebourg BranchTreeNode xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.swing;
9   
10  import java.util.ArrayList;
11  import java.util.Enumeration;
12  import java.util.List;
13  
14  import javax.swing.tree.TreeNode;
15  
16  import org.dom4j.Branch;
17  import org.dom4j.CharacterData;
18  import org.dom4j.Node;
19  
20  /***
21   * <p>
22   * <code>BranchTreeNode</code> implements the Swing TreeNode interface to bind
23   * dom4j XML Branch nodes (i.e. Document and Element nodes) to a Swing
24   * TreeModel.
25   * </p>
26   * 
27   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
28   * @author Jakob Jenkov
29   * @version $Revision: 1.10 $
30   */
31  public class BranchTreeNode extends LeafTreeNode {
32      /*** Stores the child tree nodes */
33      protected List children;
34  
35      public BranchTreeNode() {
36      }
37  
38      public BranchTreeNode(Branch xmlNode) {
39          super(xmlNode);
40      }
41  
42      public BranchTreeNode(TreeNode parent, Branch xmlNode) {
43          super(parent, xmlNode);
44      }
45  
46      // TreeNode methods
47      // -------------------------------------------------------------------------
48      public Enumeration children() {
49          return new Enumeration() {
50              private int index = -1;
51  
52              public boolean hasMoreElements() {
53                  return (index + 1) < getChildCount();
54              }
55  
56              public Object nextElement() {
57                  return getChildAt(++index);
58              }
59          };
60      }
61  
62      public boolean getAllowsChildren() {
63          return true;
64      }
65  
66      public TreeNode getChildAt(int childIndex) {
67          return (TreeNode) getChildList().get(childIndex);
68      }
69  
70      public int getChildCount() {
71          return getChildList().size();
72      }
73  
74      public int getIndex(TreeNode node) {
75          return getChildList().indexOf(node);
76      }
77  
78      public boolean isLeaf() {
79          return getXmlBranch().nodeCount() <= 0;
80      }
81  
82      public String toString() {
83          return xmlNode.getName();
84      }
85  
86      // Implementation methods
87      // -------------------------------------------------------------------------
88  
89      /***
90       * Uses Lazy Initialization pattern to create a List of children
91       * 
92       * @return DOCUMENT ME!
93       */
94      protected List getChildList() {
95          // for now lets just create the children once, the first time they
96          // are asked for.
97          // XXXX - we may wish to detect inconsistencies here....
98          if (children == null) {
99              children = createChildList();
100         }
101 
102         return children;
103     }
104 
105     /***
106      * Factory method to create List of children TreeNodes
107      * 
108      * @return DOCUMENT ME!
109      */
110     protected List createChildList() {
111         // add attributes and content as children?
112         Branch branch = getXmlBranch();
113         int size = branch.nodeCount();
114         List childList = new ArrayList(size);
115 
116         for (int i = 0; i < size; i++) {
117             Node node = branch.node(i);
118 
119             // ignore whitespace text nodes
120             if (node instanceof CharacterData) {
121                 String text = node.getText();
122 
123                 if (text == null) {
124                     continue;
125                 }
126 
127                 text = text.trim();
128 
129                 if (text.length() <= 0) {
130                     continue;
131                 }
132             }
133 
134             childList.add(createChildTreeNode(node));
135         }
136 
137         return childList;
138     }
139 
140     /***
141      * Factory method to create child tree nodes for a given XML node type
142      * 
143      * @param xmlNode
144      *            DOCUMENT ME!
145      * 
146      * @return DOCUMENT ME!
147      */
148     protected TreeNode createChildTreeNode(Node xmlNode) {
149         if (xmlNode instanceof Branch) {
150             return new BranchTreeNode(this, (Branch) xmlNode);
151         } else {
152             return new LeafTreeNode(this, xmlNode);
153         }
154     }
155 
156     protected Branch getXmlBranch() {
157         return (Branch) xmlNode;
158     }
159 }
160 
161 /*
162  * Redistribution and use of this software and associated documentation
163  * ("Software"), with or without modification, are permitted provided that the
164  * following conditions are met:
165  * 
166  * 1. Redistributions of source code must retain copyright statements and
167  * notices. Redistributions must also contain a copy of this document.
168  * 
169  * 2. Redistributions in binary form must reproduce the above copyright notice,
170  * this list of conditions and the following disclaimer in the documentation
171  * and/or other materials provided with the distribution.
172  * 
173  * 3. The name "DOM4J" must not be used to endorse or promote products derived
174  * from this Software without prior written permission of MetaStuff, Ltd. For
175  * written permission, please contact dom4j-info@metastuff.com.
176  * 
177  * 4. Products derived from this Software may not be called "DOM4J" nor may
178  * "DOM4J" appear in their names without prior written permission of MetaStuff,
179  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
180  * 
181  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
182  * 
183  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
184  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
185  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
186  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
187  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
188  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
189  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
190  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
191  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
192  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
193  * POSSIBILITY OF SUCH DAMAGE.
194  * 
195  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
196  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/swing/XMLTableColumnDefinition.html0000644000175000017500000004741310242117753024413 0ustar ebourgebourg XMLTableColumnDefinition xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.swing;
9   
10  import java.io.Serializable;
11  
12  import org.dom4j.DocumentHelper;
13  import org.dom4j.Node;
14  import org.dom4j.XPath;
15  
16  /***
17   * <p>
18   * <code>XMLTableColumnDefinition</code> a column within a table definition.
19   * </p>
20   * 
21   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
22   * @version $Revision: 1.10 $
23   */
24  public class XMLTableColumnDefinition implements Serializable {
25      public static final int OBJECT_TYPE = 0;
26  
27      public static final int STRING_TYPE = 1;
28  
29      public static final int NUMBER_TYPE = 2;
30  
31      public static final int NODE_TYPE = 3;
32  
33      /*** Holds value of property type. */
34      private int type;
35  
36      /*** Holds value of property name. */
37      private String name;
38  
39      /*** Holds value of property xpath. */
40      private XPath xpath;
41  
42      /*** Holds the XPath used for the column name */
43      private XPath columnNameXPath;
44  
45      public XMLTableColumnDefinition() {
46      }
47  
48      public XMLTableColumnDefinition(String name, String expression, int type) {
49          this.name = name;
50          this.type = type;
51          this.xpath = createXPath(expression);
52      }
53  
54      public XMLTableColumnDefinition(String name, XPath xpath, int type) {
55          this.name = name;
56          this.xpath = xpath;
57          this.type = type;
58      }
59  
60      public XMLTableColumnDefinition(XPath columnXPath, XPath xpath, int type) {
61          this.xpath = xpath;
62          this.columnNameXPath = columnXPath;
63          this.type = type;
64      }
65  
66      public static int parseType(String typeName) {
67          if ((typeName != null) && (typeName.length() > 0)) {
68              if (typeName.equals("string")) {
69                  return STRING_TYPE;
70              } else if (typeName.equals("number")) {
71                  return NUMBER_TYPE;
72              } else if (typeName.equals("node")) {
73                  return NODE_TYPE;
74              }
75          }
76  
77          return OBJECT_TYPE;
78      }
79  
80      public Class getColumnClass() {
81          switch (type) {
82              case STRING_TYPE:
83                  return String.class;
84  
85              case NUMBER_TYPE:
86                  return Number.class;
87  
88              case NODE_TYPE:
89                  return Node.class;
90  
91              default:
92                  return Object.class;
93          }
94      }
95  
96      public Object getValue(Object row) {
97          switch (type) {
98              case STRING_TYPE:
99                  return xpath.valueOf(row);
100 
101             case NUMBER_TYPE:
102                 return xpath.numberValueOf(row);
103 
104             case NODE_TYPE:
105                 return xpath.selectSingleNode(row);
106 
107             default:
108                 return xpath.evaluate(row);
109         }
110     }
111 
112     // Properties
113     // -------------------------------------------------------------------------
114 
115     /***
116      * Getter for property type.
117      * 
118      * @return Value of property type.
119      */
120     public int getType() {
121         return type;
122     }
123 
124     /***
125      * Setter for property type.
126      * 
127      * @param type
128      *            New value of property type.
129      */
130     public void setType(int type) {
131         this.type = type;
132     }
133 
134     /***
135      * Getter for property name.
136      * 
137      * @return Value of property name.
138      */
139     public String getName() {
140         return name;
141     }
142 
143     /***
144      * Setter for property name.
145      * 
146      * @param name
147      *            New value of property name.
148      */
149     public void setName(String name) {
150         this.name = name;
151     }
152 
153     /***
154      * Getter for property xpath.
155      * 
156      * @return Value of property xpath.
157      */
158     public XPath getXPath() {
159         return xpath;
160     }
161 
162     /***
163      * Setter for property xpath.
164      * 
165      * @param xPath
166      *            New value of property xpath.
167      */
168     public void setXPath(XPath xPath) {
169         this.xpath = xPath;
170     }
171 
172     /***
173      * DOCUMENT ME!
174      * 
175      * @return the XPath used to create the column name
176      */
177     public XPath getColumnNameXPath() {
178         return columnNameXPath;
179     }
180 
181     /***
182      * Setter for property columnNameXPath.
183      * 
184      * @param columnNameXPath
185      *            New value of property xpath.
186      */
187     public void setColumnNameXPath(XPath columnNameXPath) {
188         this.columnNameXPath = columnNameXPath;
189     }
190 
191     // Implementation methods
192     // -------------------------------------------------------------------------
193     protected XPath createXPath(String expression) {
194         return DocumentHelper.createXPath(expression);
195     }
196 
197     protected void handleException(Exception e) {
198         // #### should use jakarta commons-logging
199         System.out.println("Caught: " + e);
200     }
201 }
202 
203 /*
204  * Redistribution and use of this software and associated documentation
205  * ("Software"), with or without modification, are permitted provided that the
206  * following conditions are met:
207  * 
208  * 1. Redistributions of source code must retain copyright statements and
209  * notices. Redistributions must also contain a copy of this document.
210  * 
211  * 2. Redistributions in binary form must reproduce the above copyright notice,
212  * this list of conditions and the following disclaimer in the documentation
213  * and/or other materials provided with the distribution.
214  * 
215  * 3. The name "DOM4J" must not be used to endorse or promote products derived
216  * from this Software without prior written permission of MetaStuff, Ltd. For
217  * written permission, please contact dom4j-info@metastuff.com.
218  * 
219  * 4. Products derived from this Software may not be called "DOM4J" nor may
220  * "DOM4J" appear in their names without prior written permission of MetaStuff,
221  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
222  * 
223  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
224  * 
225  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
226  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
227  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
228  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
229  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
230  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
231  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
232  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
233  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
234  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
235  * POSSIBILITY OF SUCH DAMAGE.
236  * 
237  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
238  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/swing/LeafTreeNode.html0000644000175000017500000003107110242117761022101 0ustar ebourgebourg LeafTreeNode xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.swing;
9   
10  import java.util.Enumeration;
11  
12  import javax.swing.tree.TreeNode;
13  
14  import org.dom4j.Node;
15  
16  /***
17   * <p>
18   * <code>LeafTreeNode</code> implements the Swing TreeNode interface to bind a
19   * leaf XML nodes to a Swing TreeModel.
20   * </p>
21   * 
22   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
23   * @author Jakob Jenkov
24   * @version $Revision: 1.7 $
25   */
26  public class LeafTreeNode implements TreeNode {
27      protected static final Enumeration EMPTY_ENUMERATION = new Enumeration() {
28          public boolean hasMoreElements() {
29              return false;
30          }
31  
32          public Object nextElement() {
33              return null;
34          }
35      };
36  
37      /*** The parent node of this TreeNode */
38      private TreeNode parent;
39  
40      /*** The dom4j Node which contains the */
41      protected Node xmlNode;
42  
43      public LeafTreeNode() {
44      }
45  
46      public LeafTreeNode(Node xmlNode) {
47          this.xmlNode = xmlNode;
48      }
49  
50      public LeafTreeNode(TreeNode parent, Node xmlNode) {
51          this.parent = parent;
52          this.xmlNode = xmlNode;
53      }
54  
55      // TreeNode methods
56      // -------------------------------------------------------------------------
57      public Enumeration children() {
58          return EMPTY_ENUMERATION;
59      }
60  
61      public boolean getAllowsChildren() {
62          return false;
63      }
64  
65      public TreeNode getChildAt(int childIndex) {
66          return null;
67      }
68  
69      public int getChildCount() {
70          return 0;
71      }
72  
73      public int getIndex(TreeNode node) {
74          return -1;
75      }
76  
77      public TreeNode getParent() {
78          return parent;
79      }
80  
81      public boolean isLeaf() {
82          return true;
83      }
84  
85      public String toString() {
86          // should maybe do things differently based on content?
87          String text = xmlNode.getText();
88  
89          return (text != null) ? text.trim() : "";
90      }
91  
92      // Properties
93      // -------------------------------------------------------------------------
94  
95      /***
96       * Sets the parent of this node but doesn't change the parents children
97       * 
98       * @param parent
99       *            DOCUMENT ME!
100      */
101     public void setParent(LeafTreeNode parent) {
102         this.parent = parent;
103     }
104 
105     public Node getXmlNode() {
106         return xmlNode;
107     }
108 }
109 
110 /*
111  * Redistribution and use of this software and associated documentation
112  * ("Software"), with or without modification, are permitted provided that the
113  * following conditions are met:
114  * 
115  * 1. Redistributions of source code must retain copyright statements and
116  * notices. Redistributions must also contain a copy of this document.
117  * 
118  * 2. Redistributions in binary form must reproduce the above copyright notice,
119  * this list of conditions and the following disclaimer in the documentation
120  * and/or other materials provided with the distribution.
121  * 
122  * 3. The name "DOM4J" must not be used to endorse or promote products derived
123  * from this Software without prior written permission of MetaStuff, Ltd. For
124  * written permission, please contact dom4j-info@metastuff.com.
125  * 
126  * 4. Products derived from this Software may not be called "DOM4J" nor may
127  * "DOM4J" appear in their names without prior written permission of MetaStuff,
128  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
129  * 
130  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
131  * 
132  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
133  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
134  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
135  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
136  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
137  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
138  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
139  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
140  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
141  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
142  * POSSIBILITY OF SUCH DAMAGE.
143  * 
144  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
145  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/swing/XMLTableDefinition.html0000644000175000017500000006560410242117722023233 0ustar ebourgebourg XMLTableDefinition xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.swing;
9   
10  import java.io.Serializable;
11  import java.util.ArrayList;
12  import java.util.HashMap;
13  import java.util.Iterator;
14  import java.util.List;
15  import java.util.Map;
16  
17  import org.dom4j.Document;
18  import org.dom4j.DocumentHelper;
19  import org.dom4j.Element;
20  import org.dom4j.XPath;
21  
22  import org.jaxen.VariableContext;
23  
24  /***
25   * <p>
26   * <code>XMLTableDefinition</code> represents a table definition based on
27   * XPath expression evaluated on an XML document.
28   * </p>
29   * 
30   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
31   * @version $Revision: 1.8 $
32   */
33  public class XMLTableDefinition implements Serializable, VariableContext {
34      /*** Holds value of property rowXPath. */
35      private XPath rowXPath;
36  
37      /*** The columns to display in this table */
38      private List columns = new ArrayList();
39  
40      /*** integer index array cache */
41      private XMLTableColumnDefinition[] columnArray;
42  
43      /*** name index cache */
44      private Map columnNameIndex;
45  
46      /*** for cross-row variables */
47      private VariableContext variableContext;
48  
49      /*** stores the current row value for the variableContext */
50      private Object rowValue;
51  
52      public XMLTableDefinition() {
53      }
54  
55      /***
56       * Loads an XML table definition from an XML definition document
57       * 
58       * @param definition
59       *            DOCUMENT ME!
60       * 
61       * @return DOCUMENT ME!
62       */
63      public static XMLTableDefinition load(Document definition) {
64          return load(definition.getRootElement());
65      }
66  
67      /***
68       * Loads an XML table definition from an XML definition document
69       * 
70       * @param definition
71       *            DOCUMENT ME!
72       * 
73       * @return DOCUMENT ME!
74       */
75      public static XMLTableDefinition load(Element definition) {
76          XMLTableDefinition answer = new XMLTableDefinition();
77          answer.setRowExpression(definition.attributeValue("select"));
78  
79          for (Iterator iter = definition.elementIterator("column"); iter
80                  .hasNext();) {
81              Element element = (Element) iter.next();
82              String expression = element.attributeValue("select");
83              String name = element.getText();
84              String typeName = element.attributeValue("type", "string");
85              String columnXPath = element.attributeValue("columnNameXPath");
86              int type = XMLTableColumnDefinition.parseType(typeName);
87  
88              if (columnXPath != null) {
89                  answer.addColumnWithXPathName(columnXPath, expression, type);
90              } else {
91                  answer.addColumn(name, expression, type);
92              }
93          }
94  
95          return answer;
96      }
97  
98      public Class getColumnClass(int columnIndex) {
99          return getColumn(columnIndex).getColumnClass();
100     }
101 
102     public int getColumnCount() {
103         return columns.size();
104     }
105 
106     /***
107      * DOCUMENT ME!
108      * 
109      * @param columnIndex
110      *            DOCUMENT ME!
111      * 
112      * @return the static column name. This is used if there is no
113      *         columnNameXPath
114      */
115     public String getColumnName(int columnIndex) {
116         return getColumn(columnIndex).getName();
117     }
118 
119     /***
120      * DOCUMENT ME!
121      * 
122      * @param columnIndex
123      *            DOCUMENT ME!
124      * 
125      * @return the XPath expression used to evaluate the value of cells in this
126      *         column
127      */
128     public XPath getColumnXPath(int columnIndex) {
129         return getColumn(columnIndex).getXPath();
130     }
131 
132     /***
133      * DOCUMENT ME!
134      * 
135      * @param columnIndex
136      *            DOCUMENT ME!
137      * 
138      * @return the XPath expresssion used to create the column name, if there is
139      *         one or null if there is no XPath expression to name the column.
140      */
141     public XPath getColumnNameXPath(int columnIndex) {
142         return getColumn(columnIndex).getColumnNameXPath();
143     }
144 
145     public synchronized Object getValueAt(Object row, int columnIndex) {
146         XMLTableColumnDefinition column = getColumn(columnIndex);
147         Object answer = null;
148 
149         synchronized (this) {
150             this.rowValue = row;
151             answer = column.getValue(row);
152             this.rowValue = null;
153         }
154 
155         return answer;
156     }
157 
158     public void addColumn(String name, String expression) {
159         addColumn(name, expression, XMLTableColumnDefinition.OBJECT_TYPE);
160     }
161 
162     public void addColumn(String name, String expression, int type) {
163         XPath xpath = createColumnXPath(expression);
164         addColumn(new XMLTableColumnDefinition(name, xpath, type));
165     }
166 
167     public void addColumnWithXPathName(String columnNameXPathExpression,
168             String expression, int type) {
169         XPath columnNameXPath = createColumnXPath(columnNameXPathExpression);
170         XPath xpath = createColumnXPath(expression);
171         addColumn(new XMLTableColumnDefinition(columnNameXPath, xpath, type));
172     }
173 
174     public void addStringColumn(String name, String expression) {
175         addColumn(name, expression, XMLTableColumnDefinition.STRING_TYPE);
176     }
177 
178     public void addNumberColumn(String name, String expression) {
179         addColumn(name, expression, XMLTableColumnDefinition.NUMBER_TYPE);
180     }
181 
182     public void addColumn(XMLTableColumnDefinition column) {
183         clearCaches();
184         columns.add(column);
185     }
186 
187     public void removeColumn(XMLTableColumnDefinition column) {
188         clearCaches();
189         columns.remove(column);
190     }
191 
192     public void clear() {
193         clearCaches();
194         columns.clear();
195     }
196 
197     public XMLTableColumnDefinition getColumn(int index) {
198         if (columnArray == null) {
199             columnArray = new XMLTableColumnDefinition[columns.size()];
200             columns.toArray(columnArray);
201         }
202 
203         return columnArray[index];
204     }
205 
206     public XMLTableColumnDefinition getColumn(String columnName) {
207         if (columnNameIndex == null) {
208             columnNameIndex = new HashMap();
209 
210             for (Iterator it = columns.iterator(); it.hasNext();) {
211                 XMLTableColumnDefinition column = (XMLTableColumnDefinition) it
212                         .next();
213                 columnNameIndex.put(column.getName(), column);
214             }
215         }
216 
217         return (XMLTableColumnDefinition) columnNameIndex.get(columnName);
218     }
219 
220     /***
221      * Getter for property rowXPath.
222      * 
223      * @return Value of property rowXPath.
224      */
225     public XPath getRowXPath() {
226         return rowXPath;
227     }
228 
229     /***
230      * Setter for property rowXPath.
231      * 
232      * @param rowXPath
233      *            New value of property rowXPath.
234      */
235     public void setRowXPath(XPath rowXPath) {
236         this.rowXPath = rowXPath;
237     }
238 
239     public void setRowExpression(String xpath) {
240         setRowXPath(createXPath(xpath));
241     }
242 
243     // VariableContext interface
244     // -------------------------------------------------------------------------
245     public Object getVariableValue(String namespaceURI, String prefix,
246             String localName) {
247         XMLTableColumnDefinition column = getColumn(localName);
248 
249         if (column != null) {
250             return column.getValue(rowValue);
251         }
252 
253         return null;
254     }
255 
256     // Implementation methods
257     // -------------------------------------------------------------------------
258     protected XPath createXPath(String expression) {
259         return DocumentHelper.createXPath(expression);
260     }
261 
262     protected XPath createColumnXPath(String expression) {
263         XPath xpath = createXPath(expression);
264 
265         // associate my variable context
266         xpath.setVariableContext(this);
267 
268         return xpath;
269     }
270 
271     protected void clearCaches() {
272         columnArray = null;
273         columnNameIndex = null;
274     }
275 
276     protected void handleException(Exception e) {
277         // #### should use jakarta commons-logging
278         System.out.println("Caught: " + e);
279     }
280 }
281 
282 /*
283  * Redistribution and use of this software and associated documentation
284  * ("Software"), with or without modification, are permitted provided that the
285  * following conditions are met:
286  * 
287  * 1. Redistributions of source code must retain copyright statements and
288  * notices. Redistributions must also contain a copy of this document.
289  * 
290  * 2. Redistributions in binary form must reproduce the above copyright notice,
291  * this list of conditions and the following disclaimer in the documentation
292  * and/or other materials provided with the distribution.
293  * 
294  * 3. The name "DOM4J" must not be used to endorse or promote products derived
295  * from this Software without prior written permission of MetaStuff, Ltd. For
296  * written permission, please contact dom4j-info@metastuff.com.
297  * 
298  * 4. Products derived from this Software may not be called "DOM4J" nor may
299  * "DOM4J" appear in their names without prior written permission of MetaStuff,
300  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
301  * 
302  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
303  * 
304  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
305  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
306  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
307  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
308  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
309  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
310  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
311  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
312  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
313  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
314  * POSSIBILITY OF SUCH DAMAGE.
315  * 
316  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
317  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/package-summary.html0000644000175000017500000001370610242117671021550 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j

Class Summary
Attribute
Branch
CDATA
CharacterData
Comment
Document
DocumentException
DocumentFactory
DocumentHelper
DocumentType
Element
ElementHandler
ElementPath
Entity
IllegalAddException
InvalidXPathException
Namespace
Node
NodeFilter
ProcessingInstruction
QName
Text
Visitor
VisitorSupport
XPath
XPathException
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref/org/dom4j/Namespace.html0000644000175000017500000005437310242117564020364 0ustar ebourgebourg Namespace xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import org.dom4j.tree.AbstractNode;
11  import org.dom4j.tree.DefaultNamespace;
12  import org.dom4j.tree.NamespaceCache;
13  
14  /***
15   * <p>
16   * <code>Namespace</code> is a Flyweight Namespace that can be shared amongst
17   * nodes.
18   * </p>
19   * 
20   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
21   * @version $Revision: 1.22 $
22   */
23  public class Namespace extends AbstractNode {
24      /*** Cache of Namespace instances */
25      protected static final NamespaceCache CACHE = new NamespaceCache();
26  
27      /*** XML Namespace */
28      public static final Namespace XML_NAMESPACE = CACHE.get("xml",
29              "http://www.w3.org/XML/1998/namespace");
30  
31      /*** No Namespace present */
32      public static final Namespace NO_NAMESPACE = CACHE.get("", "");
33  
34      /*** The prefix mapped to this namespace */
35      private String prefix;
36  
37      /*** The URI for this namespace */
38      private String uri;
39  
40      /*** A cached version of the hashcode for efficiency */
41      private int hashCode;
42  
43      /***
44       * DOCUMENT ME!
45       * 
46       * @param prefix
47       *            is the prefix for this namespace
48       * @param uri
49       *            is the URI for this namespace
50       */
51      public Namespace(String prefix, String uri) {
52          this.prefix = (prefix != null) ? prefix : "";
53          this.uri = (uri != null) ? uri : "";
54      }
55  
56      /***
57       * A helper method to return the Namespace instance for the given prefix and
58       * URI
59       * 
60       * @param prefix
61       *            DOCUMENT ME!
62       * @param uri
63       *            DOCUMENT ME!
64       * 
65       * @return an interned Namespace object
66       */
67      public static Namespace get(String prefix, String uri) {
68          return CACHE.get(prefix, uri);
69      }
70  
71      /***
72       * A helper method to return the Namespace instance for no prefix and the
73       * URI
74       * 
75       * @param uri
76       *            DOCUMENT ME!
77       * 
78       * @return an interned Namespace object
79       */
80      public static Namespace get(String uri) {
81          return CACHE.get(uri);
82      }
83  
84      public short getNodeType() {
85          return NAMESPACE_NODE;
86      }
87  
88      /***
89       * DOCUMENT ME!
90       * 
91       * @return the hash code based on the qualified name and the URI of the
92       *         namespace.
93       */
94      public int hashCode() {
95          if (hashCode == 0) {
96              hashCode = createHashCode();
97          }
98  
99          return hashCode;
100     }
101 
102     /***
103      * Factory method to create the hashcode allowing derived classes to change
104      * the behaviour
105      * 
106      * @return DOCUMENT ME!
107      */
108     protected int createHashCode() {
109         int result = uri.hashCode() ^ prefix.hashCode();
110 
111         if (result == 0) {
112             result = 0xbabe;
113         }
114 
115         return result;
116     }
117 
118     /***
119      * Checks whether this Namespace equals the given Namespace. Two Namespaces
120      * are equals if their URI and prefix are equal.
121      * 
122      * @param object
123      *            DOCUMENT ME!
124      * 
125      * @return DOCUMENT ME!
126      */
127     public boolean equals(Object object) {
128         if (this == object) {
129             return true;
130         } else if (object instanceof Namespace) {
131             Namespace that = (Namespace) object;
132 
133             // we cache hash codes so this should be quick
134             if (hashCode() == that.hashCode()) {
135                 return uri.equals(that.getURI())
136                         && prefix.equals(that.getPrefix());
137             }
138         }
139 
140         return false;
141     }
142 
143     public String getText() {
144         return uri;
145     }
146 
147     public String getStringValue() {
148         return uri;
149     }
150 
151     /***
152      * DOCUMENT ME!
153      * 
154      * @return the prefix for this <code>Namespace</code>.
155      */
156     public String getPrefix() {
157         return prefix;
158     }
159 
160     /***
161      * DOCUMENT ME!
162      * 
163      * @return the URI for this <code>Namespace</code>.
164      */
165     public String getURI() {
166         return uri;
167     }
168 
169     public String getXPathNameStep() {
170         if ((prefix != null) && !"".equals(prefix)) {
171             return "namespace::" + prefix;
172         }
173 
174         return "namespace::*[name()='']";
175     }
176 
177     public String getPath(Element context) {
178         StringBuffer path = new StringBuffer(10);
179         Element parent = getParent();
180 
181         if ((parent != null) && (parent != context)) {
182             path.append(parent.getPath(context));
183             path.append('/');
184         }
185 
186         path.append(getXPathNameStep());
187 
188         return path.toString();
189     }
190 
191     public String getUniquePath(Element context) {
192         StringBuffer path = new StringBuffer(10);
193         Element parent = getParent();
194 
195         if ((parent != null) && (parent != context)) {
196             path.append(parent.getUniquePath(context));
197             path.append('/');
198         }
199 
200         path.append(getXPathNameStep());
201 
202         return path.toString();
203     }
204 
205     public String toString() {
206         return super.toString() + " [Namespace: prefix " + getPrefix()
207                 + " mapped to URI \"" + getURI() + "\"]";
208     }
209 
210     public String asXML() {
211         StringBuffer asxml = new StringBuffer(10);
212         String pref = getPrefix();
213 
214         if ((pref != null) && (pref.length() > 0)) {
215             asxml.append("xmlns:");
216             asxml.append(pref);
217             asxml.append("=\"");
218         } else {
219             asxml.append("xmlns=\"");
220         }
221 
222         asxml.append(getURI());
223         asxml.append("\"");
224 
225         return asxml.toString();
226     }
227 
228     public void accept(Visitor visitor) {
229         visitor.visit(this);
230     }
231 
232     protected Node createXPathResult(Element parent) {
233         return new DefaultNamespace(parent, getPrefix(), getURI());
234     }
235 }
236 
237 /*
238  * Redistribution and use of this software and associated documentation
239  * ("Software"), with or without modification, are permitted provided that the
240  * following conditions are met:
241  * 
242  * 1. Redistributions of source code must retain copyright statements and
243  * notices. Redistributions must also contain a copy of this document.
244  * 
245  * 2. Redistributions in binary form must reproduce the above copyright notice,
246  * this list of conditions and the following disclaimer in the documentation
247  * and/or other materials provided with the distribution.
248  * 
249  * 3. The name "DOM4J" must not be used to endorse or promote products derived
250  * from this Software without prior written permission of MetaStuff, Ltd. For
251  * written permission, please contact dom4j-info@metastuff.com.
252  * 
253  * 4. Products derived from this Software may not be called "DOM4J" nor may
254  * "DOM4J" appear in their names without prior written permission of MetaStuff,
255  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
256  * 
257  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
258  * 
259  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
260  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
261  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
262  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
263  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
264  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
265  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
266  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
267  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
268  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
269  * POSSIBILITY OF SUCH DAMAGE.
270  * 
271  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
272  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/xpp/0000755000175000017500000000000012133227266016377 5ustar ebourgebourgdom4j-1.6.1/docs/xref/org/dom4j/xpp/ProxyXmlStartTag.html0000644000175000017500000006505510242117743022551 0ustar ebourgebourg ProxyXmlStartTag xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpp;
9   
10  import java.util.ArrayList;
11  import java.util.Iterator;
12  
13  import org.dom4j.Attribute;
14  import org.dom4j.DocumentFactory;
15  import org.dom4j.Element;
16  import org.dom4j.QName;
17  import org.dom4j.tree.AbstractElement;
18  
19  import org.gjt.xpp.XmlPullParserException;
20  import org.gjt.xpp.XmlStartTag;
21  
22  /***
23   * <code>ProxyXmlStartTag</code> implements the XPP <code>XmlSmartTag</code>
24   * interface while creating a dom4j <code>Element</code> underneath.
25   * 
26   * @author James Strachan
27   * @author Maarten Coene
28   * @author Wolfgang Baer
29   */
30  public class ProxyXmlStartTag implements XmlStartTag {
31      /*** The element being constructed */
32      private Element element;
33  
34      /*** The factory used to create new elements */
35      private DocumentFactory factory = DocumentFactory.getInstance();
36  
37      public ProxyXmlStartTag() {
38      }
39  
40      public ProxyXmlStartTag(Element element) {
41          this.element = element;
42      }
43  
44      // XmlStartTag interface
45      // -------------------------------------------------------------------------
46      public void resetStartTag() {
47          this.element = null;
48      }
49  
50      public int getAttributeCount() {
51          return (element != null) ? element.attributeCount() : 0;
52      }
53  
54      public String getAttributeNamespaceUri(int index) {
55          if (element != null) {
56              Attribute attribute = element.attribute(index);
57  
58              if (attribute != null) {
59                  return attribute.getNamespaceURI();
60              }
61          }
62  
63          return null;
64      }
65  
66      public String getAttributeLocalName(int index) {
67          if (element != null) {
68              Attribute attribute = element.attribute(index);
69  
70              if (attribute != null) {
71                  return attribute.getName();
72              }
73          }
74  
75          return null;
76      }
77  
78      public String getAttributePrefix(int index) {
79          if (element != null) {
80              Attribute attribute = element.attribute(index);
81  
82              if (attribute != null) {
83                  String prefix = attribute.getNamespacePrefix();
84  
85                  if ((prefix != null) && (prefix.length() > 0)) {
86                      return prefix;
87                  }
88              }
89          }
90  
91          return null;
92      }
93  
94      public String getAttributeRawName(int index) {
95          if (element != null) {
96              Attribute attribute = element.attribute(index);
97  
98              if (attribute != null) {
99                  return attribute.getQualifiedName();
100             }
101         }
102 
103         return null;
104     }
105 
106     public String getAttributeValue(int index) {
107         if (element != null) {
108             Attribute attribute = element.attribute(index);
109 
110             if (attribute != null) {
111                 return attribute.getValue();
112             }
113         }
114 
115         return null;
116     }
117 
118     public String getAttributeValueFromRawName(String rawName) {
119         if (element != null) {
120             for (Iterator iter = element.attributeIterator(); iter.hasNext();) {
121                 Attribute attribute = (Attribute) iter.next();
122 
123                 if (rawName.equals(attribute.getQualifiedName())) {
124                     return attribute.getValue();
125                 }
126             }
127         }
128 
129         return null;
130     }
131 
132     public String getAttributeValueFromName(String namespaceURI,
133             String localName) {
134         if (element != null) {
135             for (Iterator iter = element.attributeIterator(); iter.hasNext();) {
136                 Attribute attribute = (Attribute) iter.next();
137 
138                 if (namespaceURI.equals(attribute.getNamespaceURI())
139                         && localName.equals(attribute.getName())) {
140                     return attribute.getValue();
141                 }
142             }
143         }
144 
145         return null;
146     }
147 
148     public boolean isAttributeNamespaceDeclaration(int index) {
149         if (element != null) {
150             Attribute attribute = element.attribute(index);
151 
152             if (attribute != null) {
153                 return "xmlns".equals(attribute.getNamespacePrefix());
154             }
155         }
156 
157         return false;
158     }
159 
160     /***
161      * parameters modeled after SAX2 attribute approach
162      * 
163      * @param namespaceURI DOCUMENT ME!
164      * @param localName DOCUMENT ME!
165      * @param rawName DOCUMENT ME!
166      * @param value DOCUMENT ME!
167      * 
168      * @throws XmlPullParserException DOCUMENT ME!
169      */
170     public void addAttribute(String namespaceURI, String localName,
171             String rawName, String value) throws XmlPullParserException {
172         QName qname = QName.get(rawName, namespaceURI);
173         element.addAttribute(qname, value);
174     }
175 
176     public void addAttribute(String namespaceURI, String localName,
177             String rawName, String value, boolean isNamespaceDeclaration)
178             throws XmlPullParserException {
179         if (isNamespaceDeclaration) {
180             String prefix = "";
181             int idx = rawName.indexOf(':');
182 
183             if (idx > 0) {
184                 prefix = rawName.substring(0, idx);
185             }
186 
187             element.addNamespace(prefix, namespaceURI);
188         } else {
189             QName qname = QName.get(rawName, namespaceURI);
190             element.addAttribute(qname, value);
191         }
192     }
193 
194     public void ensureAttributesCapacity(int minCapacity)
195             throws XmlPullParserException {
196         if (element instanceof AbstractElement) {
197             AbstractElement elementImpl = (AbstractElement) element;
198             elementImpl.ensureAttributesCapacity(minCapacity);
199         }
200     }
201 
202     /***
203      * Remove all atributes.
204      * 
205      * @deprecated Use {@link #removeAttributes()} instead.
206      */
207     public void removeAtttributes() throws XmlPullParserException {
208         removeAttributes();
209     }
210 
211     public void removeAttributes() throws XmlPullParserException {
212         if (element != null) {
213             element.setAttributes(new ArrayList());
214 
215             // ##### FIXME
216             // adding this method would be nice...
217             // element.clearAttributes();
218         }
219     }
220 
221     public String getLocalName() {
222         return element.getName();
223     }
224 
225     public String getNamespaceUri() {
226         return element.getNamespaceURI();
227     }
228 
229     public String getPrefix() {
230         return element.getNamespacePrefix();
231     }
232 
233     public String getRawName() {
234         return element.getQualifiedName();
235     }
236 
237     public void modifyTag(String namespaceURI, String lName, String rawName) {
238         this.element = factory.createElement(rawName, namespaceURI);
239     }
240 
241     public void resetTag() {
242         this.element = null;
243     }
244 
245     public boolean removeAttributeByName(String namespaceURI, String localName)
246             throws XmlPullParserException {
247         if (element != null) {
248             QName qname = QName.get(localName, namespaceURI);
249             Attribute attribute = element.attribute(qname);
250             return element.remove(attribute);
251         }
252         return false;
253     }
254 
255     public boolean removeAttributeByRawName(String rawName)
256             throws XmlPullParserException {
257         if (element != null) {
258             Attribute attribute = null;
259             Iterator it = element.attributeIterator();
260             while (it.hasNext()) {
261                 Attribute current = (Attribute) it.next();
262                 if (current.getQualifiedName().equals(rawName)) {
263                     attribute = current;
264                     break;
265                 }
266             }
267             return element.remove(attribute);
268         }
269         return false;
270     }
271 
272     // Properties
273     // -------------------------------------------------------------------------
274     public DocumentFactory getDocumentFactory() {
275         return factory;
276     }
277 
278     public void setDocumentFactory(DocumentFactory documentFactory) {
279         this.factory = documentFactory;
280     }
281 
282     public Element getElement() {
283         return element;
284     }
285 }
286 
287 /*
288  * Redistribution and use of this software and associated documentation
289  * ("Software"), with or without modification, are permitted provided that the
290  * following conditions are met:
291  * 
292  * 1. Redistributions of source code must retain copyright statements and
293  * notices. Redistributions must also contain a copy of this document.
294  * 
295  * 2. Redistributions in binary form must reproduce the above copyright notice,
296  * this list of conditions and the following disclaimer in the documentation
297  * and/or other materials provided with the distribution.
298  * 
299  * 3. The name "DOM4J" must not be used to endorse or promote products derived
300  * from this Software without prior written permission of MetaStuff, Ltd. For
301  * written permission, please contact dom4j-info@metastuff.com.
302  * 
303  * 4. Products derived from this Software may not be called "DOM4J" nor may
304  * "DOM4J" appear in their names without prior written permission of MetaStuff,
305  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
306  * 
307  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
308  * 
309  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
310  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
311  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
312  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
313  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
314  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
315  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
316  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
317  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
318  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
319  * POSSIBILITY OF SUCH DAMAGE.
320  * 
321  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
322  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/xpp/package-summary.html0000644000175000017500000000376110242117717022360 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.xpp

Class Summary
ProxyXmlStartTag
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref/org/dom4j/xpp/package-frame.html0000644000175000017500000000130210242117747021745 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.xpp

org.dom4j.xpp

Classes

  • ProxyXmlStartTag
dom4j-1.6.1/docs/xref/org/dom4j/jaxb/0000755000175000017500000000000012133227266016514 5ustar ebourgebourgdom4j-1.6.1/docs/xref/org/dom4j/jaxb/JAXBObjectHandler.html0000644000175000017500000001625710242117707022563 0ustar ebourgebourg JAXBObjectHandler xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.jaxb;
9   
10  import javax.xml.bind.Element;
11  
12  /***
13   * JAXBObjectHandler implementations can be registered with the JAXB Reader in
14   * order to receive unmarshalled XML fragments.
15   * 
16   * @author Wonne Keysers (Realsoftware.be)
17   */
18  public interface JAXBObjectHandler {
19      /***
20       * Called when the {@link JAXBReader}has finished parsing the xml path the
21       * handler was registered for. The provided object is the unmarshalled
22       * representation of the XML path. It can be casted to the appropriate
23       * implementation class that is generated by the JAXB compiler.
24       * 
25       * @param jaxbElement
26       *            the unmarshalled JAXB object to handle
27       * 
28       * @throws Exception
29       *             of any kind, thrown by the implementation
30       */
31      void handleObject(Element jaxbElement) throws Exception;
32  }
33  
34  /*
35   * Redistribution and use of this software and associated documentation
36   * ("Software"), with or without modification, are permitted provided that the
37   * following conditions are met:
38   * 
39   * 1. Redistributions of source code must retain copyright statements and
40   * notices. Redistributions must also contain a copy of this document.
41   * 
42   * 2. Redistributions in binary form must reproduce the above copyright notice,
43   * this list of conditions and the following disclaimer in the documentation
44   * and/or other materials provided with the distribution.
45   * 
46   * 3. The name "DOM4J" must not be used to endorse or promote products derived
47   * from this Software without prior written permission of MetaStuff, Ltd. For
48   * written permission, please contact dom4j-info@metastuff.com.
49   * 
50   * 4. Products derived from this Software may not be called "DOM4J" nor may
51   * "DOM4J" appear in their names without prior written permission of MetaStuff,
52   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
53   * 
54   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
55   * 
56   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
57   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
58   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
59   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
60   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
61   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
62   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
63   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
65   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
66   * POSSIBILITY OF SUCH DAMAGE.
67   * 
68   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
69   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/jaxb/package-summary.html0000644000175000017500000000575210242117746022501 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.jaxb

Class Summary
JAXBModifier
JAXBObjectHandler
JAXBObjectModifier
JAXBReader
JAXBRuntimeException
JAXBSupport
JAXBWriter
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref/org/dom4j/jaxb/package-frame.html0000644000175000017500000000262610242117717022071 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.jaxb

org.dom4j.jaxb

Classes

  • JAXBModifier
  • JAXBObjectHandler
  • JAXBObjectModifier
  • JAXBReader
  • JAXBRuntimeException
  • JAXBSupport
  • JAXBWriter
dom4j-1.6.1/docs/xref/org/dom4j/jaxb/JAXBReader.html0000644000175000017500000011000710242117705021243 0ustar ebourgebourg JAXBReader xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.jaxb;
9   
10  import java.io.File;
11  import java.io.FileInputStream;
12  import java.io.FileNotFoundException;
13  import java.io.InputStream;
14  import java.io.InputStreamReader;
15  import java.io.Reader;
16  import java.net.URL;
17  import java.nio.charset.Charset;
18  
19  import org.dom4j.Document;
20  import org.dom4j.DocumentException;
21  import org.dom4j.Element;
22  import org.dom4j.ElementHandler;
23  import org.dom4j.ElementPath;
24  import org.dom4j.io.SAXReader;
25  
26  import org.xml.sax.InputSource;
27  
28  /***
29   * Reads an XML document and creates a DOM4J tree from SAX parsing events.
30   * {@link JAXBObjectHandler}objects can be registered to automatically receive
31   * unmarshalled XML fragments. Registered {@linkorg.dom4j.ElementHandler}
32   * implementations are notified when a certain element path is encountered
33   * 
34   * @author Wonne Keysers (Realsoftware.be)
35   * 
36   * @see org.dom4j.io.SAXReader
37   * @see javax.xml.bind.JAXBContext
38   */
39  public class JAXBReader extends JAXBSupport {
40      private SAXReader reader;
41  
42      private boolean pruneElements;
43  
44      /***
45       * Creates a new JAXBReader for the given JAXB context path. This is the
46       * Java package where JAXB can find the generated XML classes. This package
47       * MUST contain jaxb.properties!
48       * 
49       * @param contextPath
50       *            context path to be used
51       * 
52       * @see javax.xml.bind.JAXBContext
53       */
54      public JAXBReader(String contextPath) {
55          super(contextPath);
56      }
57  
58      /***
59       * Creates a new JAXBReader for the given JAXB context path, using the
60       * specified {@link java.lang.Classloader}. This is the Java package where
61       * JAXB can find the generated XML classes. This package MUST contain
62       * jaxb.properties!
63       * 
64       * @param contextPath
65       *            to be used
66       * @param classloader
67       *            to be used
68       * 
69       * @see javax.xml.bind.JAXBContext
70       */
71      public JAXBReader(String contextPath, ClassLoader classloader) {
72          super(contextPath, classloader);
73      }
74  
75      /***
76       * Parses the specified {@link java.io.File}
77       * 
78       * @param source
79       *            the file to parse
80       * 
81       * @return the resulting DOM4J document
82       * 
83       * @throws DocumentException
84       *             when an error occurs while parsing
85       */
86      public Document read(File source) throws DocumentException {
87          return getReader().read(source);
88      }
89  
90      /***
91       * Parses the specified {@link java.io.File}, using the given {@link
92       * java.nio.charset.Charset}.
93       * 
94       * @param file
95       *            the file to parse
96       * @param charset
97       *            the charset to be used
98       * 
99       * @return the resulting DOM4J document
100      * 
101      * @throws DocumentException
102      *             when an error occurs while parsing
103      */
104     public Document read(File file, Charset charset) throws DocumentException {
105         try {
106             Reader xmlReader = new InputStreamReader(new FileInputStream(file),
107                     charset);
108 
109             return getReader().read(xmlReader);
110         } catch (JAXBRuntimeException ex) {
111             Throwable cause = ex.getCause();
112             throw new DocumentException(cause.getMessage(), cause);
113         } catch (FileNotFoundException ex) {
114             throw new DocumentException(ex.getMessage(), ex);
115         }
116     }
117 
118     /***
119      * Parses the specified {@link org.xml.sax.InputSource}
120      * 
121      * @param source
122      *            the source to parse
123      * 
124      * @return the resulting DOM4J document
125      * 
126      * @throws DocumentException
127      *             when an error occurs while parsing
128      */
129     public Document read(InputSource source) throws DocumentException {
130         try {
131             return getReader().read(source);
132         } catch (JAXBRuntimeException ex) {
133             Throwable cause = ex.getCause();
134             throw new DocumentException(cause.getMessage(), cause);
135         }
136     }
137 
138     /***
139      * Parses the specified {@link java.io.InputStream}
140      * 
141      * @param source
142      *            the input stream to parse
143      * 
144      * @return the resulting DOM4J document
145      * 
146      * @throws DocumentException
147      *             when an error occurs while parsing
148      */
149     public Document read(InputStream source) throws DocumentException {
150         try {
151             return getReader().read(source);
152         } catch (JAXBRuntimeException ex) {
153             Throwable cause = ex.getCause();
154             throw new DocumentException(cause.getMessage(), cause);
155         }
156     }
157 
158     /***
159      * Parses the specified {@link java.io.InputStream}
160      * 
161      * @param source
162      *            the input stream to parse
163      * @param systemId
164      *            is the URI for the input
165      * 
166      * @return the resulting DOM4J document
167      * 
168      * @throws DocumentException
169      *             when an error occurs while parsing
170      */
171     public Document read(InputStream source, String systemId)
172             throws DocumentException {
173         try {
174             return getReader().read(source);
175         } catch (JAXBRuntimeException ex) {
176             Throwable cause = ex.getCause();
177             throw new DocumentException(cause.getMessage(), cause);
178         }
179     }
180 
181     /***
182      * Parses the specified {@link java.io.Reader}
183      * 
184      * @param source
185      *            the input reader to use
186      * 
187      * @return the resulting DOM4J document
188      * 
189      * @throws DocumentException
190      *             when an error occurs while parsing
191      */
192     public Document read(Reader source) throws DocumentException {
193         try {
194             return getReader().read(source);
195         } catch (JAXBRuntimeException ex) {
196             Throwable cause = ex.getCause();
197             throw new DocumentException(cause.getMessage(), cause);
198         }
199     }
200 
201     /***
202      * Parses the specified {@link java.io.Reader}
203      * 
204      * @param source
205      *            the input reader to parse
206      * @param systemId
207      *            is the URI for the input
208      * 
209      * @return the resulting DOM4J document
210      * 
211      * @throws DocumentException
212      *             when an error occurs while parsing
213      */
214     public Document read(Reader source, String systemId)
215             throws DocumentException {
216         try {
217             return getReader().read(source);
218         } catch (JAXBRuntimeException ex) {
219             Throwable cause = ex.getCause();
220             throw new DocumentException(cause.getMessage(), cause);
221         }
222     }
223 
224     /***
225      * Parses the the given URL or filename.
226      * 
227      * @param source
228      *            the location to parse
229      * 
230      * @return the resulting DOM4J document
231      * 
232      * @throws DocumentException
233      *             when an error occurs while parsing
234      */
235     public Document read(String source) throws DocumentException {
236         try {
237             return getReader().read(source);
238         } catch (JAXBRuntimeException ex) {
239             Throwable cause = ex.getCause();
240             throw new DocumentException(cause.getMessage(), cause);
241         }
242     }
243 
244     /***
245      * Parses the the given URL.
246      * 
247      * @param source
248      *            the URL to parse
249      * 
250      * @return the resulting DOM4J document
251      * 
252      * @throws DocumentException
253      *             when an error occurs while parsing
254      */
255     public Document read(URL source) throws DocumentException {
256         try {
257             return getReader().read(source);
258         } catch (JAXBRuntimeException ex) {
259             Throwable cause = ex.getCause();
260             throw new DocumentException(cause.getMessage(), cause);
261         }
262     }
263 
264     /***
265      * Registers a {@link JAXBObjectHandler}that will be supplied with the
266      * unmarshalled representation of the xml fragment whenever the specified
267      * path is encounted.
268      * 
269      * @param path
270      *            the path to listen for
271      * @param handler
272      *            the handler to be notified
273      */
274     public void addObjectHandler(String path, JAXBObjectHandler handler) {
275         ElementHandler eHandler = new UnmarshalElementHandler(this, handler);
276         getReader().addHandler(path, eHandler);
277     }
278 
279     /***
280      * Removes the {@link JAXBObjectHandler}from the event based processor, for
281      * the specified element path.
282      * 
283      * @param path
284      *            The path to remove the {@link JAXBObjectHandler}for
285      */
286     public void removeObjectHandler(String path) {
287         getReader().removeHandler(path);
288     }
289 
290     /***
291      * Adds the <code>ElementHandler</code> to be called when the specified
292      * path is encounted.
293      * 
294      * @param path
295      *            is the path to be handled
296      * @param handler
297      *            is the <code>ElementHandler</code> to be called by the event
298      *            based processor.
299      */
300     public void addHandler(String path, ElementHandler handler) {
301         getReader().addHandler(path, handler);
302     }
303 
304     /***
305      * Removes the <code>ElementHandler</code> from the event based processor,
306      * for the specified path.
307      * 
308      * @param path
309      *            is the path to remove the <code>ElementHandler</code> for.
310      */
311     public void removeHandler(String path) {
312         getReader().removeHandler(path);
313     }
314 
315     /***
316      * Removes all registered {@link JAXBObjectHandler}and {@link
317      * org.dom4j.ElementHandler} instances from the event based processor.
318      */
319     public void resetHandlers() {
320         getReader().resetHandlers();
321     }
322 
323     /***
324      * When 'true', the DOM4J document will not be kept in memory while parsing.
325      * 
326      * @return Returns the pruneElements.
327      */
328     public boolean isPruneElements() {
329         return pruneElements;
330     }
331 
332     /***
333      * Set to true when DOM4J elements must immediately be pruned from the tree.
334      * The {@link Document}will not be available afterwards!
335      * 
336      * @param pruneElements
337      */
338     public void setPruneElements(boolean pruneElements) {
339         this.pruneElements = pruneElements;
340 
341         if (pruneElements) {
342             getReader().setDefaultHandler(new PruningElementHandler());
343         }
344     }
345 
346     private SAXReader getReader() {
347         if (reader == null) {
348             reader = new SAXReader();
349         }
350 
351         return reader;
352     }
353 
354     private class UnmarshalElementHandler implements ElementHandler {
355         private JAXBReader jaxbReader;
356 
357         private JAXBObjectHandler handler;
358 
359         public UnmarshalElementHandler(JAXBReader documentReader,
360                 JAXBObjectHandler handler) {
361             this.jaxbReader = documentReader;
362             this.handler = handler;
363         }
364 
365         public void onStart(ElementPath elementPath) {
366         }
367 
368         public void onEnd(ElementPath elementPath) {
369             try {
370                 org.dom4j.Element elem = elementPath.getCurrent();
371 
372                 javax.xml.bind.Element jaxbObject 
373                         = (javax.xml.bind.Element) jaxbReader.unmarshal(elem);
374 
375                 if (jaxbReader.isPruneElements()) {
376                     elem.detach();
377                 }
378 
379                 handler.handleObject(jaxbObject);
380             } catch (Exception ex) {
381                 throw new JAXBRuntimeException(ex);
382             }
383         }
384     }
385 
386     private class PruningElementHandler implements ElementHandler {
387         public PruningElementHandler() {
388         }
389 
390         public void onStart(ElementPath parm1) {
391         }
392 
393         public void onEnd(ElementPath elementPath) {
394             Element elem = elementPath.getCurrent();
395             elem.detach();
396             elem = null;
397         }
398     }
399 }
400 
401 /*
402  * Redistribution and use of this software and associated documentation
403  * ("Software"), with or without modification, are permitted provided that the
404  * following conditions are met:
405  * 
406  * 1. Redistributions of source code must retain copyright statements and
407  * notices. Redistributions must also contain a copy of this document.
408  * 
409  * 2. Redistributions in binary form must reproduce the above copyright notice,
410  * this list of conditions and the following disclaimer in the documentation
411  * and/or other materials provided with the distribution.
412  * 
413  * 3. The name "DOM4J" must not be used to endorse or promote products derived
414  * from this Software without prior written permission of MetaStuff, Ltd. For
415  * written permission, please contact dom4j-info@metastuff.com.
416  * 
417  * 4. Products derived from this Software may not be called "DOM4J" nor may
418  * "DOM4J" appear in their names without prior written permission of MetaStuff,
419  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
420  * 
421  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
422  * 
423  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
424  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
425  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
426  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
427  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
428  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
429  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
430  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
431  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
432  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
433  * POSSIBILITY OF SUCH DAMAGE.
434  * 
435  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
436  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/jaxb/JAXBSupport.html0000644000175000017500000003132010242117752021517 0ustar ebourgebourg JAXBSupport xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.jaxb;
9   
10  import java.io.StringReader;
11  
12  import javax.xml.bind.JAXBContext;
13  import javax.xml.bind.JAXBException;
14  import javax.xml.bind.Marshaller;
15  import javax.xml.bind.Unmarshaller;
16  import javax.xml.transform.Source;
17  import javax.xml.transform.stream.StreamSource;
18  
19  import org.dom4j.dom.DOMDocument;
20  
21  /***
22   * DOCUMENT ME!
23   * 
24   * @author Wonne Keysers (Realsoftware.be)
25   */
26  abstract class JAXBSupport {
27      private String contextPath;
28  
29      private ClassLoader classloader;
30  
31      private JAXBContext jaxbContext;
32  
33      private Marshaller marshaller;
34  
35      private Unmarshaller unmarshaller;
36  
37      public JAXBSupport(String contextPath) {
38          this.contextPath = contextPath;
39      }
40  
41      public JAXBSupport(String contextPath, ClassLoader classloader) {
42          this.contextPath = contextPath;
43          this.classloader = classloader;
44      }
45  
46      /***
47       * Marshals the given {@link javax.xml.bind.Element}in to its DOM4J
48       * counterpart.
49       * 
50       * @param element
51       *            JAXB Element to be marshalled
52       * 
53       * @return the marshalled DOM4J {@link org.dom4j.Element}
54       * 
55       * @throws JAXBException
56       *             when an error occurs
57       */
58      protected org.dom4j.Element marshal(javax.xml.bind.Element element)
59              throws JAXBException {
60          DOMDocument doc = new DOMDocument();
61          getMarshaller().marshal(element, doc);
62  
63          return doc.getRootElement();
64      }
65  
66      /***
67       * Unmarshalls the specified DOM4J {@link org.dom4j.Element}into a {@link
68       * javax.xml.bind.Element}
69       * 
70       * @param element
71       *            the DOM4J element to unmarshall
72       * 
73       * @return the unmarshalled JAXB object
74       * 
75       * @throws JAXBException
76       *             when an error occurs
77       */
78      protected javax.xml.bind.Element unmarshal(org.dom4j.Element element)
79              throws JAXBException {
80          Source source = new StreamSource(new StringReader(element.asXML()));
81  
82          return (javax.xml.bind.Element) getUnmarshaller().unmarshal(source);
83      }
84  
85      private Marshaller getMarshaller() throws JAXBException {
86          if (marshaller == null) {
87              marshaller = getContext().createMarshaller();
88          }
89  
90          return marshaller;
91      }
92  
93      private Unmarshaller getUnmarshaller() throws JAXBException {
94          if (unmarshaller == null) {
95              unmarshaller = getContext().createUnmarshaller();
96          }
97  
98          return unmarshaller;
99      }
100 
101     private JAXBContext getContext() throws JAXBException {
102         if (jaxbContext == null) {
103             if (classloader == null) {
104                 jaxbContext = JAXBContext.newInstance(contextPath);
105             } else {
106                 jaxbContext = JAXBContext.newInstance(contextPath, classloader);
107             }
108         }
109 
110         return jaxbContext;
111     }
112 }
113 
114 /*
115  * Redistribution and use of this software and associated documentation
116  * ("Software"), with or without modification, are permitted provided that the
117  * following conditions are met:
118  * 
119  * 1. Redistributions of source code must retain copyright statements and
120  * notices. Redistributions must also contain a copy of this document.
121  * 
122  * 2. Redistributions in binary form must reproduce the above copyright notice,
123  * this list of conditions and the following disclaimer in the documentation
124  * and/or other materials provided with the distribution.
125  * 
126  * 3. The name "DOM4J" must not be used to endorse or promote products derived
127  * from this Software without prior written permission of MetaStuff, Ltd. For
128  * written permission, please contact dom4j-info@metastuff.com.
129  * 
130  * 4. Products derived from this Software may not be called "DOM4J" nor may
131  * "DOM4J" appear in their names without prior written permission of MetaStuff,
132  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
133  * 
134  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
135  * 
136  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
137  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
138  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
139  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
140  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
141  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
142  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
143  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
144  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
145  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
146  * POSSIBILITY OF SUCH DAMAGE.
147  * 
148  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
149  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/jaxb/JAXBModifier.html0000644000175000017500000013057110242117607021610 0ustar ebourgebourg JAXBModifier xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.jaxb;
9   
10  import java.io.File;
11  import java.io.FileInputStream;
12  import java.io.FileNotFoundException;
13  import java.io.FileOutputStream;
14  import java.io.IOException;
15  import java.io.InputStream;
16  import java.io.InputStreamReader;
17  import java.io.OutputStream;
18  import java.io.Reader;
19  import java.io.Writer;
20  import java.net.URL;
21  import java.nio.charset.Charset;
22  import java.util.HashMap;
23  import java.util.Iterator;
24  import java.util.Map;
25  
26  import org.dom4j.Document;
27  import org.dom4j.DocumentException;
28  import org.dom4j.io.ElementModifier;
29  import org.dom4j.io.OutputFormat;
30  import org.dom4j.io.SAXModifier;
31  import org.dom4j.io.XMLWriter;
32  
33  import org.xml.sax.InputSource;
34  
35  /***
36   * Reads an XML document using SAX and writes its content to the provided
37   * {@link org.dom4j.io.XMLWriter}. Modifications must be provided by {@link
38   * org.dom4j.jaxb.JAXBObjectModifier} objects, which are called prior to writing
39   * the XML fragment they are registered for.
40   * 
41   * @author Wonne Keysers (Realsoftware.be)
42   * 
43   * @see org.dom4j.io.SAXModifier
44   */
45  public class JAXBModifier extends JAXBSupport {
46      private SAXModifier modifier;
47  
48      private XMLWriter xmlWriter;
49  
50      private boolean pruneElements;
51  
52      private OutputFormat outputFormat;
53  
54      private HashMap modifiers = new HashMap();
55  
56      /***
57       * Creates a new JAXBModifier for the given JAXB context path. This is the
58       * Java package where JAXB can find the generated XML classes. This package
59       * MUST contain jaxb.properties!
60       * 
61       * @param contextPath
62       *            JAXB context path to be used
63       * 
64       * @see javax.xml.bind.JAXBContext
65       */
66      public JAXBModifier(String contextPath) {
67          super(contextPath);
68          this.outputFormat = new OutputFormat();
69      }
70  
71      /***
72       * Creates a new JAXBModifier for the given JAXB context path, using the
73       * given {@link java.lang.ClassLoader}. This is the Java package where JAXB
74       * can find the generated XML classes. This package MUST contain
75       * jaxb.properties!
76       * 
77       * @param contextPath
78       *            JAXB context path to be used
79       * @param classloader
80       *            the classloader to use
81       * 
82       * @see javax.xml.bind.JAXBContext
83       */
84      public JAXBModifier(String contextPath, ClassLoader classloader) {
85          super(contextPath, classloader);
86          this.outputFormat = new OutputFormat();
87      }
88  
89      /***
90       * Creates a new JAXBModifier for the given JAXB context path. The specified
91       * {@link org.dom4j.io.OutputFormat}will be used while writing the XML
92       * stream.
93       * 
94       * @param contextPath
95       *            JAXB context path to be used
96       * @param outputFormat
97       *            the DOM4J {@link org.dom4j.io.OutputFormat}to be used
98       * 
99       * @see javax.xml.bind.JAXBContext
100      */
101     public JAXBModifier(String contextPath, OutputFormat outputFormat) {
102         super(contextPath);
103         this.outputFormat = outputFormat;
104     }
105 
106     /***
107      * Creates a new JAXBModifier for the given JAXB context path, using the
108      * specified {@link java.lang.Classloader}. The specified {@link
109      * org.dom4j.io.OutputFormat} will be used while writing the XML stream.
110      * 
111      * @param contextPath
112      *            JAXB context path to be used
113      * @param classloader
114      *            the class loader to be used to load JAXB
115      * @param outputFormat
116      *            the DOM4J {@link org.dom4j.io.OutputFormat}to be used
117      * 
118      * @see javax.xml.bind.JAXBContext
119      */
120     public JAXBModifier(String contextPath, ClassLoader classloader,
121             OutputFormat outputFormat) {
122         super(contextPath, classloader);
123         this.outputFormat = outputFormat;
124     }
125 
126     /***
127      * Parses the specified {@link java.io.File}with SAX
128      * 
129      * @param source
130      *            the file to parse
131      * 
132      * @return the resulting DOM4J document
133      * 
134      * @throws DocumentException
135      *             when an error occurs while parsing
136      * @throws IOException
137      *             when an error occurs while writing to the {@link
138      *             org.dom4j.io.XMLWriter}
139      */
140     public Document modify(File source) throws DocumentException, IOException {
141         return installModifier().modify(source);
142     }
143 
144     /***
145      * Parses the specified {@link java.io.File}with SAX, using the given
146      * {@link java.nio.charset.Charset}.
147      * 
148      * @param source
149      *            the file to parse
150      * @param charset
151      *            the character set to use
152      * 
153      * @return the resulting DOM4J document
154      * 
155      * @throws DocumentException
156      *             when an error occurs while parsing
157      * @throws IOException
158      *             when an error occurs while writing to the {@link
159      *             org.dom4j.io.XMLWriter}
160      */
161     public Document modify(File source, Charset charset)
162             throws DocumentException, IOException {
163         try {
164             Reader reader = new InputStreamReader(new FileInputStream(source),
165                     charset);
166 
167             return installModifier().modify(reader);
168         } catch (JAXBRuntimeException ex) {
169             Throwable cause = ex.getCause();
170             throw new DocumentException(cause.getMessage(), cause);
171         } catch (FileNotFoundException ex) {
172             throw new DocumentException(ex.getMessage(), ex);
173         }
174     }
175 
176     /***
177      * Parses the specified {@link org.xml.sax.InputSource}with SAX.
178      * 
179      * @param source
180      *            the input source to parse
181      * 
182      * @return the resulting DOM4J document
183      * 
184      * @throws DocumentException
185      *             when an error occurs while parsing
186      * @throws IOException
187      *             when an error occurs while writing to the {@link
188      *             org.dom4j.io.XMLWriter}
189      */
190     public Document modify(InputSource source) throws DocumentException,
191             IOException {
192         try {
193             return installModifier().modify(source);
194         } catch (JAXBRuntimeException ex) {
195             Throwable cause = ex.getCause();
196             throw new DocumentException(cause.getMessage(), cause);
197         }
198     }
199 
200     /***
201      * Parses the specified {@link java.io.InputStream}with SAX.
202      * 
203      * @param source
204      *            the inputstream to parse
205      * 
206      * @return the resulting DOM4J document
207      * 
208      * @throws DocumentException
209      *             when an error occurs while parsing
210      * @throws IOException
211      *             when an error occurs while writing to the {@link
212      *             org.dom4j.io.XMLWriter}
213      */
214     public Document modify(InputStream source) throws DocumentException,
215             IOException {
216         try {
217             return installModifier().modify(source);
218         } catch (JAXBRuntimeException ex) {
219             Throwable cause = ex.getCause();
220             throw new DocumentException(cause.getMessage(), cause);
221         }
222     }
223 
224     /***
225      * Parses the specified {@link java.io.InputStream}with SAX.
226      * 
227      * @param source
228      *            the inputstream to parse
229      * @param systemId
230      *            the URI of the given inputstream
231      * 
232      * @return the resulting DOM4J document
233      * 
234      * @throws DocumentException
235      *             when an error occurs while parsing
236      * @throws IOException
237      *             when an error occurs while writing to the {@link
238      *             org.dom4j.io.XMLWriter}
239      */
240     public Document modify(InputStream source, String systemId)
241             throws DocumentException, IOException {
242         try {
243             return installModifier().modify(source);
244         } catch (JAXBRuntimeException ex) {
245             Throwable cause = ex.getCause();
246             throw new DocumentException(cause.getMessage(), cause);
247         }
248     }
249 
250     /***
251      * Parses the specified {@link java.io.Reader}with SAX.
252      * 
253      * @param r
254      *            the reader to use for parsing
255      * 
256      * @return the resulting DOM4J document
257      * 
258      * @throws DocumentException
259      *             when an error occurs while parsing
260      * @throws IOException
261      *             when an error occurs while writing to the {@link
262      *             org.dom4j.io.XMLWriter}
263      */
264     public Document modify(Reader r) throws DocumentException, IOException {
265         try {
266             return installModifier().modify(r);
267         } catch (JAXBRuntimeException ex) {
268             Throwable cause = ex.getCause();
269             throw new DocumentException(cause.getMessage(), cause);
270         }
271     }
272 
273     /***
274      * Parses the specified {@link java.io.Reader}with SAX.
275      * 
276      * @param source
277      *            the reader to parse
278      * @param systemId
279      *            the URI of the given reader
280      * 
281      * @return the resulting DOM4J document
282      * 
283      * @throws DocumentException
284      *             when an error occurs while parsing
285      * @throws IOException
286      *             when an error occurs while writing to the {@link
287      *             org.dom4j.io.XMLWriter}
288      */
289     public Document modify(Reader source, String systemId)
290             throws DocumentException, IOException {
291         try {
292             return installModifier().modify(source);
293         } catch (JAXBRuntimeException ex) {
294             Throwable cause = ex.getCause();
295             throw new DocumentException(cause.getMessage(), cause);
296         }
297     }
298 
299     /***
300      * Parses the the given URL or filename.
301      * 
302      * @param url
303      *            the URL or filename to parse
304      * 
305      * @return the resulting DOM4J document
306      * 
307      * @throws DocumentException
308      *             when an error occurs while parsing
309      * @throws IOException
310      *             when an error occurs while writing to the {@link
311      *             org.dom4j.io.XMLWriter}
312      */
313     public Document modify(String url) throws DocumentException, IOException {
314         try {
315             return installModifier().modify(url);
316         } catch (JAXBRuntimeException ex) {
317             Throwable cause = ex.getCause();
318             throw new DocumentException(cause.getMessage(), cause);
319         }
320     }
321 
322     /***
323      * Parses the the given URL.
324      * 
325      * @param source
326      *            the URL to parse
327      * 
328      * @return the resulting DOM4J document
329      * 
330      * @throws DocumentException
331      *             when an error occurs while parsing
332      * @throws IOException
333      *             when an error occurs while writing to the {@link
334      *             org.dom4j.io.XMLWriter}
335      */
336     public Document modify(URL source) throws DocumentException, IOException {
337         try {
338             return installModifier().modify(source);
339         } catch (JAXBRuntimeException ex) {
340             Throwable cause = ex.getCause();
341             throw new DocumentException(cause.getMessage(), cause);
342         }
343     }
344 
345     /***
346      * Sets the Output to write the (modified) xml document to.
347      * 
348      * @param file
349      *            the {@link java.io.File}to write to
350      * 
351      * @throws IOException
352      *             when the file cannot be found or when the outputformat
353      */
354     public void setOutput(File file) throws IOException {
355         createXMLWriter().setOutputStream(new FileOutputStream(file));
356     }
357 
358     /***
359      * Sets the Output to write the (modified) xml document to.
360      * 
361      * @param outputStream
362      *            the {@link java.io.OutputStream}to write to
363      * 
364      * @throws IOException
365      *             when an error occurs
366      */
367     public void setOutput(OutputStream outputStream) throws IOException {
368         createXMLWriter().setOutputStream(outputStream);
369     }
370 
371     /***
372      * Sets the Output to write the (modified) xml document to.
373      * 
374      * @param writer
375      *            the {@link java.io.Writer}to write to
376      * 
377      * @throws IOException
378      *             when an error occurs
379      */
380     public void setOutput(Writer writer) throws IOException {
381         createXMLWriter().setWriter(writer);
382     }
383 
384     /***
385      * Adds the {@link JAXBObjectModifier}to be called when the specified xml
386      * path is encounted while parsing the source.
387      * 
388      * @param path
389      *            the element path to listen for
390      * @param mod
391      *            the modifier to register
392      */
393     public void addObjectModifier(String path, JAXBObjectModifier mod) {
394         modifiers.put(path, mod);
395     }
396 
397     /***
398      * Removes the {@link JAXBObjectModifier}from the event based processor,
399      * for the specified element path.
400      * 
401      * @param path
402      *            the xml path to remove the modifier for
403      */
404     public void removeObjectModifier(String path) {
405         modifiers.remove(path);
406         getModifier().removeModifier(path);
407     }
408 
409     /***
410      * Removes all registered {@link JAXBObjectModifier}instances from the
411      * event based processor.
412      */
413     public void resetObjectModifiers() {
414         modifiers.clear();
415         getModifier().resetModifiers();
416     }
417 
418     /***
419      * Returns true when the modified {@link org.dom4j.Document}is not kept in
420      * memory.
421      * 
422      * @return Returns true if elements are pruned.
423      */
424     public boolean isPruneElements() {
425         return pruneElements;
426     }
427 
428     /***
429      * Define whether the modified {@link org.dom4j.Document}must only be
430      * written to the output and pruned from the DOM4J tree.
431      * 
432      * @param pruneElements
433      *            When true, elements will not be kept in memory
434      */
435     public void setPruneElements(boolean pruneElements) {
436         this.pruneElements = pruneElements;
437     }
438 
439     private SAXModifier installModifier() throws IOException {
440         modifier = new SAXModifier(isPruneElements());
441 
442         modifier.resetModifiers();
443 
444         Iterator modifierIt = modifiers.entrySet().iterator();
445 
446         while (modifierIt.hasNext()) {
447             Map.Entry entry = (Map.Entry) modifierIt.next();
448             ElementModifier mod = new JAXBElementModifier(this,
449                     (JAXBObjectModifier) entry.getValue());
450             getModifier().addModifier((String) entry.getKey(), mod);
451         }
452 
453         modifier.setXMLWriter(getXMLWriter());
454 
455         return modifier;
456     }
457 
458     private SAXModifier getModifier() {
459         if (this.modifier == null) {
460             modifier = new SAXModifier(isPruneElements());
461         }
462 
463         return modifier;
464     }
465 
466     private XMLWriter getXMLWriter() {
467         return xmlWriter;
468     }
469 
470     private XMLWriter createXMLWriter() throws IOException {
471         if (this.xmlWriter == null) {
472             xmlWriter = new XMLWriter(outputFormat);
473         }
474 
475         return xmlWriter;
476     }
477 
478     private class JAXBElementModifier implements ElementModifier {
479         private JAXBModifier jaxbModifier;
480 
481         private JAXBObjectModifier objectModifier;
482 
483         public JAXBElementModifier(JAXBModifier jaxbModifier,
484                 JAXBObjectModifier objectModifier) {
485             this.jaxbModifier = jaxbModifier;
486             this.objectModifier = objectModifier;
487         }
488 
489         public org.dom4j.Element modifyElement(org.dom4j.Element element)
490                 throws Exception {
491             javax.xml.bind.Element originalObject = jaxbModifier
492                     .unmarshal(element);
493             javax.xml.bind.Element modifiedObject = objectModifier
494                     .modifyObject(originalObject);
495 
496             return jaxbModifier.marshal(modifiedObject);
497         }
498     }
499 }
500 
501 /*
502  * Redistribution and use of this software and associated documentation
503  * ("Software"), with or without modification, are permitted provided that the
504  * following conditions are met:
505  * 
506  * 1. Redistributions of source code must retain copyright statements and
507  * notices. Redistributions must also contain a copy of this document.
508  * 
509  * 2. Redistributions in binary form must reproduce the above copyright notice,
510  * this list of conditions and the following disclaimer in the documentation
511  * and/or other materials provided with the distribution.
512  * 
513  * 3. The name "DOM4J" must not be used to endorse or promote products derived
514  * from this Software without prior written permission of MetaStuff, Ltd. For
515  * written permission, please contact dom4j-info@metastuff.com.
516  * 
517  * 4. Products derived from this Software may not be called "DOM4J" nor may
518  * "DOM4J" appear in their names without prior written permission of MetaStuff,
519  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
520  * 
521  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
522  * 
523  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
524  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
525  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
526  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
527  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
528  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
529  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
530  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
531  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
532  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
533  * POSSIBILITY OF SUCH DAMAGE.
534  * 
535  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
536  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/jaxb/JAXBWriter.html0000644000175000017500000006612010242117761021325 0ustar ebourgebourg JAXBWriter xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.jaxb;
9   
10  import java.io.File;
11  import java.io.FileOutputStream;
12  import java.io.IOException;
13  import java.io.OutputStream;
14  import java.io.Writer;
15  
16  import javax.xml.bind.JAXBException;
17  
18  import org.dom4j.Element;
19  import org.dom4j.io.OutputFormat;
20  import org.dom4j.io.XMLWriter;
21  
22  import org.xml.sax.SAXException;
23  
24  /***
25   * Writes {@link javax.xml.bind.Element}objects to an XML stream. {@link
26   * javax.xml.bind.Element} instances can be created using the ObjectFactory that
27   * is generated by the JAXB compiler.
28   * 
29   * @author Wonne Keysers (Realsoftware.be)
30   * 
31   * @see org.dom4j.io.XMLWriter
32   * @see javax.xml.bind.JAXBContext
33   */
34  public class JAXBWriter extends JAXBSupport {
35      private XMLWriter xmlWriter;
36  
37      private OutputFormat outputFormat;
38  
39      /***
40       * Creates a new JAXBWriter for the given JAXB context path. This is the
41       * Java package where JAXB can find the generated XML classes. This package
42       * MUST contain jaxb.properties!
43       * 
44       * @param contextPath
45       *            JAXB context path to be used
46       * 
47       * @see javax.xml.bind.JAXBContext
48       */
49      public JAXBWriter(String contextPath) {
50          super(contextPath);
51          outputFormat = new OutputFormat();
52      }
53  
54      /***
55       * Creates a new JAXBWriter for the given JAXB context path. The specied
56       * {@link org.dom4j.io.OutputFormat}will be used for writing the XML
57       * stream.
58       * 
59       * @param contextPath
60       *            JAXB context path to be used
61       * @param outputFormat
62       *            the DOM4J {@link org.dom4j.io.OutputFormat}to be used
63       * 
64       * @see javax.xml.bind.JAXBContext
65       */
66      public JAXBWriter(String contextPath, OutputFormat outputFormat) {
67          super(contextPath);
68          this.outputFormat = outputFormat;
69      }
70  
71      /***
72       * Creates a new JAXBWriter for the given JAXB context path, using the
73       * specified {@link java.lang.Classloader}. (This is the Java package where
74       * JAXB can find the generated XML classes. This package MUST contain
75       * jaxb.properties!)
76       * 
77       * @param contextPath
78       *            JAXB context path to be used
79       * @param classloader
80       *            the classloader to be used for loading JAXB
81       * 
82       * @see javax.xml.bind.JAXBContext
83       */
84      public JAXBWriter(String contextPath, ClassLoader classloader) {
85          super(contextPath, classloader);
86      }
87  
88      /***
89       * Creates a new JAXBWriter for the given JAXB context path, using the
90       * specified {@link java.lang.Classloader}. The specied {@link
91       * org.dom4j.io.OutputFormat} will be used while writing the XML stream.
92       * 
93       * @param contextPath
94       *            JAXB context path to be used
95       * @param classloader
96       *            the class loader to be used to load JAXB
97       * @param outputFormat
98       *            the DOM4J {@link org.dom4j.io.OutputFormat}to be used
99       * 
100      * @see javax.xml.bind.JAXBContext
101      */
102     public JAXBWriter(String contextPath, ClassLoader classloader,
103             OutputFormat outputFormat) {
104         super(contextPath, classloader);
105         this.outputFormat = outputFormat;
106     }
107 
108     /***
109      * Returns the OutputFormat that will be used when writing the XML stream.
110      * 
111      * @return Returns the output format.
112      */
113     public OutputFormat getOutputFormat() {
114         return outputFormat;
115     }
116 
117     /***
118      * Defines to write the resulting output to the specified {@link
119      * java.io.File}.
120      * 
121      * @param file
122      *            file to write to
123      * 
124      * @throws IOException
125      *             when the file cannot be found
126      */
127     public void setOutput(File file) throws IOException {
128         getWriter().setOutputStream(new FileOutputStream(file));
129     }
130 
131     /***
132      * Defines to write the resulting output to the specified {@link
133      * java.io.OutputStream}
134      * 
135      * @param outputStream
136      *            outputStream to write to.
137      * 
138      * @throws IOException
139      *             DOCUMENT ME!
140      */
141     public void setOutput(OutputStream outputStream) throws IOException {
142         getWriter().setOutputStream(outputStream);
143     }
144 
145     /***
146      * Defines to write the resulting output to the specified {@link Writer}.
147      * 
148      * @param writer
149      *            writer to write to
150      * 
151      * @throws IOException
152      */
153     public void setOutput(Writer writer) throws IOException {
154         getWriter().setWriter(writer);
155     }
156 
157     /***
158      * Start a document by writing the initial XML declaration to the output.
159      * This must be done prior to writing any other elements.
160      * 
161      * @throws IOException
162      *             if an error occured while writing the output
163      * @throws SAXException
164      *             thrown by the underlying SAX driver
165      */
166     public void startDocument() throws IOException, SAXException {
167         getWriter().startDocument();
168     }
169 
170     /***
171      * Stop writing the document to the output. This must be done when all other
172      * elements are finished.
173      * 
174      * @throws IOException
175      *             if an error occured while writing the output
176      * @throws SAXException
177      *             thrown by the underlying SAX driver
178      */
179     public void endDocument() throws IOException, SAXException {
180         getWriter().endDocument();
181     }
182 
183     /***
184      * Writes the specified {@link javax.xml.bind.Element}to the document.
185      * {@link javax.xml.bind.Element}instances can be created using the
186      * ObjectFactory that is generated by the JAXB compiler.
187      * 
188      * @param jaxbObject
189      * 
190      * @throws IOException
191      *             if an error occured while writing the output
192      * @throws JAXBException
193      *             when an error occured while marshalling the jaxbObject
194      */
195     public void write(javax.xml.bind.Element jaxbObject) throws IOException,
196             JAXBException {
197         getWriter().write(marshal(jaxbObject));
198     }
199 
200     /***
201      * Writes the closing tag of the specified {@link javax.xml.bind.Element}to
202      * the document. This method can be used for writing {@link
203      * javax.xml.bind.Element} instances can be created using the ObjectFactory
204      * that is generated by the JAXB compiler.
205      * 
206      * @param jaxbObject
207      *            the JAXB element to write
208      * 
209      * @throws IOException
210      *             if an error occured while writing the output
211      * @throws JAXBException
212      *             when an error occured while marshalling the jaxbObject
213      */
214     public void writeClose(javax.xml.bind.Element jaxbObject)
215             throws IOException, JAXBException {
216         getWriter().writeClose(marshal(jaxbObject));
217     }
218 
219     /***
220      * Writes the opening tag of the specified {@link javax.xml.bind.Element}to
221      * the document. {@link javax.xml.bind.Element}instances can be created
222      * using the ObjectFactory that is generated by the JAXB compiler.
223      * 
224      * @param jaxbObject
225      *            the JAXB element to write
226      * 
227      * @throws IOException
228      *             if an error occured while writing the output
229      * @throws JAXBException
230      *             when an error occured while marshalling the jaxbObject
231      */
232     public void writeOpen(javax.xml.bind.Element jaxbObject)
233             throws IOException, JAXBException {
234         getWriter().writeOpen(marshal(jaxbObject));
235     }
236 
237     /***
238      * Writes the specified {@link org.dom4j.Element}to the document.
239      * 
240      * @param element
241      *            the {@link org.dom4j.Element}to write
242      * 
243      * @throws IOException
244      *             if an error occured while writing the output
245      */
246     public void writeElement(Element element) throws IOException {
247         getWriter().write(element);
248     }
249 
250     /***
251      * Writes the closing tag of the specified {@link org.dom4j.Element}to the
252      * document.
253      * 
254      * @param element
255      *            the {@link org.dom4j.Element}to write
256      * 
257      * @throws IOException
258      *             if an error occured while writing the output
259      */
260     public void writeCloseElement(Element element) throws IOException {
261         getWriter().writeClose(element);
262     }
263 
264     /***
265      * Writes the opening tag of the specified {@link org.dom4j.Element}to the
266      * document.
267      * 
268      * @param element
269      *            the {@link org.dom4j.Element}to write
270      * 
271      * @throws IOException
272      *             if an error occured while writing the output
273      */
274     public void writeOpenElement(Element element) throws IOException {
275         getWriter().writeOpen(element);
276     }
277 
278     private XMLWriter getWriter() throws IOException {
279         if (xmlWriter == null) {
280             if (this.outputFormat != null) {
281                 xmlWriter = new XMLWriter(outputFormat);
282             } else {
283                 xmlWriter = new XMLWriter();
284             }
285         }
286 
287         return xmlWriter;
288     }
289 }
290 
291 /*
292  * Redistribution and use of this software and associated documentation
293  * ("Software"), with or without modification, are permitted provided that the
294  * following conditions are met:
295  * 
296  * 1. Redistributions of source code must retain copyright statements and
297  * notices. Redistributions must also contain a copy of this document.
298  * 
299  * 2. Redistributions in binary form must reproduce the above copyright notice,
300  * this list of conditions and the following disclaimer in the documentation
301  * and/or other materials provided with the distribution.
302  * 
303  * 3. The name "DOM4J" must not be used to endorse or promote products derived
304  * from this Software without prior written permission of MetaStuff, Ltd. For
305  * written permission, please contact dom4j-info@metastuff.com.
306  * 
307  * 4. Products derived from this Software may not be called "DOM4J" nor may
308  * "DOM4J" appear in their names without prior written permission of MetaStuff,
309  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
310  * 
311  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
312  * 
313  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
314  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
315  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
316  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
317  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
318  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
319  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
320  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
321  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
322  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
323  * POSSIBILITY OF SUCH DAMAGE.
324  * 
325  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
326  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/jaxb/JAXBObjectModifier.html0000644000175000017500000001707110242117677022745 0ustar ebourgebourg JAXBObjectModifier xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.jaxb;
9   
10  import javax.xml.bind.Element;
11  
12  /***
13   * JAXBObjectHandler implementations can be registered with the {@link
14   * JAXBModifier} in order to change unmarshalled XML fragments.
15   * 
16   * @author Wonne Keysers (Realsoftware.be)
17   */
18  public interface JAXBObjectModifier {
19      /***
20       * Called when the {@link JAXBModifier}has finished parsing the xml path
21       * the handler was registered for. The provided object is the unmarshalled
22       * representation of the XML fragment. It can be casted to the appropriate
23       * implementation class that is generated by the JAXB compiler. <br>
24       * The modified JAXB element that returns from this method will be
25       * marshalled by the {@link JAXBModifier}and put in the DOM4J tree.
26       * 
27       * @param jaxbElement
28       *            the JAXB object to be modified
29       * 
30       * @return the modified JAXB object, or null when it must be removed.
31       * 
32       * @throws Exception
33       *             possibly thrown by the implementation.
34       */
35      Element modifyObject(Element jaxbElement) throws Exception;
36  }
37  
38  /*
39   * Redistribution and use of this software and associated documentation
40   * ("Software"), with or without modification, are permitted provided that the
41   * following conditions are met:
42   * 
43   * 1. Redistributions of source code must retain copyright statements and
44   * notices. Redistributions must also contain a copy of this document.
45   * 
46   * 2. Redistributions in binary form must reproduce the above copyright notice,
47   * this list of conditions and the following disclaimer in the documentation
48   * and/or other materials provided with the distribution.
49   * 
50   * 3. The name "DOM4J" must not be used to endorse or promote products derived
51   * from this Software without prior written permission of MetaStuff, Ltd. For
52   * written permission, please contact dom4j-info@metastuff.com.
53   * 
54   * 4. Products derived from this Software may not be called "DOM4J" nor may
55   * "DOM4J" appear in their names without prior written permission of MetaStuff,
56   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
57   * 
58   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
59   * 
60   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
61   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
62   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
64   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
65   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
66   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
67   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
68   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
69   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
70   * POSSIBILITY OF SUCH DAMAGE.
71   * 
72   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
73   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/jaxb/JAXBRuntimeException.html0000644000175000017500000001533310242117757023360 0ustar ebourgebourg JAXBRuntimeException xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.jaxb;
9   
10  /***
11   * Exception internally thrown by the JAXBReader classes. This is a
12   * RuntimeException since the {@link org.dom4j.ElementHandler}methods do not
13   * throw Exceptions.
14   * 
15   * @author Wonne Keysers (Realsoftware.be)
16   */
17  class JAXBRuntimeException extends RuntimeException {
18      /***
19       * DOCUMENT ME!
20       * 
21       * @param cause
22       *            The causing {@link java.lang.Throwable}
23       */
24      protected JAXBRuntimeException(Throwable cause) {
25          super(cause);
26      }
27  }
28  
29  /*
30   * Redistribution and use of this software and associated documentation
31   * ("Software"), with or without modification, are permitted provided that the
32   * following conditions are met:
33   * 
34   * 1. Redistributions of source code must retain copyright statements and
35   * notices. Redistributions must also contain a copy of this document.
36   * 
37   * 2. Redistributions in binary form must reproduce the above copyright notice,
38   * this list of conditions and the following disclaimer in the documentation
39   * and/or other materials provided with the distribution.
40   * 
41   * 3. The name "DOM4J" must not be used to endorse or promote products derived
42   * from this Software without prior written permission of MetaStuff, Ltd. For
43   * written permission, please contact dom4j-info@metastuff.com.
44   * 
45   * 4. Products derived from this Software may not be called "DOM4J" nor may
46   * "DOM4J" appear in their names without prior written permission of MetaStuff,
47   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
48   * 
49   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
50   * 
51   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
52   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
53   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
54   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
55   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
56   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
57   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
58   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
59   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
60   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
61   * POSSIBILITY OF SUCH DAMAGE.
62   * 
63   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
64   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/Node.html0000644000175000017500000014035310242117751017345 0ustar ebourgebourg Node xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import java.io.IOException;
11  import java.io.Writer;
12  import java.util.List;
13  
14  /***
15   * <p>
16   * <code>Node</code> defines the polymorphic behavior for all XML nodes in a
17   * dom4j tree.
18   * </p>
19   * 
20   * <p>
21   * A node can be output as its XML format, can be detached from its position in
22   * a document and can have XPath expressions evaluated on itself.
23   * </p>
24   * 
25   * <p>
26   * A node may optionally support the parent relationship and may be read only.
27   * </p>
28   * 
29   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
30   * @version $Revision: 1.31 $
31   * 
32   * @see #supportsParent
33   * @see #isReadOnly
34   */
35  public interface Node extends Cloneable {
36      // W3C DOM complient node type codes
37  
38      /*** Matches Element nodes */
39      short ANY_NODE = 0;
40  
41      /*** Matches Element nodes */
42      short ELEMENT_NODE = 1;
43  
44      /*** Matches elements nodes */
45      short ATTRIBUTE_NODE = 2;
46  
47      /*** Matches elements nodes */
48      short TEXT_NODE = 3;
49  
50      /*** Matches elements nodes */
51      short CDATA_SECTION_NODE = 4;
52  
53      /*** Matches elements nodes */
54      short ENTITY_REFERENCE_NODE = 5;
55  
56      /*** Matches elements nodes */
57  
58      // public static final short ENTITY_NODE = 6;
59      /*** Matches ProcessingInstruction */
60      short PROCESSING_INSTRUCTION_NODE = 7;
61  
62      /*** Matches Comments nodes */
63      short COMMENT_NODE = 8;
64  
65      /*** Matches Document nodes */
66      short DOCUMENT_NODE = 9;
67  
68      /*** Matches DocumentType nodes */
69      short DOCUMENT_TYPE_NODE = 10;
70  
71      // public static final short DOCUMENT_FRAGMENT_NODE = 11;
72      // public static final short NOTATION_NODE = 12;
73  
74      /*** Matchs a Namespace Node - NOTE this differs from DOM */
75  
76      // XXXX: ????
77      short NAMESPACE_NODE = 13;
78  
79      /*** Does not match any valid node */
80      short UNKNOWN_NODE = 14;
81  
82      /*** The maximum number of node types for sizing purposes */
83      short MAX_NODE_TYPE = 14;
84  
85      /***
86       * <p>
87       * <code>supportsParent</code> returns true if this node supports the
88       * parent relationship.
89       * </p>
90       * 
91       * <p>
92       * Some XML tree implementations are singly linked and only support downward
93       * navigation through children relationships. The default case is that both
94       * parent and children relationships are supported though for memory and
95       * performance reasons the parent relationship may not be supported.
96       * </p>
97       * 
98       * @return true if this node supports the parent relationship or false it is
99       *         not supported
100      */
101     boolean supportsParent();
102 
103     /***
104      * <p>
105      * <code>getParent</code> returns the parent <code>Element</code> if
106      * this node supports the parent relationship or null if it is the root
107      * element or does not support the parent relationship.
108      * </p>
109      * 
110      * <p>
111      * This method is an optional feature and may not be supported for all
112      * <code>Node</code> implementations.
113      * </p>
114      * 
115      * @return the parent of this node or null if it is the root of the tree or
116      *         the parent relationship is not supported.
117      */
118     Element getParent();
119 
120     /***
121      * <p>
122      * <code>setParent</code> sets the parent relationship of this node if the
123      * parent relationship is supported or does nothing if the parent
124      * relationship is not supported.
125      * </p>
126      * 
127      * <p>
128      * This method should only be called from inside an <code>Element</code>
129      * implementation method and is not intended for general use.
130      * </p>
131      * 
132      * @param parent
133      *            is the new parent of this node.
134      */
135     void setParent(Element parent);
136 
137     /***
138      * <p>
139      * <code>getDocument</code> returns the <code>Document</code> that this
140      * <code>Node</code> is part of if this node supports the parent
141      * relationship.
142      * </p>
143      * 
144      * <p>
145      * This method is an optional feature and may not be supported for all
146      * <code>Node</code> implementations.
147      * </p>
148      * 
149      * @return the document of this node or null if this feature is not
150      *         supported or the node is not associated with a
151      *         <code>Document</code>
152      */
153     Document getDocument();
154 
155     /***
156      * <p>
157      * <code>setDocument</code> sets the document of this node if the parent
158      * relationship is supported or does nothing if the parent relationship is
159      * not supported.
160      * </p>
161      * 
162      * <p>
163      * This method should only be called from inside a <code>Document</code>
164      * implementation method and is not intended for general use.
165      * </p>
166      * 
167      * @param document
168      *            is the new document of this node.
169      */
170     void setDocument(Document document);
171 
172     /***
173      * <p>
174      * <code>isReadOnly</code> returns true if this node is read only and
175      * cannot be modified. Any attempt to modify a read-only <code>Node</code>
176      * will result in an <code>UnsupportedOperationException</code> being
177      * thrown.
178      * </p>
179      * 
180      * @return true if this <code>Node</code> is read only and cannot be
181      *         modified otherwise false.
182      */
183     boolean isReadOnly();
184 
185     /***
186      * <p>
187      * <code>hasContent</code> returns true if this node is a Branch (either
188      * an Element or a Document) and it contains at least one content node such
189      * as a child Element or Text node.
190      * </p>
191      * 
192      * @return true if this <code>Node</code> is a Branch with a nodeCount()
193      *         of one or more.
194      */
195     boolean hasContent();
196 
197     /***
198      * <p>
199      * <code>getName</code> returns the name of this node. This is the XML
200      * local name of the element, attribute, entity or processing instruction.
201      * For CDATA and Text nodes this method will return null.
202      * </p>
203      * 
204      * @return the XML name of this node
205      */
206     String getName();
207 
208     /***
209      * <p>
210      * Sets the text data of this node or this method will throw an
211      * <code>UnsupportedOperationException</code> if it is read-only.
212      * </p>
213      * 
214      * @param name
215      *            is the new name of this node
216      */
217     void setName(String name);
218 
219     /***
220      * <p>
221      * Returns the text of this node.
222      * </p>
223      * 
224      * @return the text for this node.
225      */
226     String getText();
227 
228     /***
229      * <p>
230      * Sets the text data of this node or this method will throw an
231      * <code>UnsupportedOperationException</code> if it is read-only.
232      * </p>
233      * 
234      * @param text
235      *            is the new textual value of this node
236      */
237     void setText(String text);
238 
239     /***
240      * Returns the XPath string-value of this node. The behaviour of this method
241      * is defined in the <a href="http://www.w3.org/TR/xpath">XPath
242      * specification </a>.
243      * 
244      * @return the text from all the child Text and Element nodes appended
245      *         together.
246      */
247     String getStringValue();
248 
249     /***
250      * <p>
251      * Returns the XPath expression which will return a node set containing the
252      * given node such as /a/b/&#64;c. No indexing will be used to restrict the
253      * path if multiple elements with the same name occur on the path.
254      * </p>
255      * 
256      * @return the XPath expression which will return a nodeset containing at
257      *         least this node.
258      */
259     String getPath();
260 
261     /***
262      * Returns the relative XPath expression which will return a node set
263      * containing the given node such as a/b/&#64;c. No indexing will be used to
264      * restrict the path if multiple elements with the same name occur on the
265      * path.
266      * 
267      * @param context
268      *            is the parent context from which the relative path should
269      *            start. If the context is null or the context is not an
270      *            ancestor of this node then the path will be absolute and start
271      *            from the document and so begin with the '/' character.
272      * 
273      * @return the XPath expression relative to the given context which will
274      *         return a nodeset containing at least this node.
275      */
276     String getPath(Element context);
277 
278     /***
279      * <p>
280      * Returns the XPath expression which will return a nodeset of one node
281      * which is the current node. This method will use the XPath index operator
282      * to restrict the path if multiple elements with the same name occur on the
283      * path.
284      * </p>
285      * 
286      * @return the XPath expression which will return a nodeset containing just
287      *         this node.
288      */
289     String getUniquePath();
290 
291     /***
292      * <p>
293      * Returns the relative unique XPath expression from the given context which
294      * will return a nodeset of one node which is the current node. This method
295      * will use the XPath index operator to restrict the path if multiple
296      * elements with the same name occur on the path.
297      * </p>
298      * 
299      * @param context
300      *            is the parent context from which the path should start. If the
301      *            context is null or the context is not an ancestor of this node
302      *            then the path will start from the document and so begin with
303      *            the '/' character.
304      * 
305      * @return the XPath expression relative to the given context which will
306      *         return a nodeset containing just this node.
307      */
308     String getUniquePath(Element context);
309 
310     /***
311      * <p>
312      * <code>asXML</code> returns the textual XML representation of this node.
313      * </p>
314      * 
315      * @return the XML representation of this node
316      */
317     String asXML();
318 
319     /***
320      * <p>
321      * <code>write</code> writes this node as the default XML notation for
322      * this node. If you wish to control the XML output (such as for pretty
323      * printing, changing the indentation policy etc.) then please use {@link
324      * org.dom4j.io.XMLWriter} or its derivations.
325      * </p>
326      * 
327      * @param writer
328      *            is the <code>Writer</code> to output the XML to
329      * 
330      * @throws IOException
331      *             DOCUMENT ME!
332      */
333     void write(Writer writer) throws IOException;
334 
335     /***
336      * Returns the code according to the type of node. This makes processing
337      * nodes polymorphically much easier as the switch statement can be used
338      * instead of multiple if (instanceof) statements.
339      * 
340      * @return a W3C DOM complient code for the node type such as ELEMENT_NODE
341      *         or ATTRIBUTE_NODE
342      */
343     short getNodeType();
344 
345     /***
346      * DOCUMENT ME!
347      * 
348      * @return the name of the type of node such as "Document", "Element",
349      *         "Attribute" or "Text"
350      */
351     String getNodeTypeName();
352 
353     /***
354      * <p>
355      * Removes this node from its parent if there is one. If this node is the
356      * root element of a document then it is removed from the document as well.
357      * </p>
358      * 
359      * <p>
360      * This method is useful if you want to remove a node from its source
361      * document and add it to another document. For example
362      * </p>
363      * <code> Node node = ...; Element someOtherElement = ...;
364      * someOtherElement.add( node.detach() ); </code>
365      * 
366      * @return the node that has been removed from its parent node if any and
367      *         its document if any.
368      */
369     Node detach();
370 
371     /***
372      * <p>
373      * <code>selectNodes</code> evaluates an XPath expression and returns the
374      * result as a <code>List</code> of <code>Node</code> instances or
375      * <code>String</code> instances depending on the XPath expression.
376      * </p>
377      * 
378      * @param xpathExpression
379      *            is the XPath expression to be evaluated
380      * 
381      * @return the list of <code>Node</code> or <code>String</code>
382      *         instances depending on the XPath expression
383      */
384     List selectNodes(String xpathExpression);
385 
386     /***
387      * <p>
388      * <code>selectObject</code> evaluates an XPath expression and returns the
389      * result as an {@link Object}. The object returned can either be a {@link
390      * List} of one or more {@link Node}instances or a scalar object like a
391      * {@link String}or a {@link Number}instance depending on the XPath
392      * expression.
393      * </p>
394      * 
395      * @param xpathExpression
396      *            is the XPath expression to be evaluated
397      * 
398      * @return the value of the XPath expression as a {@link List}of {@link
399      *         Node} instances, a {@link String}or a {@link Number}instance
400      *         depending on the XPath expression.
401      */
402     Object selectObject(String xpathExpression);
403 
404     /***
405      * <p>
406      * <code>selectNodes</code> evaluates an XPath expression then sorts the
407      * results using a secondary XPath expression Returns a sorted
408      * <code>List</code> of <code>Node</code> instances.
409      * </p>
410      * 
411      * @param xpathExpression
412      *            is the XPath expression to be evaluated
413      * @param comparisonXPathExpression
414      *            is the XPath expression used to compare the results by for
415      *            sorting
416      * 
417      * @return the list of <code>Node</code> instances sorted by the
418      *         comparisonXPathExpression
419      */
420     List selectNodes(String xpathExpression, String comparisonXPathExpression);
421 
422     /***
423      * <p>
424      * <code>selectNodes</code> evaluates an XPath expression then sorts the
425      * results using a secondary XPath expression Returns a sorted
426      * <code>List</code> of <code>Node</code> instances.
427      * </p>
428      * 
429      * @param xpathExpression
430      *            is the XPath expression to be evaluated
431      * @param comparisonXPathExpression
432      *            is the XPath expression used to compare the results by for
433      *            sorting
434      * @param removeDuplicates
435      *            if this parameter is true then duplicate values (using the
436      *            comparisonXPathExpression) are removed from the result List.
437      * 
438      * @return the list of <code>Node</code> instances sorted by the
439      *         comparisonXPathExpression
440      */
441     List selectNodes(String xpathExpression, String comparisonXPathExpression,
442             boolean removeDuplicates);
443 
444     /***
445      * <p>
446      * <code>selectSingleNode</code> evaluates an XPath expression and returns
447      * the result as a single <code>Node</code> instance.
448      * </p>
449      * 
450      * @param xpathExpression
451      *            is the XPath expression to be evaluated
452      * 
453      * @return the <code>Node</code> matching the XPath expression
454      */
455     Node selectSingleNode(String xpathExpression);
456 
457     /***
458      * <p>
459      * <code>valueOf</code> evaluates an XPath expression and returns the
460      * textual representation of the results the XPath string-value of this
461      * node. The string-value for a given node type is defined in the <a
462      * href="http://www.w3.org/TR/xpath">XPath specification </a>.
463      * </p>
464      * 
465      * @param xpathExpression
466      *            is the XPath expression to be evaluated
467      * 
468      * @return the string-value representation of the results of the XPath
469      *         expression
470      */
471     String valueOf(String xpathExpression);
472 
473     /***
474      * <p>
475      * <code>numberValueOf</code> evaluates an XPath expression and returns
476      * the numeric value of the XPath expression if the XPath expression results
477      * in a number, or null if the result is not a number.
478      * </p>
479      * 
480      * @param xpathExpression
481      *            is the XPath expression to be evaluated
482      * 
483      * @return the numeric result of the XPath expression or null if the result
484      *         is not a number.
485      */
486     Number numberValueOf(String xpathExpression);
487 
488     /***
489      * <p>
490      * <code>matches</code> returns true if evaluating the given XPath
491      * expression on this node returns a non-empty node set containing this
492      * node.
493      * </p>
494      * 
495      * <p>
496      * This method does not behave like the &lt;xsl:if&gt; element - if you want
497      * that behaviour, to evaluate if an XPath expression matches something,
498      * then you can use the following code to be equivalent...
499      * </p>
500      * <code>if ( node.selectSingleNode( "/some/path" ) != nulll )</code>
501      * 
502      * @param xpathExpression
503      *            is an XPath expression
504      * 
505      * @return true if this node is returned by the given XPath expression
506      */
507     boolean matches(String xpathExpression);
508 
509     /***
510      * <p>
511      * <code>createXPath</code> creates an XPath object for the given
512      * xpathExpression. The XPath object allows the variable context to be
513      * specified.
514      * </p>
515      * 
516      * @param xpathExpression
517      *            is the XPath expression to be evaluated
518      * 
519      * @return an XPath object represeting the given expression
520      * 
521      * @throws InvalidXPathException
522      *             if the XPath expression is invalid
523      */
524     XPath createXPath(String xpathExpression) throws InvalidXPathException;
525 
526     /***
527      * <p>
528      * <code>asXPathResult</code> returns a version of this node which is
529      * capable of being an XPath result. The result of an XPath expression
530      * should always support the parent relationship, whether the original XML
531      * tree was singly or doubly linked. If the node does not support the parent
532      * relationship then a new node will be created which is linked to its
533      * parent and returned.
534      * </p>
535      * 
536      * @param parent
537      *            DOCUMENT ME!
538      * 
539      * @return a <code>Node</code> which supports the parent relationship
540      */
541     Node asXPathResult(Element parent);
542 
543     /***
544      * <p>
545      * <code>accept</code> is the method used in the Visitor Pattern.
546      * </p>
547      * 
548      * @param visitor
549      *            is the visitor in the Visitor Pattern
550      */
551     void accept(Visitor visitor);
552 
553     /***
554      * <p>
555      * <code>clone</code> will return a deep clone or if this node is
556      * read-only then clone will return the same instance.
557      * </p>
558      * 
559      * @return a deep clone of myself or myself if I am read only.
560      */
561     Object clone();
562 }
563 
564 /*
565  * Redistribution and use of this software and associated documentation
566  * ("Software"), with or without modification, are permitted provided that the
567  * following conditions are met:
568  * 
569  * 1. Redistributions of source code must retain copyright statements and
570  * notices. Redistributions must also contain a copy of this document.
571  * 
572  * 2. Redistributions in binary form must reproduce the above copyright notice,
573  * this list of conditions and the following disclaimer in the documentation
574  * and/or other materials provided with the distribution.
575  * 
576  * 3. The name "DOM4J" must not be used to endorse or promote products derived
577  * from this Software without prior written permission of MetaStuff, Ltd. For
578  * written permission, please contact dom4j-info@metastuff.com.
579  * 
580  * 4. Products derived from this Software may not be called "DOM4J" nor may
581  * "DOM4J" appear in their names without prior written permission of MetaStuff,
582  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
583  * 
584  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
585  * 
586  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
587  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
588  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
589  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
590  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
591  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
592  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
593  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
594  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
595  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
596  * POSSIBILITY OF SUCH DAMAGE.
597  * 
598  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
599  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dom/0000755000175000017500000000000012133227266016347 5ustar ebourgebourgdom4j-1.6.1/docs/xref/org/dom4j/dom/DOMText.html0000644000175000017500000005471110242117723020524 0ustar ebourgebourg DOMText xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dom;
9   
10  import org.dom4j.Element;
11  import org.dom4j.Text;
12  import org.dom4j.tree.DefaultText;
13  
14  import org.w3c.dom.DOMException;
15  import org.w3c.dom.Document;
16  import org.w3c.dom.NamedNodeMap;
17  import org.w3c.dom.NodeList;
18  
19  /***
20   * <p>
21   * <code>DOMText</code> implements a Text node which supports the W3C DOM API.
22   * </p>
23   * 
24   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
25   * @version $Revision: 1.12 $
26   */
27  public class DOMText extends DefaultText implements org.w3c.dom.Text {
28      public DOMText(String text) {
29          super(text);
30      }
31  
32      public DOMText(Element parent, String text) {
33          super(parent, text);
34      }
35  
36      // org.w3c.dom.Node interface
37      // -------------------------------------------------------------------------
38      public boolean supports(String feature, String version) {
39          return DOMNodeHelper.supports(this, feature, version);
40      }
41  
42      public String getNamespaceURI() {
43          return DOMNodeHelper.getNamespaceURI(this);
44      }
45  
46      public String getPrefix() {
47          return DOMNodeHelper.getPrefix(this);
48      }
49  
50      public void setPrefix(String prefix) throws DOMException {
51          DOMNodeHelper.setPrefix(this, prefix);
52      }
53  
54      public String getLocalName() {
55          return DOMNodeHelper.getLocalName(this);
56      }
57  
58      public String getNodeName() {
59          return "#text";
60      }
61  
62      // already part of API
63      //
64      // public short getNodeType();
65      public String getNodeValue() throws DOMException {
66          return DOMNodeHelper.getNodeValue(this);
67      }
68  
69      public void setNodeValue(String nodeValue) throws DOMException {
70          DOMNodeHelper.setNodeValue(this, nodeValue);
71      }
72  
73      public org.w3c.dom.Node getParentNode() {
74          return DOMNodeHelper.getParentNode(this);
75      }
76  
77      public NodeList getChildNodes() {
78          return DOMNodeHelper.getChildNodes(this);
79      }
80  
81      public org.w3c.dom.Node getFirstChild() {
82          return DOMNodeHelper.getFirstChild(this);
83      }
84  
85      public org.w3c.dom.Node getLastChild() {
86          return DOMNodeHelper.getLastChild(this);
87      }
88  
89      public org.w3c.dom.Node getPreviousSibling() {
90          return DOMNodeHelper.getPreviousSibling(this);
91      }
92  
93      public org.w3c.dom.Node getNextSibling() {
94          return DOMNodeHelper.getNextSibling(this);
95      }
96  
97      public NamedNodeMap getAttributes() {
98          return null;
99      }
100 
101     public Document getOwnerDocument() {
102         return DOMNodeHelper.getOwnerDocument(this);
103     }
104 
105     public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
106             org.w3c.dom.Node refChild) throws DOMException {
107         checkNewChildNode(newChild);
108 
109         return DOMNodeHelper.insertBefore(this, newChild, refChild);
110     }
111 
112     public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
113             org.w3c.dom.Node oldChild) throws DOMException {
114         checkNewChildNode(newChild);
115 
116         return DOMNodeHelper.replaceChild(this, newChild, oldChild);
117     }
118 
119     public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
120             throws DOMException {
121         return DOMNodeHelper.removeChild(this, oldChild);
122     }
123 
124     public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
125             throws DOMException {
126         checkNewChildNode(newChild);
127 
128         return DOMNodeHelper.appendChild(this, newChild);
129     }
130 
131     private void checkNewChildNode(org.w3c.dom.Node newChild)
132             throws DOMException {
133         throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
134                 "Text nodes cannot have children");
135     }
136 
137     public boolean hasChildNodes() {
138         return DOMNodeHelper.hasChildNodes(this);
139     }
140 
141     public org.w3c.dom.Node cloneNode(boolean deep) {
142         return DOMNodeHelper.cloneNode(this, deep);
143     }
144 
145     public void normalize() {
146         DOMNodeHelper.normalize(this);
147     }
148 
149     public boolean isSupported(String feature, String version) {
150         return DOMNodeHelper.isSupported(this, feature, version);
151     }
152 
153     public boolean hasAttributes() {
154         return DOMNodeHelper.hasAttributes(this);
155     }
156 
157     // org.w3c.dom.CharacterData interface
158     // -------------------------------------------------------------------------
159     public String getData() throws DOMException {
160         return DOMNodeHelper.getData(this);
161     }
162 
163     public void setData(String data) throws DOMException {
164         DOMNodeHelper.setData(this, data);
165     }
166 
167     public int getLength() {
168         return DOMNodeHelper.getLength(this);
169     }
170 
171     public String substringData(int offset, int count) throws DOMException {
172         return DOMNodeHelper.substringData(this, offset, count);
173     }
174 
175     public void appendData(String arg) throws DOMException {
176         DOMNodeHelper.appendData(this, arg);
177     }
178 
179     public void insertData(int offset, String arg) throws DOMException {
180         DOMNodeHelper.insertData(this, offset, arg);
181     }
182 
183     public void deleteData(int offset, int count) throws DOMException {
184         DOMNodeHelper.deleteData(this, offset, count);
185     }
186 
187     public void replaceData(int offset, int count, String arg)
188             throws DOMException {
189         DOMNodeHelper.replaceData(this, offset, count, arg);
190     }
191 
192     // org.w3c.dom.Text interface
193     // -------------------------------------------------------------------------
194     public org.w3c.dom.Text splitText(int offset) throws DOMException {
195         if (isReadOnly()) {
196             throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
197                     "CharacterData node is read only: " + this);
198         } else {
199             String text = getText();
200             int length = (text != null) ? text.length() : 0;
201 
202             if ((offset < 0) || (offset >= length)) {
203                 throw new DOMException(DOMException.INDEX_SIZE_ERR,
204                         "No text at offset: " + offset);
205             } else {
206                 String start = text.substring(0, offset);
207                 String rest = text.substring(offset);
208                 setText(start);
209 
210                 Element parent = getParent();
211                 Text newText = createText(rest);
212 
213                 if (parent != null) {
214                     parent.add(newText);
215                 }
216 
217                 return DOMNodeHelper.asDOMText(newText);
218             }
219         }
220     }
221 
222     // Implementation methods
223     // -------------------------------------------------------------------------
224     protected Text createText(String text) {
225         return new DOMText(text);
226     }
227 }
228 
229 /*
230  * Redistribution and use of this software and associated documentation
231  * ("Software"), with or without modification, are permitted provided that the
232  * following conditions are met:
233  * 
234  * 1. Redistributions of source code must retain copyright statements and
235  * notices. Redistributions must also contain a copy of this document.
236  * 
237  * 2. Redistributions in binary form must reproduce the above copyright notice,
238  * this list of conditions and the following disclaimer in the documentation
239  * and/or other materials provided with the distribution.
240  * 
241  * 3. The name "DOM4J" must not be used to endorse or promote products derived
242  * from this Software without prior written permission of MetaStuff, Ltd. For
243  * written permission, please contact dom4j-info@metastuff.com.
244  * 
245  * 4. Products derived from this Software may not be called "DOM4J" nor may
246  * "DOM4J" appear in their names without prior written permission of MetaStuff,
247  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
248  * 
249  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
250  * 
251  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
252  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
253  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
254  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
255  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
256  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
257  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
258  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
259  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
260  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
261  * POSSIBILITY OF SUCH DAMAGE.
262  * 
263  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
264  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dom/DOMElement.html0000644000175000017500000010626410242117606021172 0ustar ebourgebourg DOMElement xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dom;
9   
10  import java.util.ArrayList;
11  import java.util.List;
12  
13  import org.dom4j.Attribute;
14  import org.dom4j.DocumentFactory;
15  import org.dom4j.Namespace;
16  import org.dom4j.QName;
17  import org.dom4j.tree.DefaultElement;
18  
19  import org.w3c.dom.DOMException;
20  import org.w3c.dom.Document;
21  import org.w3c.dom.NamedNodeMap;
22  import org.w3c.dom.Node;
23  import org.w3c.dom.NodeList;
24  
25  /***
26   * <p>
27   * <code>DOMElement</code> implements an XML element which supports the W3C
28   * DOM API.
29   * </p>
30   * 
31   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
32   * @version $Revision: 1.23 $
33   */
34  public class DOMElement extends DefaultElement implements org.w3c.dom.Element {
35      /*** The <code>DocumentFactory</code> instance used by default */
36      private static final DocumentFactory DOCUMENT_FACTORY = DOMDocumentFactory
37              .getInstance();
38  
39      public DOMElement(String name) {
40          super(name);
41      }
42  
43      public DOMElement(QName qname) {
44          super(qname);
45      }
46  
47      public DOMElement(QName qname, int attributeCount) {
48          super(qname, attributeCount);
49      }
50  
51      public DOMElement(String name, Namespace namespace) {
52          super(name, namespace);
53      }
54  
55      // org.w3c.dom.Node interface
56      // -------------------------------------------------------------------------
57      public boolean supports(String feature, String version) {
58          return DOMNodeHelper.supports(this, feature, version);
59      }
60  
61      public String getNamespaceURI() {
62          return getQName().getNamespaceURI();
63      }
64  
65      public String getPrefix() {
66          return getQName().getNamespacePrefix();
67      }
68  
69      public void setPrefix(String prefix) throws DOMException {
70          DOMNodeHelper.setPrefix(this, prefix);
71      }
72  
73      public String getLocalName() {
74          return getQName().getName();
75      }
76  
77      public String getNodeName() {
78          return getName();
79      }
80  
81      // already part of API
82      //
83      // public short getNodeType();
84      public String getNodeValue() throws DOMException {
85          return null;
86      }
87  
88      public void setNodeValue(String nodeValue) throws DOMException {
89      }
90  
91      public org.w3c.dom.Node getParentNode() {
92          return DOMNodeHelper.getParentNode(this);
93      }
94  
95      public NodeList getChildNodes() {
96          return DOMNodeHelper.createNodeList(content());
97      }
98  
99      public org.w3c.dom.Node getFirstChild() {
100         return DOMNodeHelper.asDOMNode(node(0));
101     }
102 
103     public org.w3c.dom.Node getLastChild() {
104         return DOMNodeHelper.asDOMNode(node(nodeCount() - 1));
105     }
106 
107     public org.w3c.dom.Node getPreviousSibling() {
108         return DOMNodeHelper.getPreviousSibling(this);
109     }
110 
111     public org.w3c.dom.Node getNextSibling() {
112         return DOMNodeHelper.getNextSibling(this);
113     }
114 
115     public NamedNodeMap getAttributes() {
116         return new DOMAttributeNodeMap(this);
117     }
118 
119     public Document getOwnerDocument() {
120         return DOMNodeHelper.getOwnerDocument(this);
121     }
122 
123     public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
124             org.w3c.dom.Node refChild) throws DOMException {
125         checkNewChildNode(newChild);
126 
127         return DOMNodeHelper.insertBefore(this, newChild, refChild);
128     }
129 
130     public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
131             org.w3c.dom.Node oldChild) throws DOMException {
132         checkNewChildNode(newChild);
133 
134         return DOMNodeHelper.replaceChild(this, newChild, oldChild);
135     }
136 
137     public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
138             throws DOMException {
139         return DOMNodeHelper.removeChild(this, oldChild);
140     }
141 
142     public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
143             throws DOMException {
144         checkNewChildNode(newChild);
145 
146         return DOMNodeHelper.appendChild(this, newChild);
147     }
148 
149     private void checkNewChildNode(org.w3c.dom.Node newChild)
150             throws DOMException {
151         final int nodeType = newChild.getNodeType();
152 
153         if (!((nodeType == Node.ELEMENT_NODE) || (nodeType == Node.TEXT_NODE)
154                 || (nodeType == Node.COMMENT_NODE)
155                 || (nodeType == Node.PROCESSING_INSTRUCTION_NODE)
156                 || (nodeType == Node.CDATA_SECTION_NODE) 
157                 || (nodeType == Node.ENTITY_REFERENCE_NODE))) {
158             throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
159                     "Given node cannot be a child of element");
160         }
161     }
162 
163     public boolean hasChildNodes() {
164         return nodeCount() > 0;
165     }
166 
167     public org.w3c.dom.Node cloneNode(boolean deep) {
168         return DOMNodeHelper.cloneNode(this, deep);
169     }
170 
171     public boolean isSupported(String feature, String version) {
172         return DOMNodeHelper.isSupported(this, feature, version);
173     }
174 
175     public boolean hasAttributes() {
176         return DOMNodeHelper.hasAttributes(this);
177     }
178 
179     // org.w3c.dom.Element interface
180     // -------------------------------------------------------------------------
181     public String getTagName() {
182         return getName();
183     }
184 
185     public String getAttribute(String name) {
186         String answer = attributeValue(name);
187 
188         return (answer != null) ? answer : "";
189     }
190 
191     public void setAttribute(String name, String value) throws DOMException {
192         addAttribute(name, value);
193     }
194 
195     public void removeAttribute(String name) throws DOMException {
196         Attribute attribute = attribute(name);
197 
198         if (attribute != null) {
199             remove(attribute);
200         }
201     }
202 
203     public org.w3c.dom.Attr getAttributeNode(String name) {
204         return DOMNodeHelper.asDOMAttr(attribute(name));
205     }
206 
207     public org.w3c.dom.Attr setAttributeNode(org.w3c.dom.Attr newAttr)
208             throws DOMException {
209         if (this.isReadOnly()) {
210             throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
211                     "No modification allowed");
212         }
213 
214         Attribute attribute = attribute(newAttr);
215 
216         if (attribute != newAttr) {
217             if (newAttr.getOwnerElement() != null) {
218                 throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR,
219                         "Attribute is already in use");
220             }
221 
222             Attribute newAttribute = createAttribute(newAttr);
223 
224             if (attribute != null) {
225                 attribute.detach();
226             }
227 
228             add(newAttribute);
229         }
230 
231         return DOMNodeHelper.asDOMAttr(attribute);
232     }
233 
234     public org.w3c.dom.Attr removeAttributeNode(org.w3c.dom.Attr oldAttr)
235             throws DOMException {
236         Attribute attribute = attribute(oldAttr);
237 
238         if (attribute != null) {
239             attribute.detach();
240 
241             return DOMNodeHelper.asDOMAttr(attribute);
242         } else {
243             throw new DOMException(DOMException.NOT_FOUND_ERR,
244                     "No such attribute");
245         }
246     }
247 
248     public String getAttributeNS(String namespaceURI, String localName) {
249         Attribute attribute = attribute(namespaceURI, localName);
250 
251         if (attribute != null) {
252             String answer = attribute.getValue();
253 
254             if (answer != null) {
255                 return answer;
256             }
257         }
258 
259         return "";
260     }
261 
262     public void setAttributeNS(String namespaceURI, String qualifiedName,
263             String value) throws DOMException {
264         Attribute attribute = attribute(namespaceURI, qualifiedName);
265 
266         if (attribute != null) {
267             attribute.setValue(value);
268         } else {
269             QName qname = getQName(namespaceURI, qualifiedName);
270             addAttribute(qname, value);
271         }
272     }
273 
274     public void removeAttributeNS(String namespaceURI, String localName)
275             throws DOMException {
276         Attribute attribute = attribute(namespaceURI, localName);
277 
278         if (attribute != null) {
279             remove(attribute);
280         }
281     }
282 
283     public org.w3c.dom.Attr getAttributeNodeNS(String namespaceURI,
284             String localName) {
285         Attribute attribute = attribute(namespaceURI, localName);
286 
287         if (attribute != null) {
288             DOMNodeHelper.asDOMAttr(attribute);
289         }
290 
291         return null;
292     }
293 
294     public org.w3c.dom.Attr setAttributeNodeNS(org.w3c.dom.Attr newAttr)
295             throws DOMException {
296         Attribute attribute = attribute(newAttr.getNamespaceURI(), newAttr
297                 .getLocalName());
298 
299         if (attribute != null) {
300             attribute.setValue(newAttr.getValue());
301         } else {
302             attribute = createAttribute(newAttr);
303             add(attribute);
304         }
305 
306         return DOMNodeHelper.asDOMAttr(attribute);
307     }
308 
309     public NodeList getElementsByTagName(String name) {
310         ArrayList list = new ArrayList();
311         DOMNodeHelper.appendElementsByTagName(list, this, name);
312 
313         return DOMNodeHelper.createNodeList(list);
314     }
315 
316     public NodeList getElementsByTagNameNS(String namespace, String lName) {
317         ArrayList list = new ArrayList();
318         DOMNodeHelper.appendElementsByTagNameNS(list, this, namespace, lName);
319 
320         return DOMNodeHelper.createNodeList(list);
321     }
322 
323     public boolean hasAttribute(String name) {
324         return attribute(name) != null;
325     }
326 
327     public boolean hasAttributeNS(String namespaceURI, String localName) {
328         return attribute(namespaceURI, localName) != null;
329     }
330 
331     // Implementation methods
332     // -------------------------------------------------------------------------
333     protected DocumentFactory getDocumentFactory() {
334         DocumentFactory factory = getQName().getDocumentFactory();
335 
336         return (factory != null) ? factory : DOCUMENT_FACTORY;
337     }
338 
339     protected Attribute attribute(org.w3c.dom.Attr attr) {
340         return attribute(DOCUMENT_FACTORY.createQName(attr.getLocalName(), attr
341                 .getPrefix(), attr.getNamespaceURI()));
342     }
343 
344     protected Attribute attribute(String namespaceURI, String localName) {
345         List attributes = attributeList();
346         int size = attributes.size();
347 
348         for (int i = 0; i < size; i++) {
349             Attribute attribute = (Attribute) attributes.get(i);
350 
351             if (localName.equals(attribute.getName())
352                     && (((namespaceURI == null || namespaceURI.length() == 0)
353                           && ((attribute.getNamespaceURI() == null) 
354                               || (attribute.getNamespaceURI().length() == 0)))
355                               || ((namespaceURI != null) && namespaceURI
356                                       .equals(attribute.getNamespaceURI())))) {
357                 return attribute;
358             }
359         }
360 
361         return null;
362     }
363 
364     protected Attribute createAttribute(org.w3c.dom.Attr newAttr) {
365         QName qname = null;
366         String name = newAttr.getLocalName();
367 
368         if (name != null) {
369             String prefix = newAttr.getPrefix();
370             String uri = newAttr.getNamespaceURI();
371             qname = getDocumentFactory().createQName(name, prefix, uri);
372         } else {
373             name = newAttr.getName();
374             qname = getDocumentFactory().createQName(name);
375         }
376 
377         return new DOMAttribute(qname, newAttr.getValue());
378     }
379 
380     protected QName getQName(String namespace, String qualifiedName) {
381         int index = qualifiedName.indexOf(':');
382         String prefix = "";
383         String localName = qualifiedName;
384 
385         if (index >= 0) {
386             prefix = qualifiedName.substring(0, index);
387             localName = qualifiedName.substring(index + 1);
388         }
389 
390         return getDocumentFactory().createQName(localName, prefix, namespace);
391     }
392 }
393 
394 /*
395  * Redistribution and use of this software and associated documentation
396  * ("Software"), with or without modification, are permitted provided that the
397  * following conditions are met:
398  * 
399  * 1. Redistributions of source code must retain copyright statements and
400  * notices. Redistributions must also contain a copy of this document.
401  * 
402  * 2. Redistributions in binary form must reproduce the above copyright notice,
403  * this list of conditions and the following disclaimer in the documentation
404  * and/or other materials provided with the distribution.
405  * 
406  * 3. The name "DOM4J" must not be used to endorse or promote products derived
407  * from this Software without prior written permission of MetaStuff, Ltd. For
408  * written permission, please contact dom4j-info@metastuff.com.
409  * 
410  * 4. Products derived from this Software may not be called "DOM4J" nor may
411  * "DOM4J" appear in their names without prior written permission of MetaStuff,
412  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
413  * 
414  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
415  * 
416  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
417  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
418  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
419  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
420  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
421  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
422  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
423  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
424  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
425  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
426  * POSSIBILITY OF SUCH DAMAGE.
427  * 
428  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
429  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dom/DOMNamespace.html0000644000175000017500000003723010242117606021471 0ustar ebourgebourg DOMNamespace xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dom;
9   
10  import org.dom4j.Element;
11  import org.dom4j.tree.DefaultNamespace;
12  
13  import org.w3c.dom.DOMException;
14  import org.w3c.dom.Document;
15  import org.w3c.dom.NamedNodeMap;
16  import org.w3c.dom.NodeList;
17  
18  /***
19   * <p>
20   * <code>DOMNamespace</code> implements a Namespace that is compatable with
21   * the DOM API.
22   * </p>
23   * 
24   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
25   * @version $Revision: 1.10 $
26   */
27  public class DOMNamespace extends DefaultNamespace implements org.w3c.dom.Node {
28      public DOMNamespace(String prefix, String uri) {
29          super(prefix, uri);
30      }
31  
32      public DOMNamespace(Element parent, String prefix, String uri) {
33          super(parent, prefix, uri);
34      }
35  
36      // org.w3c.dom.Node interface
37      // -------------------------------------------------------------------------
38      public boolean supports(String feature, String version) {
39          return DOMNodeHelper.supports(this, feature, version);
40      }
41  
42      public String getNamespaceURI() {
43          return DOMNodeHelper.getNamespaceURI(this);
44      }
45  
46      // public String getPrefix() {
47      // return DOMNodeHelper.getPrefix(this);
48      // }
49      public void setPrefix(String prefix) throws DOMException {
50          DOMNodeHelper.setPrefix(this, prefix);
51      }
52  
53      public String getLocalName() {
54          return DOMNodeHelper.getLocalName(this);
55      }
56  
57      public String getNodeName() {
58          return getName();
59      }
60  
61      // already part of API
62      //
63      // public short getNodeType();
64      public String getNodeValue() throws DOMException {
65          return DOMNodeHelper.getNodeValue(this);
66      }
67  
68      public void setNodeValue(String nodeValue) throws DOMException {
69          DOMNodeHelper.setNodeValue(this, nodeValue);
70      }
71  
72      public org.w3c.dom.Node getParentNode() {
73          return DOMNodeHelper.getParentNode(this);
74      }
75  
76      public NodeList getChildNodes() {
77          return DOMNodeHelper.getChildNodes(this);
78      }
79  
80      public org.w3c.dom.Node getFirstChild() {
81          return DOMNodeHelper.getFirstChild(this);
82      }
83  
84      public org.w3c.dom.Node getLastChild() {
85          return DOMNodeHelper.getLastChild(this);
86      }
87  
88      public org.w3c.dom.Node getPreviousSibling() {
89          return DOMNodeHelper.getPreviousSibling(this);
90      }
91  
92      public org.w3c.dom.Node getNextSibling() {
93          return DOMNodeHelper.getNextSibling(this);
94      }
95  
96      public NamedNodeMap getAttributes() {
97          return DOMNodeHelper.getAttributes(this);
98      }
99  
100     public Document getOwnerDocument() {
101         return DOMNodeHelper.getOwnerDocument(this);
102     }
103 
104     public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
105             org.w3c.dom.Node refChild) throws DOMException {
106         return DOMNodeHelper.insertBefore(this, newChild, refChild);
107     }
108 
109     public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
110             org.w3c.dom.Node oldChild) throws DOMException {
111         return DOMNodeHelper.replaceChild(this, newChild, oldChild);
112     }
113 
114     public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
115             throws DOMException {
116         return DOMNodeHelper.removeChild(this, oldChild);
117     }
118 
119     public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
120             throws DOMException {
121         return DOMNodeHelper.appendChild(this, newChild);
122     }
123 
124     public boolean hasChildNodes() {
125         return DOMNodeHelper.hasChildNodes(this);
126     }
127 
128     public org.w3c.dom.Node cloneNode(boolean deep) {
129         return DOMNodeHelper.cloneNode(this, deep);
130     }
131 
132     public void normalize() {
133         DOMNodeHelper.normalize(this);
134     }
135 
136     public boolean isSupported(String feature, String version) {
137         return DOMNodeHelper.isSupported(this, feature, version);
138     }
139 
140     public boolean hasAttributes() {
141         return DOMNodeHelper.hasAttributes(this);
142     }
143 }
144 
145 /*
146  * Redistribution and use of this software and associated documentation
147  * ("Software"), with or without modification, are permitted provided that the
148  * following conditions are met:
149  * 
150  * 1. Redistributions of source code must retain copyright statements and
151  * notices. Redistributions must also contain a copy of this document.
152  * 
153  * 2. Redistributions in binary form must reproduce the above copyright notice,
154  * this list of conditions and the following disclaimer in the documentation
155  * and/or other materials provided with the distribution.
156  * 
157  * 3. The name "DOM4J" must not be used to endorse or promote products derived
158  * from this Software without prior written permission of MetaStuff, Ltd. For
159  * written permission, please contact dom4j-info@metastuff.com.
160  * 
161  * 4. Products derived from this Software may not be called "DOM4J" nor may
162  * "DOM4J" appear in their names without prior written permission of MetaStuff,
163  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
164  * 
165  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
166  * 
167  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
168  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
169  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
170  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
171  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
172  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
173  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
174  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
175  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
176  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
177  * POSSIBILITY OF SUCH DAMAGE.
178  * 
179  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
180  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dom/package-summary.html0000644000175000017500000000773310242117707022332 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.dom

Class Summary
DOMAttribute
DOMAttributeNodeMap
DOMCDATA
DOMComment
DOMDocument
DOMDocumentFactory
DOMDocumentType
DOMElement
DOMEntityReference
DOMNamespace
DOMNodeHelper
DOMProcessingInstruction
DOMText
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref/org/dom4j/dom/DOMProcessingInstruction.html0000644000175000017500000004525010242117555024157 0ustar ebourgebourg DOMProcessingInstruction xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dom;
9   
10  import java.util.Map;
11  
12  import org.dom4j.Element;
13  import org.dom4j.tree.DefaultProcessingInstruction;
14  
15  import org.w3c.dom.DOMException;
16  import org.w3c.dom.Document;
17  import org.w3c.dom.NamedNodeMap;
18  import org.w3c.dom.NodeList;
19  
20  /***
21   * <p>
22   * <code>DOMProcessingInstruction</code> implements a ProcessingInstruction
23   * node which supports the W3C DOM API.
24   * </p>
25   * 
26   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
27   * @version $Revision: 1.12 $
28   */
29  public class DOMProcessingInstruction extends DefaultProcessingInstruction
30          implements org.w3c.dom.ProcessingInstruction {
31      public DOMProcessingInstruction(String target, Map values) {
32          super(target, values);
33      }
34  
35      public DOMProcessingInstruction(String target, String values) {
36          super(target, values);
37      }
38  
39      public DOMProcessingInstruction(Element parent, String target, String val) {
40          super(parent, target, val);
41      }
42  
43      // org.w3c.dom.Node interface
44      // -------------------------------------------------------------------------
45      public boolean supports(String feature, String version) {
46          return DOMNodeHelper.supports(this, feature, version);
47      }
48  
49      public String getNamespaceURI() {
50          return DOMNodeHelper.getNamespaceURI(this);
51      }
52  
53      public String getPrefix() {
54          return DOMNodeHelper.getPrefix(this);
55      }
56  
57      public void setPrefix(String prefix) throws DOMException {
58          DOMNodeHelper.setPrefix(this, prefix);
59      }
60  
61      public String getLocalName() {
62          return DOMNodeHelper.getLocalName(this);
63      }
64  
65      public String getNodeName() {
66          return getName();
67      }
68  
69      // already part of API
70      //
71      // public short getNodeType();
72      public String getNodeValue() throws DOMException {
73          return DOMNodeHelper.getNodeValue(this);
74      }
75  
76      public void setNodeValue(String nodeValue) throws DOMException {
77          DOMNodeHelper.setNodeValue(this, nodeValue);
78      }
79  
80      public org.w3c.dom.Node getParentNode() {
81          return DOMNodeHelper.getParentNode(this);
82      }
83  
84      public NodeList getChildNodes() {
85          return DOMNodeHelper.getChildNodes(this);
86      }
87  
88      public org.w3c.dom.Node getFirstChild() {
89          return DOMNodeHelper.getFirstChild(this);
90      }
91  
92      public org.w3c.dom.Node getLastChild() {
93          return DOMNodeHelper.getLastChild(this);
94      }
95  
96      public org.w3c.dom.Node getPreviousSibling() {
97          return DOMNodeHelper.getPreviousSibling(this);
98      }
99  
100     public org.w3c.dom.Node getNextSibling() {
101         return DOMNodeHelper.getNextSibling(this);
102     }
103 
104     public NamedNodeMap getAttributes() {
105         return null;
106     }
107 
108     public Document getOwnerDocument() {
109         return DOMNodeHelper.getOwnerDocument(this);
110     }
111 
112     public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
113             org.w3c.dom.Node refChild) throws DOMException {
114         checkNewChildNode(newChild);
115 
116         return DOMNodeHelper.insertBefore(this, newChild, refChild);
117     }
118 
119     public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
120             org.w3c.dom.Node oldChild) throws DOMException {
121         checkNewChildNode(newChild);
122 
123         return DOMNodeHelper.replaceChild(this, newChild, oldChild);
124     }
125 
126     public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
127             throws DOMException {
128         return DOMNodeHelper.removeChild(this, oldChild);
129     }
130 
131     public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
132             throws DOMException {
133         checkNewChildNode(newChild);
134 
135         return DOMNodeHelper.appendChild(this, newChild);
136     }
137 
138     private void checkNewChildNode(org.w3c.dom.Node newChild)
139             throws DOMException {
140         throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
141                 "PI nodes cannot have children");
142     }
143 
144     public boolean hasChildNodes() {
145         return DOMNodeHelper.hasChildNodes(this);
146     }
147 
148     public org.w3c.dom.Node cloneNode(boolean deep) {
149         return DOMNodeHelper.cloneNode(this, deep);
150     }
151 
152     public void normalize() {
153         DOMNodeHelper.normalize(this);
154     }
155 
156     public boolean isSupported(String feature, String version) {
157         return DOMNodeHelper.isSupported(this, feature, version);
158     }
159 
160     public boolean hasAttributes() {
161         return DOMNodeHelper.hasAttributes(this);
162     }
163 
164     // org.w3c.dom.ProcessingInstruction interface
165     // -------------------------------------------------------------------------
166     // public String getTarget();
167     public String getData() {
168         return getText();
169     }
170 
171     public void setData(String data) throws DOMException {
172         if (isReadOnly()) {
173             throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
174                     "This ProcessingInstruction is read only");
175         } else {
176             setText(data);
177         }
178     }
179 
180     // Implementation methods
181     // -------------------------------------------------------------------------
182 }
183 
184 /*
185  * Redistribution and use of this software and associated documentation
186  * ("Software"), with or without modification, are permitted provided that the
187  * following conditions are met:
188  * 
189  * 1. Redistributions of source code must retain copyright statements and
190  * notices. Redistributions must also contain a copy of this document.
191  * 
192  * 2. Redistributions in binary form must reproduce the above copyright notice,
193  * this list of conditions and the following disclaimer in the documentation
194  * and/or other materials provided with the distribution.
195  * 
196  * 3. The name "DOM4J" must not be used to endorse or promote products derived
197  * from this Software without prior written permission of MetaStuff, Ltd. For
198  * written permission, please contact dom4j-info@metastuff.com.
199  * 
200  * 4. Products derived from this Software may not be called "DOM4J" nor may
201  * "DOM4J" appear in their names without prior written permission of MetaStuff,
202  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
203  * 
204  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
205  * 
206  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
207  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
208  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
209  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
210  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
211  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
212  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
213  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
214  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
215  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
216  * POSSIBILITY OF SUCH DAMAGE.
217  * 
218  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
219  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dom/DOMAttribute.html0000644000175000017500000004534310242117732021544 0ustar ebourgebourg DOMAttribute xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dom;
9   
10  import org.dom4j.Element;
11  import org.dom4j.QName;
12  import org.dom4j.tree.DefaultAttribute;
13  
14  import org.w3c.dom.DOMException;
15  import org.w3c.dom.Document;
16  import org.w3c.dom.NamedNodeMap;
17  import org.w3c.dom.NodeList;
18  
19  /***
20   * <p>
21   * <code>DOMAttribute</code> implements a doubly linked attribute which
22   * supports the W3C DOM API.
23   * </p>
24   * 
25   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
26   * @version $Revision: 1.14 $
27   */
28  public class DOMAttribute extends DefaultAttribute implements org.w3c.dom.Attr {
29      public DOMAttribute(QName qname) {
30          super(qname);
31      }
32  
33      public DOMAttribute(QName qname, String value) {
34          super(qname, value);
35      }
36  
37      public DOMAttribute(Element parent, QName qname, String value) {
38          super(parent, qname, value);
39      }
40  
41      // org.w3c.dom.Node interface
42      // -------------------------------------------------------------------------
43      public boolean supports(String feature, String version) {
44          return DOMNodeHelper.supports(this, feature, version);
45      }
46  
47      public String getNamespaceURI() {
48          return getQName().getNamespaceURI();
49      }
50  
51      public String getPrefix() {
52          return getQName().getNamespacePrefix();
53      }
54  
55      public void setPrefix(String prefix) throws DOMException {
56          DOMNodeHelper.setPrefix(this, prefix);
57      }
58  
59      public String getLocalName() {
60          return getQName().getName();
61      }
62  
63      public String getNodeName() {
64          return getName();
65      }
66  
67      // already part of API
68      //
69      // public short getNodeType();
70      public String getNodeValue() throws DOMException {
71          return DOMNodeHelper.getNodeValue(this);
72      }
73  
74      public void setNodeValue(String nodeValue) throws DOMException {
75          DOMNodeHelper.setNodeValue(this, nodeValue);
76      }
77  
78      public org.w3c.dom.Node getParentNode() {
79          // Per http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-637646024
80          // and the NIST conformance tests, Attr.getParentNode() should always
81          // return null
82          return null;
83      }
84  
85      public NodeList getChildNodes() {
86          return DOMNodeHelper.getChildNodes(this);
87      }
88  
89      public org.w3c.dom.Node getFirstChild() {
90          return DOMNodeHelper.getFirstChild(this);
91      }
92  
93      public org.w3c.dom.Node getLastChild() {
94          return DOMNodeHelper.getLastChild(this);
95      }
96  
97      public org.w3c.dom.Node getPreviousSibling() {
98          return DOMNodeHelper.getPreviousSibling(this);
99      }
100 
101     public org.w3c.dom.Node getNextSibling() {
102         return DOMNodeHelper.getNextSibling(this);
103     }
104 
105     public NamedNodeMap getAttributes() {
106         return null;
107     }
108 
109     public Document getOwnerDocument() {
110         return DOMNodeHelper.getOwnerDocument(this);
111     }
112 
113     public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
114             org.w3c.dom.Node refChild) throws DOMException {
115         checkNewChildNode(newChild);
116 
117         return DOMNodeHelper.insertBefore(this, newChild, refChild);
118     }
119 
120     public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
121             org.w3c.dom.Node oldChild) throws DOMException {
122         checkNewChildNode(newChild);
123 
124         return DOMNodeHelper.replaceChild(this, newChild, oldChild);
125     }
126 
127     public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
128             throws DOMException {
129         return DOMNodeHelper.removeChild(this, oldChild);
130     }
131 
132     public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
133             throws DOMException {
134         checkNewChildNode(newChild);
135 
136         return DOMNodeHelper.appendChild(this, newChild);
137     }
138 
139     private void checkNewChildNode(org.w3c.dom.Node newChild)
140             throws DOMException {
141         final int nodeType = newChild.getNodeType();
142 
143         if (!((nodeType == org.w3c.dom.Node.TEXT_NODE) 
144                 || (nodeType == org.w3c.dom.Node.ENTITY_REFERENCE_NODE))) {
145             throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
146                     "The node cannot be a child of attribute");
147         }
148     }
149 
150     public boolean hasChildNodes() {
151         return DOMNodeHelper.hasChildNodes(this);
152     }
153 
154     public org.w3c.dom.Node cloneNode(boolean deep) {
155         return DOMNodeHelper.cloneNode(this, deep);
156     }
157 
158     public void normalize() {
159         DOMNodeHelper.normalize(this);
160     }
161 
162     public boolean isSupported(String feature, String version) {
163         return DOMNodeHelper.isSupported(this, feature, version);
164     }
165 
166     public boolean hasAttributes() {
167         return DOMNodeHelper.hasAttributes(this);
168     }
169 
170     // org.w3c.dom.Attr interface
171     // -------------------------------------------------------------------------
172     // public String getName();
173     public boolean getSpecified() {
174         return true;
175     }
176 
177     // public String getValue();
178     // public void setValue(String value) throws DOMException;
179     public org.w3c.dom.Element getOwnerElement() {
180         return DOMNodeHelper.asDOMElement(getParent());
181     }
182 }
183 
184 /*
185  * Redistribution and use of this software and associated documentation
186  * ("Software"), with or without modification, are permitted provided that the
187  * following conditions are met:
188  * 
189  * 1. Redistributions of source code must retain copyright statements and
190  * notices. Redistributions must also contain a copy of this document.
191  * 
192  * 2. Redistributions in binary form must reproduce the above copyright notice,
193  * this list of conditions and the following disclaimer in the documentation
194  * and/or other materials provided with the distribution.
195  * 
196  * 3. The name "DOM4J" must not be used to endorse or promote products derived
197  * from this Software without prior written permission of MetaStuff, Ltd. For
198  * written permission, please contact dom4j-info@metastuff.com.
199  * 
200  * 4. Products derived from this Software may not be called "DOM4J" nor may
201  * "DOM4J" appear in their names without prior written permission of MetaStuff,
202  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
203  * 
204  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
205  * 
206  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
207  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
208  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
209  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
210  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
211  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
212  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
213  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
214  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
215  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
216  * POSSIBILITY OF SUCH DAMAGE.
217  * 
218  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
219  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dom/DOMCDATA.html0000644000175000017500000005505210242117606020413 0ustar ebourgebourg DOMCDATA xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dom;
9   
10  import org.dom4j.CDATA;
11  import org.dom4j.Element;
12  import org.dom4j.tree.DefaultCDATA;
13  
14  import org.w3c.dom.DOMException;
15  import org.w3c.dom.Document;
16  import org.w3c.dom.NamedNodeMap;
17  import org.w3c.dom.NodeList;
18  
19  /***
20   * <p>
21   * <code>DOMCDATA</code> implements a CDATA Section which supports the W3C DOM
22   * API.
23   * </p>
24   * 
25   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
26   * @version $Revision: 1.12 $
27   */
28  public class DOMCDATA extends DefaultCDATA implements org.w3c.dom.CDATASection {
29      public DOMCDATA(String text) {
30          super(text);
31      }
32  
33      public DOMCDATA(Element parent, String text) {
34          super(parent, text);
35      }
36  
37      // org.w3c.dom.Node interface
38      // -------------------------------------------------------------------------
39      public boolean supports(String feature, String version) {
40          return DOMNodeHelper.supports(this, feature, version);
41      }
42  
43      public String getNamespaceURI() {
44          return DOMNodeHelper.getNamespaceURI(this);
45      }
46  
47      public String getPrefix() {
48          return DOMNodeHelper.getPrefix(this);
49      }
50  
51      public void setPrefix(String prefix) throws DOMException {
52          DOMNodeHelper.setPrefix(this, prefix);
53      }
54  
55      public String getLocalName() {
56          return DOMNodeHelper.getLocalName(this);
57      }
58  
59      public String getNodeName() {
60          return "#cdata-section";
61      }
62  
63      // already part of API
64      //
65      // public short getNodeType();
66      public String getNodeValue() throws DOMException {
67          return DOMNodeHelper.getNodeValue(this);
68      }
69  
70      public void setNodeValue(String nodeValue) throws DOMException {
71          DOMNodeHelper.setNodeValue(this, nodeValue);
72      }
73  
74      public org.w3c.dom.Node getParentNode() {
75          return DOMNodeHelper.getParentNode(this);
76      }
77  
78      public NodeList getChildNodes() {
79          return DOMNodeHelper.getChildNodes(this);
80      }
81  
82      public org.w3c.dom.Node getFirstChild() {
83          return DOMNodeHelper.getFirstChild(this);
84      }
85  
86      public org.w3c.dom.Node getLastChild() {
87          return DOMNodeHelper.getLastChild(this);
88      }
89  
90      public org.w3c.dom.Node getPreviousSibling() {
91          return DOMNodeHelper.getPreviousSibling(this);
92      }
93  
94      public org.w3c.dom.Node getNextSibling() {
95          return DOMNodeHelper.getNextSibling(this);
96      }
97  
98      public NamedNodeMap getAttributes() {
99          return null;
100     }
101 
102     public Document getOwnerDocument() {
103         return DOMNodeHelper.getOwnerDocument(this);
104     }
105 
106     public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
107             org.w3c.dom.Node refChild) throws DOMException {
108         checkNewChildNode(newChild);
109 
110         return DOMNodeHelper.insertBefore(this, newChild, refChild);
111     }
112 
113     public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
114             org.w3c.dom.Node oldChild) throws DOMException {
115         checkNewChildNode(newChild);
116 
117         return DOMNodeHelper.replaceChild(this, newChild, oldChild);
118     }
119 
120     public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
121             throws DOMException {
122         return DOMNodeHelper.removeChild(this, oldChild);
123     }
124 
125     public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
126             throws DOMException {
127         checkNewChildNode(newChild);
128 
129         return DOMNodeHelper.appendChild(this, newChild);
130     }
131 
132     private void checkNewChildNode(org.w3c.dom.Node newChild)
133             throws DOMException {
134         throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
135                 "CDATASection nodes cannot have children");
136     }
137 
138     public boolean hasChildNodes() {
139         return DOMNodeHelper.hasChildNodes(this);
140     }
141 
142     public org.w3c.dom.Node cloneNode(boolean deep) {
143         return DOMNodeHelper.cloneNode(this, deep);
144     }
145 
146     public void normalize() {
147         DOMNodeHelper.normalize(this);
148     }
149 
150     public boolean isSupported(String feature, String version) {
151         return DOMNodeHelper.isSupported(this, feature, version);
152     }
153 
154     public boolean hasAttributes() {
155         return DOMNodeHelper.hasAttributes(this);
156     }
157 
158     // org.w3c.dom.CharacterData interface
159     // -------------------------------------------------------------------------
160     public String getData() throws DOMException {
161         return DOMNodeHelper.getData(this);
162     }
163 
164     public void setData(String data) throws DOMException {
165         DOMNodeHelper.setData(this, data);
166     }
167 
168     public int getLength() {
169         return DOMNodeHelper.getLength(this);
170     }
171 
172     public String substringData(int offset, int count) throws DOMException {
173         return DOMNodeHelper.substringData(this, offset, count);
174     }
175 
176     public void appendData(String arg) throws DOMException {
177         DOMNodeHelper.appendData(this, arg);
178     }
179 
180     public void insertData(int offset, String arg) throws DOMException {
181         DOMNodeHelper.insertData(this, offset, arg);
182     }
183 
184     public void deleteData(int offset, int count) throws DOMException {
185         DOMNodeHelper.deleteData(this, offset, count);
186     }
187 
188     public void replaceData(int offset, int count, String arg)
189             throws DOMException {
190         DOMNodeHelper.replaceData(this, offset, count, arg);
191     }
192 
193     // org.w3c.dom.Text interface
194     // -------------------------------------------------------------------------
195     public org.w3c.dom.Text splitText(int offset) throws DOMException {
196         if (isReadOnly()) {
197             throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
198                     "CharacterData node is read only: " + this);
199         } else {
200             String text = getText();
201             int length = (text != null) ? text.length() : 0;
202 
203             if ((offset < 0) || (offset >= length)) {
204                 throw new DOMException(DOMException.INDEX_SIZE_ERR,
205                         "No text at offset: " + offset);
206             } else {
207                 String start = text.substring(0, offset);
208                 String rest = text.substring(offset);
209                 setText(start);
210 
211                 Element parent = getParent();
212                 CDATA newText = createCDATA(rest);
213 
214                 if (parent != null) {
215                     parent.add(newText);
216                 }
217 
218                 return DOMNodeHelper.asDOMText(newText);
219             }
220         }
221     }
222 
223     // Implementation methods
224     // -------------------------------------------------------------------------
225     protected CDATA createCDATA(String text) {
226         return new DOMCDATA(text);
227     }
228 }
229 
230 /*
231  * Redistribution and use of this software and associated documentation
232  * ("Software"), with or without modification, are permitted provided that the
233  * following conditions are met:
234  * 
235  * 1. Redistributions of source code must retain copyright statements and
236  * notices. Redistributions must also contain a copy of this document.
237  * 
238  * 2. Redistributions in binary form must reproduce the above copyright notice,
239  * this list of conditions and the following disclaimer in the documentation
240  * and/or other materials provided with the distribution.
241  * 
242  * 3. The name "DOM4J" must not be used to endorse or promote products derived
243  * from this Software without prior written permission of MetaStuff, Ltd. For
244  * written permission, please contact dom4j-info@metastuff.com.
245  * 
246  * 4. Products derived from this Software may not be called "DOM4J" nor may
247  * "DOM4J" appear in their names without prior written permission of MetaStuff,
248  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
249  * 
250  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
251  * 
252  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
253  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
254  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
255  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
256  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
257  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
258  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
259  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
260  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
261  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
262  * POSSIBILITY OF SUCH DAMAGE.
263  * 
264  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
265  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dom/package-frame.html0000644000175000017500000000414010242117705021712 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.dom

org.dom4j.dom

Classes

  • DOMAttribute
  • DOMAttributeNodeMap
  • DOMCDATA
  • DOMComment
  • DOMDocument
  • DOMDocumentFactory
  • DOMDocumentType
  • DOMElement
  • DOMEntityReference
  • DOMNamespace
  • DOMNodeHelper
  • DOMProcessingInstruction
  • DOMText
dom4j-1.6.1/docs/xref/org/dom4j/dom/DOMEntityReference.html0000644000175000017500000004313010242117752022666 0ustar ebourgebourg DOMEntityReference xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dom;
9   
10  import org.dom4j.Element;
11  import org.dom4j.tree.DefaultEntity;
12  
13  import org.w3c.dom.DOMException;
14  import org.w3c.dom.Document;
15  import org.w3c.dom.NamedNodeMap;
16  import org.w3c.dom.NodeList;
17  
18  /***
19   * <p>
20   * <code>DOMEntity</code> implements a Entity node which supports the W3C DOM
21   * API.
22   * </p>
23   * 
24   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
25   * @version $Revision: 1.12 $
26   */
27  public class DOMEntityReference extends DefaultEntity implements
28          org.w3c.dom.EntityReference {
29      public DOMEntityReference(String name) {
30          super(name);
31      }
32  
33      public DOMEntityReference(String name, String text) {
34          super(name, text);
35      }
36  
37      public DOMEntityReference(Element parent, String name, String text) {
38          super(parent, name, text);
39      }
40  
41      // org.w3c.dom.Node interface
42      // -------------------------------------------------------------------------
43      public boolean supports(String feature, String version) {
44          return DOMNodeHelper.supports(this, feature, version);
45      }
46  
47      public String getNamespaceURI() {
48          return DOMNodeHelper.getNamespaceURI(this);
49      }
50  
51      public String getPrefix() {
52          return DOMNodeHelper.getPrefix(this);
53      }
54  
55      public void setPrefix(String prefix) throws DOMException {
56          DOMNodeHelper.setPrefix(this, prefix);
57      }
58  
59      public String getLocalName() {
60          return DOMNodeHelper.getLocalName(this);
61      }
62  
63      public String getNodeName() {
64          return getName();
65      }
66  
67      // already part of API
68      //
69      // public short getNodeType();
70      public String getNodeValue() throws DOMException {
71          return null;
72      }
73  
74      public void setNodeValue(String nodeValue) throws DOMException {
75      }
76  
77      public org.w3c.dom.Node getParentNode() {
78          return DOMNodeHelper.getParentNode(this);
79      }
80  
81      public NodeList getChildNodes() {
82          return DOMNodeHelper.getChildNodes(this);
83      }
84  
85      public org.w3c.dom.Node getFirstChild() {
86          return DOMNodeHelper.getFirstChild(this);
87      }
88  
89      public org.w3c.dom.Node getLastChild() {
90          return DOMNodeHelper.getLastChild(this);
91      }
92  
93      public org.w3c.dom.Node getPreviousSibling() {
94          return DOMNodeHelper.getPreviousSibling(this);
95      }
96  
97      public org.w3c.dom.Node getNextSibling() {
98          return DOMNodeHelper.getNextSibling(this);
99      }
100 
101     public NamedNodeMap getAttributes() {
102         return null;
103     }
104 
105     public Document getOwnerDocument() {
106         return DOMNodeHelper.getOwnerDocument(this);
107     }
108 
109     public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
110             org.w3c.dom.Node refChild) throws DOMException {
111         checkNewChildNode(newChild);
112 
113         return DOMNodeHelper.insertBefore(this, newChild, refChild);
114     }
115 
116     public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
117             org.w3c.dom.Node oldChild) throws DOMException {
118         checkNewChildNode(newChild);
119 
120         return DOMNodeHelper.replaceChild(this, newChild, oldChild);
121     }
122 
123     public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
124             throws DOMException {
125         return DOMNodeHelper.removeChild(this, oldChild);
126     }
127 
128     public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
129             throws DOMException {
130         checkNewChildNode(newChild);
131 
132         return DOMNodeHelper.appendChild(this, newChild);
133     }
134 
135     private void checkNewChildNode(org.w3c.dom.Node newChild)
136             throws DOMException {
137         final int nodeType = newChild.getNodeType();
138 
139         if (!((nodeType == org.w3c.dom.Node.ELEMENT_NODE)
140                 || (nodeType == org.w3c.dom.Node.TEXT_NODE)
141                 || (nodeType == org.w3c.dom.Node.COMMENT_NODE)
142                 || (nodeType == org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE)
143                 || (nodeType == org.w3c.dom.Node.CDATA_SECTION_NODE) 
144                 || (nodeType == org.w3c.dom.Node.ENTITY_REFERENCE_NODE))) {
145             throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
146                     "Given node cannot be a child of an entity " + "reference");
147         }
148     }
149 
150     public boolean hasChildNodes() {
151         return DOMNodeHelper.hasChildNodes(this);
152     }
153 
154     public org.w3c.dom.Node cloneNode(boolean deep) {
155         return DOMNodeHelper.cloneNode(this, deep);
156     }
157 
158     public void normalize() {
159         DOMNodeHelper.normalize(this);
160     }
161 
162     public boolean isSupported(String feature, String version) {
163         return DOMNodeHelper.isSupported(this, feature, version);
164     }
165 
166     public boolean hasAttributes() {
167         return DOMNodeHelper.hasAttributes(this);
168     }
169 }
170 
171 /*
172  * Redistribution and use of this software and associated documentation
173  * ("Software"), with or without modification, are permitted provided that the
174  * following conditions are met:
175  * 
176  * 1. Redistributions of source code must retain copyright statements and
177  * notices. Redistributions must also contain a copy of this document.
178  * 
179  * 2. Redistributions in binary form must reproduce the above copyright notice,
180  * this list of conditions and the following disclaimer in the documentation
181  * and/or other materials provided with the distribution.
182  * 
183  * 3. The name "DOM4J" must not be used to endorse or promote products derived
184  * from this Software without prior written permission of MetaStuff, Ltd. For
185  * written permission, please contact dom4j-info@metastuff.com.
186  * 
187  * 4. Products derived from this Software may not be called "DOM4J" nor may
188  * "DOM4J" appear in their names without prior written permission of MetaStuff,
189  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
190  * 
191  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
192  * 
193  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
194  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
195  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
196  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
197  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
198  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
199  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
200  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
201  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
202  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
203  * POSSIBILITY OF SUCH DAMAGE.
204  * 
205  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
206  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dom/DOMDocumentFactory.html0000644000175000017500000005073010242117750022703 0ustar ebourgebourg DOMDocumentFactory xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dom;
9   
10  import java.util.Map;
11  
12  import org.dom4j.Attribute;
13  import org.dom4j.CDATA;
14  import org.dom4j.Comment;
15  import org.dom4j.Document;
16  import org.dom4j.DocumentFactory;
17  import org.dom4j.DocumentType;
18  import org.dom4j.Element;
19  import org.dom4j.Entity;
20  import org.dom4j.Namespace;
21  import org.dom4j.ProcessingInstruction;
22  import org.dom4j.QName;
23  import org.dom4j.Text;
24  import org.dom4j.util.SingletonStrategy;
25  import org.w3c.dom.DOMException;
26  
27  /***
28   * <p>
29   * <code>DOMDocumentFactory</code> is a factory of DOM4J objects which
30   * implement the W3C DOM API.
31   * </p>
32   * 
33   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
34   * @version $Revision: 1.21 $
35   */
36  public class DOMDocumentFactory extends DocumentFactory implements
37          org.w3c.dom.DOMImplementation {
38  
39      /*** The Singleton instance */
40      private static SingletonStrategy singleton = null;
41  
42      static {
43          try {
44              String defaultSingletonClass = "org.dom4j.util.SimpleSingleton";
45              Class clazz = null;
46              try {
47                  String singletonClass = defaultSingletonClass;
48                  singletonClass = System.getProperty(
49                          "org.dom4j.dom.DOMDocumentFactory.singleton.strategy",
50                          singletonClass);
51                  clazz = Class.forName(singletonClass);
52              } catch (Exception exc1) {
53                  try {
54                      String singletonClass = defaultSingletonClass;
55                      clazz = Class.forName(singletonClass);
56                  } catch (Exception exc2) {
57                  }
58              }
59              singleton = (SingletonStrategy) clazz.newInstance();
60              singleton.setSingletonClassName(DOMDocumentFactory.class.getName());
61          } catch (Exception exc3) {
62          }
63      }
64  
65      /***
66       * <p>
67       * Access to the singleton instance of this factory.
68       * </p>
69       * 
70       * @return the default singleon instance
71       */
72      public static DocumentFactory getInstance() {
73          DOMDocumentFactory fact = (DOMDocumentFactory) singleton.instance();
74          return fact;
75      }
76  
77      // Factory methods
78      public Document createDocument() {
79          DOMDocument answer = new DOMDocument();
80          answer.setDocumentFactory(this);
81  
82          return answer;
83      }
84  
85      public DocumentType createDocType(String name, String publicId,
86              String systemId) {
87          return new DOMDocumentType(name, publicId, systemId);
88      }
89  
90      public Element createElement(QName qname) {
91          return new DOMElement(qname);
92      }
93  
94      public Element createElement(QName qname, int attributeCount) {
95          return new DOMElement(qname, attributeCount);
96      }
97  
98      public Attribute createAttribute(Element owner, QName qname, String value) {
99          return new DOMAttribute(qname, value);
100     }
101 
102     public CDATA createCDATA(String text) {
103         return new DOMCDATA(text);
104     }
105 
106     public Comment createComment(String text) {
107         return new DOMComment(text);
108     }
109 
110     public Text createText(String text) {
111         return new DOMText(text);
112     }
113 
114     public Entity createEntity(String name) {
115         return new DOMEntityReference(name);
116     }
117 
118     public Entity createEntity(String name, String text) {
119         return new DOMEntityReference(name, text);
120     }
121 
122     public Namespace createNamespace(String prefix, String uri) {
123         return new DOMNamespace(prefix, uri);
124     }
125 
126     public ProcessingInstruction createProcessingInstruction(String target,
127             String data) {
128         return new DOMProcessingInstruction(target, data);
129     }
130 
131     public ProcessingInstruction createProcessingInstruction(String target,
132             Map data) {
133         return new DOMProcessingInstruction(target, data);
134     }
135 
136     // org.w3c.dom.DOMImplementation interface
137     public boolean hasFeature(String feat, String version) {
138         if ("XML".equalsIgnoreCase(feat) || "Core".equalsIgnoreCase(feat)) {
139             return ((version == null) || (version.length() == 0)
140                     || "1.0".equals(version) || "2.0".equals(version));
141         }
142 
143         return false;
144     }
145 
146     public org.w3c.dom.DocumentType createDocumentType(String qualifiedName,
147             String publicId, String systemId) throws DOMException {
148         return new DOMDocumentType(qualifiedName, publicId, systemId);
149     }
150 
151     public org.w3c.dom.Document createDocument(String namespaceURI,
152             String qualifiedName, org.w3c.dom.DocumentType docType)
153             throws org.w3c.dom.DOMException {
154         DOMDocument document;
155 
156         if (docType != null) {
157             DOMDocumentType documentType = asDocumentType(docType);
158             document = new DOMDocument(documentType);
159         } else {
160             document = new DOMDocument();
161         }
162 
163         document.addElement(createQName(qualifiedName, namespaceURI));
164 
165         return document;
166     }
167 
168     // Implementation methods
169     protected DOMDocumentType asDocumentType(org.w3c.dom.DocumentType docType) {
170         if (docType instanceof DOMDocumentType) {
171             return (DOMDocumentType) docType;
172         } else {
173             return new DOMDocumentType(docType.getName(),
174                     docType.getPublicId(), docType.getSystemId());
175         }
176     }
177 }
178 
179 
180 
181 /*
182  * Redistribution and use of this software and associated documentation
183  * ("Software"), with or without modification, are permitted provided that the
184  * following conditions are met:
185  * 
186  * 1. Redistributions of source code must retain copyright statements and
187  * notices. Redistributions must also contain a copy of this document.
188  * 
189  * 2. Redistributions in binary form must reproduce the above copyright notice,
190  * this list of conditions and the following disclaimer in the documentation
191  * and/or other materials provided with the distribution.
192  * 
193  * 3. The name "DOM4J" must not be used to endorse or promote products derived
194  * from this Software without prior written permission of MetaStuff, Ltd. For
195  * written permission, please contact dom4j-info@metastuff.com.
196  * 
197  * 4. Products derived from this Software may not be called "DOM4J" nor may
198  * "DOM4J" appear in their names without prior written permission of MetaStuff,
199  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
200  * 
201  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
202  * 
203  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
204  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
205  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
206  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
207  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
208  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
209  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
210  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
211  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
212  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
213  * POSSIBILITY OF SUCH DAMAGE.
214  * 
215  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
216  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dom/DOMAttributeNodeMap.html0000644000175000017500000002735010242117554023010 0ustar ebourgebourg DOMAttributeNodeMap xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dom;
9   
10  import org.w3c.dom.Attr;
11  import org.w3c.dom.DOMException;
12  import org.w3c.dom.Node;
13  
14  /***
15   * <p>
16   * <code>DOMAttributeNodeMap</code> implements a W3C NameNodeMap for the
17   * attributes of an element.
18   * </p>
19   * 
20   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
21   * @version $Revision: 1.8 $
22   */
23  public class DOMAttributeNodeMap implements org.w3c.dom.NamedNodeMap {
24      private DOMElement element;
25  
26      public DOMAttributeNodeMap(DOMElement element) {
27          this.element = element;
28      }
29  
30      // org.w3c.dom.NamedNodeMap interface
31      // -------------------------------------------------------------------------
32      public void foo() throws DOMException {
33          DOMNodeHelper.notSupported();
34      }
35  
36      public Node getNamedItem(String name) {
37          return element.getAttributeNode(name);
38      }
39  
40      public Node setNamedItem(Node arg) throws DOMException {
41          if (arg instanceof Attr) {
42              return element.setAttributeNode((org.w3c.dom.Attr) arg);
43          } else {
44              throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
45                      "Node is not an Attr: " + arg);
46          }
47      }
48  
49      public Node removeNamedItem(String name) throws DOMException {
50          org.w3c.dom.Attr attr = element.getAttributeNode(name);
51  
52          if (attr == null) {
53              throw new DOMException(DOMException.NOT_FOUND_ERR,
54                      "No attribute named " + name);
55          }
56  
57          return element.removeAttributeNode(attr);
58      }
59  
60      public Node item(int index) {
61          return DOMNodeHelper.asDOMAttr(element.attribute(index));
62      }
63  
64      public int getLength() {
65          return element.attributeCount();
66      }
67  
68      public Node getNamedItemNS(String namespaceURI, String localName) {
69          return element.getAttributeNodeNS(namespaceURI, localName);
70      }
71  
72      public Node setNamedItemNS(Node arg) throws DOMException {
73          if (arg instanceof Attr) {
74              return element.setAttributeNodeNS((org.w3c.dom.Attr) arg);
75          } else {
76              throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
77                      "Node is not an Attr: " + arg);
78          }
79      }
80  
81      public Node removeNamedItemNS(String namespaceURI, String localName)
82              throws DOMException {
83          org.w3c.dom.Attr attr = element.getAttributeNodeNS(namespaceURI,
84                  localName);
85  
86          if (attr != null) {
87              return element.removeAttributeNode(attr);
88          }
89  
90          return attr;
91      }
92  }
93  
94  /*
95   * Redistribution and use of this software and associated documentation
96   * ("Software"), with or without modification, are permitted provided that the
97   * following conditions are met:
98   * 
99   * 1. Redistributions of source code must retain copyright statements and
100  * notices. Redistributions must also contain a copy of this document.
101  * 
102  * 2. Redistributions in binary form must reproduce the above copyright notice,
103  * this list of conditions and the following disclaimer in the documentation
104  * and/or other materials provided with the distribution.
105  * 
106  * 3. The name "DOM4J" must not be used to endorse or promote products derived
107  * from this Software without prior written permission of MetaStuff, Ltd. For
108  * written permission, please contact dom4j-info@metastuff.com.
109  * 
110  * 4. Products derived from this Software may not be called "DOM4J" nor may
111  * "DOM4J" appear in their names without prior written permission of MetaStuff,
112  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
113  * 
114  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
115  * 
116  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
117  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
118  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
119  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
120  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
121  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
122  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
123  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
124  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
125  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
126  * POSSIBILITY OF SUCH DAMAGE.
127  * 
128  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
129  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dom/DOMComment.html0000644000175000017500000004636110242117677021214 0ustar ebourgebourg DOMComment xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dom;
9   
10  import org.dom4j.Element;
11  import org.dom4j.tree.DefaultComment;
12  
13  import org.w3c.dom.DOMException;
14  import org.w3c.dom.Document;
15  import org.w3c.dom.NamedNodeMap;
16  import org.w3c.dom.NodeList;
17  
18  /***
19   * <p>
20   * <code>DOMText</code> implements a Text node which supports the W3C DOM API.
21   * </p>
22   * 
23   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
24   * @version $Revision: 1.12 $
25   */
26  public class DOMComment extends DefaultComment implements org.w3c.dom.Comment {
27      public DOMComment(String text) {
28          super(text);
29      }
30  
31      public DOMComment(Element parent, String text) {
32          super(parent, text);
33      }
34  
35      // org.w3c.dom.Node interface
36      // -------------------------------------------------------------------------
37      public boolean supports(String feature, String version) {
38          return DOMNodeHelper.supports(this, feature, version);
39      }
40  
41      public String getNamespaceURI() {
42          return DOMNodeHelper.getNamespaceURI(this);
43      }
44  
45      public String getPrefix() {
46          return DOMNodeHelper.getPrefix(this);
47      }
48  
49      public void setPrefix(String prefix) throws DOMException {
50          DOMNodeHelper.setPrefix(this, prefix);
51      }
52  
53      public String getLocalName() {
54          return DOMNodeHelper.getLocalName(this);
55      }
56  
57      public String getNodeName() {
58          return "#comment";
59      }
60  
61      // already part of API
62      //
63      // public short getNodeType();
64      public String getNodeValue() throws DOMException {
65          return DOMNodeHelper.getNodeValue(this);
66      }
67  
68      public void setNodeValue(String nodeValue) throws DOMException {
69          DOMNodeHelper.setNodeValue(this, nodeValue);
70      }
71  
72      public org.w3c.dom.Node getParentNode() {
73          return DOMNodeHelper.getParentNode(this);
74      }
75  
76      public NodeList getChildNodes() {
77          return DOMNodeHelper.getChildNodes(this);
78      }
79  
80      public org.w3c.dom.Node getFirstChild() {
81          return DOMNodeHelper.getFirstChild(this);
82      }
83  
84      public org.w3c.dom.Node getLastChild() {
85          return DOMNodeHelper.getLastChild(this);
86      }
87  
88      public org.w3c.dom.Node getPreviousSibling() {
89          return DOMNodeHelper.getPreviousSibling(this);
90      }
91  
92      public org.w3c.dom.Node getNextSibling() {
93          return DOMNodeHelper.getNextSibling(this);
94      }
95  
96      public NamedNodeMap getAttributes() {
97          return null;
98      }
99  
100     public Document getOwnerDocument() {
101         return DOMNodeHelper.getOwnerDocument(this);
102     }
103 
104     public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
105             org.w3c.dom.Node refChild) throws DOMException {
106         checkNewChildNode(newChild);
107 
108         return DOMNodeHelper.insertBefore(this, newChild, refChild);
109     }
110 
111     public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
112             org.w3c.dom.Node oldChild) throws DOMException {
113         checkNewChildNode(newChild);
114 
115         return DOMNodeHelper.replaceChild(this, newChild, oldChild);
116     }
117 
118     public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
119             throws DOMException {
120         return DOMNodeHelper.removeChild(this, oldChild);
121     }
122 
123     public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
124             throws DOMException {
125         checkNewChildNode(newChild);
126 
127         return DOMNodeHelper.appendChild(this, newChild);
128     }
129 
130     private void checkNewChildNode(org.w3c.dom.Node newChild)
131             throws DOMException {
132         throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
133                 "Comment nodes cannot have children");
134     }
135 
136     public boolean hasChildNodes() {
137         return DOMNodeHelper.hasChildNodes(this);
138     }
139 
140     public org.w3c.dom.Node cloneNode(boolean deep) {
141         return DOMNodeHelper.cloneNode(this, deep);
142     }
143 
144     public void normalize() {
145         DOMNodeHelper.normalize(this);
146     }
147 
148     public boolean isSupported(String feature, String version) {
149         return DOMNodeHelper.isSupported(this, feature, version);
150     }
151 
152     public boolean hasAttributes() {
153         return DOMNodeHelper.hasAttributes(this);
154     }
155 
156     // org.w3c.dom.CharacterData interface
157     // -------------------------------------------------------------------------
158     public String getData() throws DOMException {
159         return DOMNodeHelper.getData(this);
160     }
161 
162     public void setData(String data) throws DOMException {
163         DOMNodeHelper.setData(this, data);
164     }
165 
166     public int getLength() {
167         return DOMNodeHelper.getLength(this);
168     }
169 
170     public String substringData(int offset, int count) throws DOMException {
171         return DOMNodeHelper.substringData(this, offset, count);
172     }
173 
174     public void appendData(String arg) throws DOMException {
175         DOMNodeHelper.appendData(this, arg);
176     }
177 
178     public void insertData(int offset, String arg) throws DOMException {
179         DOMNodeHelper.insertData(this, offset, arg);
180     }
181 
182     public void deleteData(int offset, int count) throws DOMException {
183         DOMNodeHelper.deleteData(this, offset, count);
184     }
185 
186     public void replaceData(int offset, int count, String arg)
187             throws DOMException {
188         DOMNodeHelper.replaceData(this, offset, count, arg);
189     }
190 }
191 
192 /*
193  * Redistribution and use of this software and associated documentation
194  * ("Software"), with or without modification, are permitted provided that the
195  * following conditions are met:
196  * 
197  * 1. Redistributions of source code must retain copyright statements and
198  * notices. Redistributions must also contain a copy of this document.
199  * 
200  * 2. Redistributions in binary form must reproduce the above copyright notice,
201  * this list of conditions and the following disclaimer in the documentation
202  * and/or other materials provided with the distribution.
203  * 
204  * 3. The name "DOM4J" must not be used to endorse or promote products derived
205  * from this Software without prior written permission of MetaStuff, Ltd. For
206  * written permission, please contact dom4j-info@metastuff.com.
207  * 
208  * 4. Products derived from this Software may not be called "DOM4J" nor may
209  * "DOM4J" appear in their names without prior written permission of MetaStuff,
210  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
211  * 
212  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
213  * 
214  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
215  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
216  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
217  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
218  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
219  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
220  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
221  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
222  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
223  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
224  * POSSIBILITY OF SUCH DAMAGE.
225  * 
226  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
227  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dom/DOMNodeHelper.html0000644000175000017500000014175510242117677021642 0ustar ebourgebourg DOMNodeHelper xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dom;
9   
10  import java.util.List;
11  
12  import org.dom4j.Branch;
13  import org.dom4j.CharacterData;
14  import org.dom4j.Document;
15  import org.dom4j.DocumentType;
16  import org.dom4j.Element;
17  import org.dom4j.Node;
18  
19  import org.w3c.dom.DOMException;
20  import org.w3c.dom.NamedNodeMap;
21  import org.w3c.dom.NodeList;
22  
23  /***
24   * <p>
25   * <code>DOMNodeHelper</code> contains a collection of utility methods for use
26   * across Node implementations.
27   * </p>
28   * 
29   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
30   * @version $Revision: 1.20 $
31   */
32  public class DOMNodeHelper {
33      public static final NodeList EMPTY_NODE_LIST = new EmptyNodeList();
34  
35      protected DOMNodeHelper() {
36      }
37  
38      // Node API
39      // -------------------------------------------------------------------------
40      public static boolean supports(Node node, String feature, String version) {
41          return false;
42      }
43  
44      public static String getNamespaceURI(Node node) {
45          return null;
46      }
47  
48      public static String getPrefix(Node node) {
49          return null;
50      }
51  
52      public static String getLocalName(Node node) {
53          return null;
54      }
55  
56      public static void setPrefix(Node node, String prefix) throws DOMException {
57          notSupported();
58      }
59  
60      public static String getNodeValue(Node node) throws DOMException {
61          return node.getText();
62      }
63  
64      public static void setNodeValue(Node node, String nodeValue)
65              throws DOMException {
66          node.setText(nodeValue);
67      }
68  
69      public static org.w3c.dom.Node getParentNode(Node node) {
70          return asDOMNode(node.getParent());
71      }
72  
73      public static NodeList getChildNodes(Node node) {
74          return EMPTY_NODE_LIST;
75      }
76  
77      public static org.w3c.dom.Node getFirstChild(Node node) {
78          return null;
79      }
80  
81      public static org.w3c.dom.Node getLastChild(Node node) {
82          return null;
83      }
84  
85      public static org.w3c.dom.Node getPreviousSibling(Node node) {
86          Element parent = node.getParent();
87  
88          if (parent != null) {
89              int index = parent.indexOf(node);
90  
91              if (index > 0) {
92                  Node previous = parent.node(index - 1);
93  
94                  return asDOMNode(previous);
95              }
96          }
97  
98          return null;
99      }
100 
101     public static org.w3c.dom.Node getNextSibling(Node node) {
102         Element parent = node.getParent();
103 
104         if (parent != null) {
105             int index = parent.indexOf(node);
106 
107             if (index >= 0) {
108                 if (++index < parent.nodeCount()) {
109                     Node next = parent.node(index);
110 
111                     return asDOMNode(next);
112                 }
113             }
114         }
115 
116         return null;
117     }
118 
119     public static NamedNodeMap getAttributes(Node node) {
120         return null;
121     }
122 
123     public static org.w3c.dom.Document getOwnerDocument(Node node) {
124         return asDOMDocument(node.getDocument());
125     }
126 
127     public static org.w3c.dom.Node insertBefore(Node node,
128             org.w3c.dom.Node newChild, org.w3c.dom.Node refChild)
129             throws DOMException {
130         if (node instanceof Branch) {
131             Branch branch = (Branch) node;
132             List list = branch.content();
133             int index = list.indexOf(refChild);
134 
135             if (index < 0) {
136                 branch.add((Node) newChild);
137             } else {
138                 list.add(index, newChild);
139             }
140 
141             return newChild;
142         } else {
143             throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
144                     "Children not allowed for this node: " + node);
145         }
146     }
147 
148     public static org.w3c.dom.Node replaceChild(Node node,
149             org.w3c.dom.Node newChild, org.w3c.dom.Node oldChild)
150             throws DOMException {
151         if (node instanceof Branch) {
152             Branch branch = (Branch) node;
153             List list = branch.content();
154             int index = list.indexOf(oldChild);
155 
156             if (index < 0) {
157                 throw new DOMException(DOMException.NOT_FOUND_ERR,
158                         "Tried to replace a non existing child " + "for node: "
159                                 + node);
160             }
161 
162             list.set(index, newChild);
163 
164             return oldChild;
165         } else {
166             throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
167                     "Children not allowed for this node: " + node);
168         }
169     }
170 
171     public static org.w3c.dom.Node removeChild(Node node,
172             org.w3c.dom.Node oldChild) throws DOMException {
173         if (node instanceof Branch) {
174             Branch branch = (Branch) node;
175             branch.remove((Node) oldChild);
176 
177             return oldChild;
178         }
179 
180         throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
181                 "Children not allowed for this node: " + node);
182     }
183 
184     public static org.w3c.dom.Node appendChild(Node node,
185             org.w3c.dom.Node newChild) throws DOMException {
186         if (node instanceof Branch) {
187             Branch branch = (Branch) node;
188             org.w3c.dom.Node previousParent = newChild.getParentNode();
189 
190             if (previousParent != null) {
191                 previousParent.removeChild(newChild);
192             }
193 
194             branch.add((Node) newChild);
195 
196             return newChild;
197         }
198 
199         throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
200                 "Children not allowed for this node: " + node);
201     }
202 
203     public static boolean hasChildNodes(Node node) {
204         return false;
205     }
206 
207     public static org.w3c.dom.Node cloneNode(Node node, boolean deep) {
208         return asDOMNode((Node) node.clone());
209     }
210 
211     public static void normalize(Node node) {
212         notSupported();
213     }
214 
215     public static boolean isSupported(Node n, String feature, String version) {
216         return false;
217     }
218 
219     public static boolean hasAttributes(Node node) {
220         if ((node != null) && node instanceof Element) {
221             return ((Element) node).attributeCount() > 0;
222         } else {
223             return false;
224         }
225     }
226 
227     // CharacterData API
228     // -------------------------------------------------------------------------
229     public static String getData(CharacterData charData) throws DOMException {
230         return charData.getText();
231     }
232 
233     public static void setData(CharacterData charData, String data)
234             throws DOMException {
235         charData.setText(data);
236     }
237 
238     public static int getLength(CharacterData charData) {
239         String text = charData.getText();
240 
241         return (text != null) ? text.length() : 0;
242     }
243 
244     public static String substringData(CharacterData charData, int offset,
245             int count) throws DOMException {
246         if (count < 0) {
247             throw new DOMException(DOMException.INDEX_SIZE_ERR,
248                     "Illegal value for count: " + count);
249         }
250 
251         String text = charData.getText();
252         int length = (text != null) ? text.length() : 0;
253 
254         if ((offset < 0) || (offset >= length)) {
255             throw new DOMException(DOMException.INDEX_SIZE_ERR,
256                     "No text at offset: " + offset);
257         }
258 
259         if ((offset + count) > length) {
260             return text.substring(offset);
261         }
262 
263         return text.substring(offset, offset + count);
264     }
265 
266     public static void appendData(CharacterData charData, String arg)
267             throws DOMException {
268         if (charData.isReadOnly()) {
269             throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
270                     "CharacterData node is read only: " + charData);
271         } else {
272             String text = charData.getText();
273 
274             if (text == null) {
275                 charData.setText(text);
276             } else {
277                 charData.setText(text + arg);
278             }
279         }
280     }
281 
282     public static void insertData(CharacterData data, int offset, String arg)
283             throws DOMException {
284         if (data.isReadOnly()) {
285             throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
286                     "CharacterData node is read only: " + data);
287         } else {
288             String text = data.getText();
289 
290             if (text == null) {
291                 data.setText(arg);
292             } else {
293                 int length = text.length();
294 
295                 if ((offset < 0) || (offset > length)) {
296                     throw new DOMException(DOMException.INDEX_SIZE_ERR,
297                             "No text at offset: " + offset);
298                 } else {
299                     StringBuffer buffer = new StringBuffer(text);
300                     buffer.insert(offset, arg);
301                     data.setText(buffer.toString());
302                 }
303             }
304         }
305     }
306 
307     public static void deleteData(CharacterData charData, int offset, int count)
308             throws DOMException {
309         if (charData.isReadOnly()) {
310             throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
311                     "CharacterData node is read only: " + charData);
312         } else {
313             if (count < 0) {
314                 throw new DOMException(DOMException.INDEX_SIZE_ERR,
315                         "Illegal value for count: " + count);
316             }
317 
318             String text = charData.getText();
319 
320             if (text != null) {
321                 int length = text.length();
322 
323                 if ((offset < 0) || (offset >= length)) {
324                     throw new DOMException(DOMException.INDEX_SIZE_ERR,
325                             "No text at offset: " + offset);
326                 } else {
327                     StringBuffer buffer = new StringBuffer(text);
328                     buffer.delete(offset, offset + count);
329                     charData.setText(buffer.toString());
330                 }
331             }
332         }
333     }
334 
335     public static void replaceData(CharacterData charData, int offset,
336             int count, String arg) throws DOMException {
337         if (charData.isReadOnly()) {
338             throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
339                     "CharacterData node is read only: " + charData);
340         } else {
341             if (count < 0) {
342                 throw new DOMException(DOMException.INDEX_SIZE_ERR,
343                         "Illegal value for count: " + count);
344             }
345 
346             String text = charData.getText();
347 
348             if (text != null) {
349                 int length = text.length();
350 
351                 if ((offset < 0) || (offset >= length)) {
352                     throw new DOMException(DOMException.INDEX_SIZE_ERR,
353                             "No text at offset: " + offset);
354                 } else {
355                     StringBuffer buffer = new StringBuffer(text);
356                     buffer.replace(offset, offset + count, arg);
357                     charData.setText(buffer.toString());
358                 }
359             }
360         }
361     }
362 
363     // Branch API
364     // -------------------------------------------------------------------------
365     public static void appendElementsByTagName(List list, Branch parent,
366             String name) {
367         final boolean isStar = "*".equals(name);
368 
369         for (int i = 0, size = parent.nodeCount(); i < size; i++) {
370             Node node = parent.node(i);
371 
372             if (node instanceof Element) {
373                 Element element = (Element) node;
374 
375                 if (isStar || name.equals(element.getName())) {
376                     list.add(element);
377                 }
378 
379                 appendElementsByTagName(list, element, name);
380             }
381         }
382     }
383 
384     public static void appendElementsByTagNameNS(List list, Branch parent,
385             String namespace, String localName) {
386         final boolean isStarNS = "*".equals(namespace);
387         final boolean isStar = "*".equals(localName);
388 
389         for (int i = 0, size = parent.nodeCount(); i < size; i++) {
390             Node node = parent.node(i);
391 
392             if (node instanceof Element) {
393                 Element element = (Element) node;
394 
395                 if ((isStarNS
396                         || (((namespace == null) 
397                                 || (namespace.length() == 0)) && ((element
398                                 .getNamespaceURI() == null) || (element
399                                 .getNamespaceURI().length() == 0))) 
400                                 || ((namespace != null) && namespace
401                         .equals(element.getNamespaceURI())))
402                         && (isStar || localName.equals(element.getName()))) {
403                     list.add(element);
404                 }
405 
406                 appendElementsByTagNameNS(list, element, namespace, localName);
407             }
408         }
409     }
410 
411     // Helper methods
412     // -------------------------------------------------------------------------
413     public static NodeList createNodeList(final List list) {
414         return new NodeList() {
415             public org.w3c.dom.Node item(int index) {
416                 if (index >= getLength()) {
417                     /*
418                      * From the NodeList specification: If index is greater than
419                      * or equal to the number of nodes in the list, this returns
420                      * null.
421                      */
422                     return null;
423                 } else {
424                     return DOMNodeHelper.asDOMNode((Node) list.get(index));
425                 }
426             }
427 
428             public int getLength() {
429                 return list.size();
430             }
431         };
432     }
433 
434     public static org.w3c.dom.Node asDOMNode(Node node) {
435         if (node == null) {
436             return null;
437         }
438 
439         if (node instanceof org.w3c.dom.Node) {
440             return (org.w3c.dom.Node) node;
441         } else {
442             // Use DOMWriter?
443             System.out.println("Cannot convert: " + node
444                     + " into a W3C DOM Node");
445             notSupported();
446 
447             return null;
448         }
449     }
450 
451     public static org.w3c.dom.Document asDOMDocument(Document document) {
452         if (document == null) {
453             return null;
454         }
455 
456         if (document instanceof org.w3c.dom.Document) {
457             return (org.w3c.dom.Document) document;
458         } else {
459             // Use DOMWriter?
460             notSupported();
461 
462             return null;
463         }
464     }
465 
466     public static org.w3c.dom.DocumentType asDOMDocumentType(DocumentType dt) {
467         if (dt == null) {
468             return null;
469         }
470 
471         if (dt instanceof org.w3c.dom.DocumentType) {
472             return (org.w3c.dom.DocumentType) dt;
473         } else {
474             // Use DOMWriter?
475             notSupported();
476 
477             return null;
478         }
479     }
480 
481     public static org.w3c.dom.Text asDOMText(CharacterData text) {
482         if (text == null) {
483             return null;
484         }
485 
486         if (text instanceof org.w3c.dom.Text) {
487             return (org.w3c.dom.Text) text;
488         } else {
489             // Use DOMWriter?
490             notSupported();
491 
492             return null;
493         }
494     }
495 
496     public static org.w3c.dom.Element asDOMElement(Node element) {
497         if (element == null) {
498             return null;
499         }
500 
501         if (element instanceof org.w3c.dom.Element) {
502             return (org.w3c.dom.Element) element;
503         } else {
504             // Use DOMWriter?
505             notSupported();
506 
507             return null;
508         }
509     }
510 
511     public static org.w3c.dom.Attr asDOMAttr(Node attribute) {
512         if (attribute == null) {
513             return null;
514         }
515 
516         if (attribute instanceof org.w3c.dom.Attr) {
517             return (org.w3c.dom.Attr) attribute;
518         } else {
519             // Use DOMWriter?
520             notSupported();
521 
522             return null;
523         }
524     }
525 
526     /***
527      * Called when a method has not been implemented yet
528      * 
529      * @throws DOMException
530      *             DOCUMENT ME!
531      */
532     public static void notSupported() {
533         throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
534                 "Not supported yet");
535     }
536 
537     public static class EmptyNodeList implements NodeList {
538         public org.w3c.dom.Node item(int index) {
539             return null;
540         }
541 
542         public int getLength() {
543             return 0;
544         }
545     }
546 }
547 
548 /*
549  * Redistribution and use of this software and associated documentation
550  * ("Software"), with or without modification, are permitted provided that the
551  * following conditions are met:
552  * 
553  * 1. Redistributions of source code must retain copyright statements and
554  * notices. Redistributions must also contain a copy of this document.
555  * 
556  * 2. Redistributions in binary form must reproduce the above copyright notice,
557  * this list of conditions and the following disclaimer in the documentation
558  * and/or other materials provided with the distribution.
559  * 
560  * 3. The name "DOM4J" must not be used to endorse or promote products derived
561  * from this Software without prior written permission of MetaStuff, Ltd. For
562  * written permission, please contact dom4j-info@metastuff.com.
563  * 
564  * 4. Products derived from this Software may not be called "DOM4J" nor may
565  * "DOM4J" appear in their names without prior written permission of MetaStuff,
566  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
567  * 
568  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
569  * 
570  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
571  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
572  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
573  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
574  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
575  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
576  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
577  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
578  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
579  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
580  * POSSIBILITY OF SUCH DAMAGE.
581  * 
582  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
583  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dom/DOMDocumentType.html0000644000175000017500000004400210242117714022210 0ustar ebourgebourg DOMDocumentType xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dom;
9   
10  import org.dom4j.tree.DefaultDocumentType;
11  
12  import org.w3c.dom.DOMException;
13  import org.w3c.dom.Document;
14  import org.w3c.dom.NamedNodeMap;
15  import org.w3c.dom.NodeList;
16  
17  /***
18   * <p>
19   * <code>DOMDocumentType</code> implements a DocumentType node which supports
20   * the W3C DOM API.
21   * </p>
22   * 
23   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
24   * @version $Revision: 1.11 $
25   */
26  public class DOMDocumentType extends DefaultDocumentType implements
27          org.w3c.dom.DocumentType {
28      public DOMDocumentType() {
29      }
30  
31      public DOMDocumentType(String elementName, String systemID) {
32          super(elementName, systemID);
33      }
34  
35      public DOMDocumentType(String name, String publicID, String systemID) {
36          super(name, publicID, systemID);
37      }
38  
39      // org.w3c.dom.Node interface
40      // -------------------------------------------------------------------------
41      public boolean supports(String feature, String version) {
42          return DOMNodeHelper.supports(this, feature, version);
43      }
44  
45      public String getNamespaceURI() {
46          return DOMNodeHelper.getNamespaceURI(this);
47      }
48  
49      public String getPrefix() {
50          return DOMNodeHelper.getPrefix(this);
51      }
52  
53      public void setPrefix(String prefix) throws DOMException {
54          DOMNodeHelper.setPrefix(this, prefix);
55      }
56  
57      public String getLocalName() {
58          return DOMNodeHelper.getLocalName(this);
59      }
60  
61      public String getNodeName() {
62          return getName();
63      }
64  
65      // already part of API
66      //
67      // public short getNodeType();
68      public String getNodeValue() throws DOMException {
69          return null;
70      }
71  
72      public void setNodeValue(String nodeValue) throws DOMException {
73      }
74  
75      public org.w3c.dom.Node getParentNode() {
76          return DOMNodeHelper.getParentNode(this);
77      }
78  
79      public NodeList getChildNodes() {
80          return DOMNodeHelper.getChildNodes(this);
81      }
82  
83      public org.w3c.dom.Node getFirstChild() {
84          return DOMNodeHelper.getFirstChild(this);
85      }
86  
87      public org.w3c.dom.Node getLastChild() {
88          return DOMNodeHelper.getLastChild(this);
89      }
90  
91      public org.w3c.dom.Node getPreviousSibling() {
92          return DOMNodeHelper.getPreviousSibling(this);
93      }
94  
95      public org.w3c.dom.Node getNextSibling() {
96          return DOMNodeHelper.getNextSibling(this);
97      }
98  
99      public NamedNodeMap getAttributes() {
100         return null;
101     }
102 
103     public Document getOwnerDocument() {
104         return DOMNodeHelper.getOwnerDocument(this);
105     }
106 
107     public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
108             org.w3c.dom.Node refChild) throws DOMException {
109         checkNewChildNode(newChild);
110 
111         return DOMNodeHelper.insertBefore(this, newChild, refChild);
112     }
113 
114     public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
115             org.w3c.dom.Node oldChild) throws DOMException {
116         checkNewChildNode(newChild);
117 
118         return DOMNodeHelper.replaceChild(this, newChild, oldChild);
119     }
120 
121     public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
122             throws DOMException {
123         return DOMNodeHelper.removeChild(this, oldChild);
124     }
125 
126     public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
127             throws DOMException {
128         checkNewChildNode(newChild);
129 
130         return DOMNodeHelper.appendChild(this, newChild);
131     }
132 
133     private void checkNewChildNode(org.w3c.dom.Node newChild)
134             throws DOMException {
135         throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
136                 "DocumentType nodes cannot have children");
137     }
138 
139     public boolean hasChildNodes() {
140         return DOMNodeHelper.hasChildNodes(this);
141     }
142 
143     public org.w3c.dom.Node cloneNode(boolean deep) {
144         return DOMNodeHelper.cloneNode(this, deep);
145     }
146 
147     public void normalize() {
148         DOMNodeHelper.normalize(this);
149     }
150 
151     public boolean isSupported(String feature, String version) {
152         return DOMNodeHelper.isSupported(this, feature, version);
153     }
154 
155     public boolean hasAttributes() {
156         return DOMNodeHelper.hasAttributes(this);
157     }
158 
159     // org.w3c.dom.DocumentType interface
160     // -------------------------------------------------------------------------
161     public NamedNodeMap getEntities() {
162         return null;
163     }
164 
165     public NamedNodeMap getNotations() {
166         return null;
167     }
168 
169     public String getPublicId() {
170         return getPublicID();
171     }
172 
173     public String getSystemId() {
174         return getSystemID();
175     }
176 
177     public String getInternalSubset() {
178         return getElementName();
179     }
180 }
181 
182 /*
183  * Redistribution and use of this software and associated documentation
184  * ("Software"), with or without modification, are permitted provided that the
185  * following conditions are met:
186  * 
187  * 1. Redistributions of source code must retain copyright statements and
188  * notices. Redistributions must also contain a copy of this document.
189  * 
190  * 2. Redistributions in binary form must reproduce the above copyright notice,
191  * this list of conditions and the following disclaimer in the documentation
192  * and/or other materials provided with the distribution.
193  * 
194  * 3. The name "DOM4J" must not be used to endorse or promote products derived
195  * from this Software without prior written permission of MetaStuff, Ltd. For
196  * written permission, please contact dom4j-info@metastuff.com.
197  * 
198  * 4. Products derived from this Software may not be called "DOM4J" nor may
199  * "DOM4J" appear in their names without prior written permission of MetaStuff,
200  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
201  * 
202  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
203  * 
204  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
205  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
206  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
207  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
208  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
209  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
210  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
211  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
212  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
213  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
214  * POSSIBILITY OF SUCH DAMAGE.
215  * 
216  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
217  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dom/DOMDocument.html0000644000175000017500000007063010242117727021360 0ustar ebourgebourg DOMDocument xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dom;
9   
10  import java.util.ArrayList;
11  
12  import org.dom4j.DocumentFactory;
13  import org.dom4j.QName;
14  import org.dom4j.tree.DefaultDocument;
15  
16  import org.w3c.dom.Attr;
17  import org.w3c.dom.CDATASection;
18  import org.w3c.dom.DOMException;
19  import org.w3c.dom.Document;
20  import org.w3c.dom.EntityReference;
21  import org.w3c.dom.NamedNodeMap;
22  import org.w3c.dom.NodeList;
23  import org.w3c.dom.ProcessingInstruction;
24  
25  /***
26   * <p>
27   * <code>DOMDocument</code> implements an XML document which supports the W3C
28   * DOM API.
29   * </p>
30   * 
31   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
32   * @version $Revision: 1.17 $
33   */
34  public class DOMDocument extends DefaultDocument implements Document {
35      /*** The <code>DocumentFactory</code> instance used by default */
36      private static final DOMDocumentFactory DOCUMENT_FACTORY
37              = (DOMDocumentFactory) DOMDocumentFactory.getInstance();
38  
39      public DOMDocument() {
40          init();
41      }
42  
43      public DOMDocument(String name) {
44          super(name);
45          init();
46      }
47  
48      public DOMDocument(DOMElement rootElement) {
49          super(rootElement);
50          init();
51      }
52  
53      public DOMDocument(DOMDocumentType docType) {
54          super(docType);
55          init();
56      }
57  
58      public DOMDocument(DOMElement rootElement, DOMDocumentType docType) {
59          super(rootElement, docType);
60          init();
61      }
62  
63      public DOMDocument(String name, DOMElement rootElement,
64              DOMDocumentType docType) {
65          super(name, rootElement, docType);
66          init();
67      }
68  
69      private void init() {
70          setDocumentFactory(DOCUMENT_FACTORY);
71      }
72  
73      // org.w3c.dom.Node interface
74      // -------------------------------------------------------------------------
75      public boolean supports(String feature, String version) {
76          return DOMNodeHelper.supports(this, feature, version);
77      }
78  
79      public String getNamespaceURI() {
80          return DOMNodeHelper.getNamespaceURI(this);
81      }
82  
83      public String getPrefix() {
84          return DOMNodeHelper.getPrefix(this);
85      }
86  
87      public void setPrefix(String prefix) throws DOMException {
88          DOMNodeHelper.setPrefix(this, prefix);
89      }
90  
91      public String getLocalName() {
92          return DOMNodeHelper.getLocalName(this);
93      }
94  
95      public String getNodeName() {
96          return "#document";
97      }
98  
99      // already part of API
100     //
101     // public short getNodeType();
102     public String getNodeValue() throws DOMException {
103         return null;
104     }
105 
106     public void setNodeValue(String nodeValue) throws DOMException {
107     }
108 
109     public org.w3c.dom.Node getParentNode() {
110         return DOMNodeHelper.getParentNode(this);
111     }
112 
113     public NodeList getChildNodes() {
114         return DOMNodeHelper.createNodeList(content());
115     }
116 
117     public org.w3c.dom.Node getFirstChild() {
118         return DOMNodeHelper.asDOMNode(node(0));
119     }
120 
121     public org.w3c.dom.Node getLastChild() {
122         return DOMNodeHelper.asDOMNode(node(nodeCount() - 1));
123     }
124 
125     public org.w3c.dom.Node getPreviousSibling() {
126         return DOMNodeHelper.getPreviousSibling(this);
127     }
128 
129     public org.w3c.dom.Node getNextSibling() {
130         return DOMNodeHelper.getNextSibling(this);
131     }
132 
133     public NamedNodeMap getAttributes() {
134         return null;
135     }
136 
137     public org.w3c.dom.Document getOwnerDocument() {
138         return null;
139     }
140 
141     public org.w3c.dom.Node insertBefore(org.w3c.dom.Node newChild,
142             org.w3c.dom.Node refChild) throws DOMException {
143         checkNewChildNode(newChild);
144 
145         return DOMNodeHelper.insertBefore(this, newChild, refChild);
146     }
147 
148     public org.w3c.dom.Node replaceChild(org.w3c.dom.Node newChild,
149             org.w3c.dom.Node oldChild) throws DOMException {
150         checkNewChildNode(newChild);
151 
152         return DOMNodeHelper.replaceChild(this, newChild, oldChild);
153     }
154 
155     public org.w3c.dom.Node removeChild(org.w3c.dom.Node oldChild)
156             throws DOMException {
157         return DOMNodeHelper.removeChild(this, oldChild);
158     }
159 
160     public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild)
161             throws DOMException {
162         checkNewChildNode(newChild);
163 
164         return DOMNodeHelper.appendChild(this, newChild);
165     }
166 
167     private void checkNewChildNode(org.w3c.dom.Node newChild)
168             throws DOMException {
169         final int nodeType = newChild.getNodeType();
170 
171         if (!((nodeType == org.w3c.dom.Node.ELEMENT_NODE)
172                 || (nodeType == org.w3c.dom.Node.COMMENT_NODE)
173                 || (nodeType == org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE) 
174                 || (nodeType == org.w3c.dom.Node.DOCUMENT_TYPE_NODE))) {
175             throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
176                     "Given node cannot be a child of document");
177         }
178     }
179 
180     public boolean hasChildNodes() {
181         return nodeCount() > 0;
182     }
183 
184     public org.w3c.dom.Node cloneNode(boolean deep) {
185         return DOMNodeHelper.cloneNode(this, deep);
186     }
187 
188     public boolean isSupported(String feature, String version) {
189         return DOMNodeHelper.isSupported(this, feature, version);
190     }
191 
192     public boolean hasAttributes() {
193         return DOMNodeHelper.hasAttributes(this);
194     }
195 
196     // org.w3c.dom.Document interface
197     // -------------------------------------------------------------------------
198     public NodeList getElementsByTagName(String name) {
199         ArrayList list = new ArrayList();
200         DOMNodeHelper.appendElementsByTagName(list, this, name);
201 
202         return DOMNodeHelper.createNodeList(list);
203     }
204 
205     public NodeList getElementsByTagNameNS(String namespace, String name) {
206         ArrayList list = new ArrayList();
207         DOMNodeHelper.appendElementsByTagNameNS(list, this, namespace, name);
208 
209         return DOMNodeHelper.createNodeList(list);
210     }
211 
212     public org.w3c.dom.DocumentType getDoctype() {
213         return DOMNodeHelper.asDOMDocumentType(getDocType());
214     }
215 
216     public org.w3c.dom.DOMImplementation getImplementation() {
217         if (getDocumentFactory() instanceof org.w3c.dom.DOMImplementation) {
218             return (org.w3c.dom.DOMImplementation) getDocumentFactory();
219         } else {
220             return DOCUMENT_FACTORY;
221         }
222     }
223 
224     public org.w3c.dom.Element getDocumentElement() {
225         return DOMNodeHelper.asDOMElement(getRootElement());
226     }
227 
228     public org.w3c.dom.Element createElement(String name) throws DOMException {
229         return (org.w3c.dom.Element) getDocumentFactory().createElement(name);
230     }
231 
232     public org.w3c.dom.DocumentFragment createDocumentFragment() {
233         DOMNodeHelper.notSupported();
234 
235         return null;
236     }
237 
238     public org.w3c.dom.Text createTextNode(String data) {
239         return (org.w3c.dom.Text) getDocumentFactory().createText(data);
240     }
241 
242     public org.w3c.dom.Comment createComment(String data) {
243         return (org.w3c.dom.Comment) getDocumentFactory().createComment(data);
244     }
245 
246     public CDATASection createCDATASection(String data) throws DOMException {
247         return (CDATASection) getDocumentFactory().createCDATA(data);
248     }
249 
250     public ProcessingInstruction createProcessingInstruction(String target,
251             String data) throws DOMException {
252         return (ProcessingInstruction) getDocumentFactory()
253                 .createProcessingInstruction(target, data);
254     }
255 
256     public Attr createAttribute(String name) throws DOMException {
257         QName qname = getDocumentFactory().createQName(name);
258 
259         return (Attr) getDocumentFactory().createAttribute(null, qname, "");
260     }
261 
262     public EntityReference createEntityReference(String name)
263             throws DOMException {
264         return (EntityReference) getDocumentFactory().createEntity(name, null);
265     }
266 
267     public org.w3c.dom.Node importNode(org.w3c.dom.Node importedNode,
268             boolean deep) throws DOMException {
269         DOMNodeHelper.notSupported();
270 
271         return null;
272     }
273 
274     public org.w3c.dom.Element createElementNS(String namespaceURI,
275             String qualifiedName) throws DOMException {
276         QName qname = getDocumentFactory().createQName(qualifiedName,
277                 namespaceURI);
278 
279         return (org.w3c.dom.Element) getDocumentFactory().createElement(qname);
280     }
281 
282     public org.w3c.dom.Attr createAttributeNS(String namespaceURI,
283             String qualifiedName) throws DOMException {
284         QName qname = getDocumentFactory().createQName(qualifiedName,
285                 namespaceURI);
286 
287         return (org.w3c.dom.Attr) getDocumentFactory().createAttribute(null,
288                 qname, null);
289     }
290 
291     public org.w3c.dom.Element getElementById(String elementId) {
292         return DOMNodeHelper.asDOMElement(elementByID(elementId));
293     }
294 
295     // Implementation methods
296     // -------------------------------------------------------------------------
297     protected DocumentFactory getDocumentFactory() {
298         if (super.getDocumentFactory() == null) {
299             return DOCUMENT_FACTORY;
300         } else {
301             return super.getDocumentFactory();
302         }
303     }
304 }
305 
306 /*
307  * Redistribution and use of this software and associated documentation
308  * ("Software"), with or without modification, are permitted provided that the
309  * following conditions are met:
310  * 
311  * 1. Redistributions of source code must retain copyright statements and
312  * notices. Redistributions must also contain a copy of this document.
313  * 
314  * 2. Redistributions in binary form must reproduce the above copyright notice,
315  * this list of conditions and the following disclaimer in the documentation
316  * and/or other materials provided with the distribution.
317  * 
318  * 3. The name "DOM4J" must not be used to endorse or promote products derived
319  * from this Software without prior written permission of MetaStuff, Ltd. For
320  * written permission, please contact dom4j-info@metastuff.com.
321  * 
322  * 4. Products derived from this Software may not be called "DOM4J" nor may
323  * "DOM4J" appear in their names without prior written permission of MetaStuff,
324  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
325  * 
326  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
327  * 
328  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
329  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
330  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
331  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
332  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
333  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
334  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
335  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
336  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
337  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
338  * POSSIBILITY OF SUCH DAMAGE.
339  * 
340  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
341  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/Text.html0000644000175000017500000001421310242117710017372 0ustar ebourgebourg Text xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  /***
11   * <p>
12   * <code>Text</code> defines an XML Text node.
13   * </p>
14   * 
15   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
16   * @version $Revision: 1.7 $
17   */
18  public interface Text extends CharacterData {
19  }
20  
21  /*
22   * Redistribution and use of this software and associated documentation
23   * ("Software"), with or without modification, are permitted provided that the
24   * following conditions are met:
25   * 
26   * 1. Redistributions of source code must retain copyright statements and
27   * notices. Redistributions must also contain a copy of this document.
28   * 
29   * 2. Redistributions in binary form must reproduce the above copyright notice,
30   * this list of conditions and the following disclaimer in the documentation
31   * and/or other materials provided with the distribution.
32   * 
33   * 3. The name "DOM4J" must not be used to endorse or promote products derived
34   * from this Software without prior written permission of MetaStuff, Ltd. For
35   * written permission, please contact dom4j-info@metastuff.com.
36   * 
37   * 4. Products derived from this Software may not be called "DOM4J" nor may
38   * "DOM4J" appear in their names without prior written permission of MetaStuff,
39   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
40   * 
41   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
42   * 
43   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
44   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
47   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
48   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
49   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
50   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
51   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
52   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
53   * POSSIBILITY OF SUCH DAMAGE.
54   * 
55   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
56   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/rule/0000755000175000017500000000000012133227266016537 5ustar ebourgebourgdom4j-1.6.1/docs/xref/org/dom4j/rule/Stylesheet.html0000644000175000017500000006656510242117614021572 0ustar ebourgebourg Stylesheet xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.rule;
9   
10  import java.util.Iterator;
11  import java.util.List;
12  
13  import org.dom4j.Document;
14  import org.dom4j.Element;
15  import org.dom4j.Node;
16  import org.dom4j.XPath;
17  
18  /***
19   * <p>
20   * <code>Stylesheet</code> implements an XSLT stylesheet such that rules can
21   * be added to the stylesheet and the stylesheet can be applied to a source
22   * document or node.
23   * </p>
24   * 
25   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
26   * @version $Revision: 1.14 $
27   */
28  public class Stylesheet {
29      private RuleManager ruleManager = new RuleManager();
30  
31      /*** Holds value of property mode. */
32      private String modeName;
33  
34      /***
35       * Creates a new empty stylesheet.
36       */
37      public Stylesheet() {
38      }
39  
40      /***
41       * Add a rule to this stylesheet.
42       * 
43       * @param rule
44       *            the rule to add
45       */
46      public void addRule(Rule rule) {
47          ruleManager.addRule(rule);
48      }
49  
50      /***
51       * Removes the specified rule from this stylesheet.
52       * 
53       * @param rule
54       *            the rule to remove
55       */
56      public void removeRule(Rule rule) {
57          ruleManager.removeRule(rule);
58      }
59  
60      /***
61       * Runs this stylesheet on the given input which should be either a Node or
62       * a List of Node objects.
63       * 
64       * @param input
65       *            the input to run this stylesheet on
66       * 
67       * @throws Exception
68       *             if something goes wrong
69       */
70      public void run(Object input) throws Exception {
71          run(input, this.modeName);
72      }
73  
74      public void run(Object input, String mode) throws Exception {
75          if (input instanceof Node) {
76              run((Node) input, mode);
77          } else if (input instanceof List) {
78              run((List) input, mode);
79          }
80      }
81  
82      public void run(List list) throws Exception {
83          run(list, this.modeName);
84      }
85  
86      public void run(List list, String mode) throws Exception {
87          for (int i = 0, size = list.size(); i < size; i++) {
88              Object object = list.get(i);
89  
90              if (object instanceof Node) {
91                  run((Node) object, mode);
92              }
93          }
94      }
95  
96      public void run(Node node) throws Exception {
97          run(node, this.modeName);
98      }
99  
100     public void run(Node node, String mode) throws Exception {
101         Mode mod = ruleManager.getMode(mode);
102         mod.fireRule(node);
103     }
104 
105     /***
106      * Processes the result of the xpath expression. The xpath expression is
107      * evaluated against the provided input object.
108      * 
109      * @param input
110      *            the input object
111      * @param xpath
112      *            the xpath expression
113      * @throws Exception
114      *             if something goes wrong
115      */
116     public void applyTemplates(Object input, XPath xpath) throws Exception {
117         applyTemplates(input, xpath, this.modeName);
118     }
119 
120     /***
121      * Processes the result of the xpath expression in the given mode. The xpath
122      * expression is evaluated against the provided input object.
123      * 
124      * @param input
125      *            the input object
126      * @param xpath
127      *            the xpath expression
128      * @param mode
129      *            the mode
130      * @throws Exception
131      *             if something goes wrong
132      */
133     public void applyTemplates(Object input, XPath xpath, String mode)
134             throws Exception {
135         Mode mod = ruleManager.getMode(mode);
136 
137         List list = xpath.selectNodes(input);
138         Iterator it = list.iterator();
139         while (it.hasNext()) {
140             Node current = (Node) it.next();
141             mod.fireRule(current);
142         }
143     }
144 
145     /***
146      * Processes the result of the xpath expression. The xpath expression is
147      * evaluated against the provided input object.
148      * 
149      * @param input
150      *            the input object
151      * @param xpath
152      *            the xpath expression
153      * @throws Exception
154      *             if something goes wrong
155      * @deprecated Use {@link Stylesheet#applyTemplates(Object, XPath)}instead.
156      */
157     public void applyTemplates(Object input, org.jaxen.XPath xpath)
158             throws Exception {
159         applyTemplates(input, xpath, this.modeName);
160     }
161 
162     /***
163      * Processes the result of the xpath expression in the given mode. The xpath
164      * expression is evaluated against the provided input object.
165      * 
166      * @param input
167      *            the input object
168      * @param xpath
169      *            the xpath expression
170      * @param mode
171      *            the mode
172      * @throws Exception
173      *             if something goes wrong
174      * @deprecated Use {@link Stylesheet#applyTemplates(Object, XPath, String)}
175      *             instead.
176      */
177     public void applyTemplates(Object input, org.jaxen.XPath xpath, String mode)
178             throws Exception {
179         Mode mod = ruleManager.getMode(mode);
180 
181         List list = xpath.selectNodes(input);
182         Iterator it = list.iterator();
183         while (it.hasNext()) {
184             Node current = (Node) it.next();
185             mod.fireRule(current);
186         }
187     }
188 
189     /***
190      * If input is a <code>Node</code>, this will processes all of the
191      * children of that node. If input is a <code>List</code> of
192      * <code>Nodes</code>s, these nodes will be iterated and all children of
193      * each node will be processed.
194      * 
195      * @param input
196      *            the input object, this can either be a <code>Node</code> or
197      *            a <code>List</code>
198      * @throws Exception
199      *             if something goes wrong
200      */
201     public void applyTemplates(Object input) throws Exception {
202         applyTemplates(input, this.modeName);
203     }
204 
205     /***
206      * Processes the input object in the given mode. If input is a
207      * <code>Node</code>, this will processes all of the children of that
208      * node. If input is a <code>List</code> of <code>Nodes</code>s, these
209      * nodes will be iterated and all children of each node will be processed.
210      * 
211      * @param input
212      *            the input object, this can either be a <code>Node</code> or
213      *            a <code>List</code>
214      * @param mode
215      *            the mode
216      * @throws Exception
217      *             if something goes wrong
218      */
219     public void applyTemplates(Object input, String mode) throws Exception {
220         Mode mod = ruleManager.getMode(mode);
221 
222         if (input instanceof Element) {
223             // iterate through all children
224             Element element = (Element) input;
225             for (int i = 0, size = element.nodeCount(); i < size; i++) {
226                 Node node = element.node(i);
227                 mod.fireRule(node);
228             }
229         } else if (input instanceof Document) {
230             // iterate through all children
231             Document document = (Document) input;
232             for (int i = 0, size = document.nodeCount(); i < size; i++) {
233                 Node node = document.node(i);
234                 mod.fireRule(node);
235             }
236         } else if (input instanceof List) {
237             List list = (List) input;
238 
239             for (int i = 0, size = list.size(); i < size; i++) {
240                 Object object = list.get(i);
241 
242                 if (object instanceof Element) {
243                     applyTemplates((Element) object, mode);
244                 } else if (object instanceof Document) {
245                     applyTemplates((Document) object, mode);
246                 }
247             }
248         }
249     }
250 
251     public void clear() {
252         ruleManager.clear();
253     }
254 
255     // Properties
256     // -------------------------------------------------------------------------
257 
258     /***
259      * DOCUMENT ME!
260      * 
261      * @return the name of the mode the stylesheet uses by default
262      */
263     public String getModeName() {
264         return modeName;
265     }
266 
267     /***
268      * Sets the name of the mode that the stylesheet uses by default.
269      * 
270      * @param modeName
271      *            DOCUMENT ME!
272      */
273     public void setModeName(String modeName) {
274         this.modeName = modeName;
275     }
276 
277     /***
278      * DOCUMENT ME!
279      * 
280      * @return the default value-of action which is used in the default rules
281      *         for the pattern "text()|&#64;"
282      */
283     public Action getValueOfAction() {
284         return ruleManager.getValueOfAction();
285     }
286 
287     /***
288      * Sets the default value-of action which is used in the default rules for
289      * the pattern "text()|&#64;"
290      * 
291      * @param valueOfAction
292      *            DOCUMENT ME!
293      */
294     public void setValueOfAction(Action valueOfAction) {
295         ruleManager.setValueOfAction(valueOfAction);
296     }
297 }
298 
299 /*
300  * Redistribution and use of this software and associated documentation
301  * ("Software"), with or without modification, are permitted provided that the
302  * following conditions are met:
303  * 
304  * 1. Redistributions of source code must retain copyright statements and
305  * notices. Redistributions must also contain a copy of this document.
306  * 
307  * 2. Redistributions in binary form must reproduce the above copyright notice,
308  * this list of conditions and the following disclaimer in the documentation
309  * and/or other materials provided with the distribution.
310  * 
311  * 3. The name "DOM4J" must not be used to endorse or promote products derived
312  * from this Software without prior written permission of MetaStuff, Ltd. For
313  * written permission, please contact dom4j-info@metastuff.com.
314  * 
315  * 4. Products derived from this Software may not be called "DOM4J" nor may
316  * "DOM4J" appear in their names without prior written permission of MetaStuff,
317  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
318  * 
319  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
320  * 
321  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
322  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
323  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
324  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
325  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
326  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
327  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
328  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
329  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
330  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
331  * POSSIBILITY OF SUCH DAMAGE.
332  * 
333  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
334  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/rule/Action.html0000644000175000017500000001471510242117716020647 0ustar ebourgebourg Action xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.rule;
9   
10  import org.dom4j.Node;
11  
12  /***
13   * <p>
14   * <code>Action</code> represents some default action which should occur when
15   * a rule matches a node in the XSLT processing model.
16   * </p>
17   * 
18   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
19   * @version $Revision: 1.7 $
20   */
21  public interface Action {
22      void run(Node node) throws Exception;
23  }
24  
25  /*
26   * Redistribution and use of this software and associated documentation
27   * ("Software"), with or without modification, are permitted provided that the
28   * following conditions are met:
29   * 
30   * 1. Redistributions of source code must retain copyright statements and
31   * notices. Redistributions must also contain a copy of this document.
32   * 
33   * 2. Redistributions in binary form must reproduce the above copyright notice,
34   * this list of conditions and the following disclaimer in the documentation
35   * and/or other materials provided with the distribution.
36   * 
37   * 3. The name "DOM4J" must not be used to endorse or promote products derived
38   * from this Software without prior written permission of MetaStuff, Ltd. For
39   * written permission, please contact dom4j-info@metastuff.com.
40   * 
41   * 4. Products derived from this Software may not be called "DOM4J" nor may
42   * "DOM4J" appear in their names without prior written permission of MetaStuff,
43   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
44   * 
45   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
46   * 
47   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
48   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
50   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
51   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
52   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
53   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
54   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
55   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
56   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
57   * POSSIBILITY OF SUCH DAMAGE.
58   * 
59   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
60   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/rule/Pattern.html0000644000175000017500000002676710242117575021064 0ustar ebourgebourg Pattern xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.rule;
9   
10  import org.dom4j.Node;
11  import org.dom4j.NodeFilter;
12  
13  /***
14   * <p>
15   * <code>Pattern</code> defines the behaviour for pattern in the XSLT
16   * processing model.
17   * </p>
18   * 
19   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
20   * @version $Revision: 1.6 $
21   */
22  public interface Pattern extends NodeFilter {
23      // These node numbers are compatable with DOM4J's Node types
24  
25      /*** Matches any node */
26      short ANY_NODE = 0;
27  
28      /*** Matches no nodes */
29      short NONE = 9999;
30  
31      /*** Count of the number of node types */
32      short NUMBER_OF_TYPES = Node.UNKNOWN_NODE;
33  
34      /***
35       * According to the <a href="http://www.w3.org/TR/xslt11/#conflict">spec
36       * </a> we should return 0.5 if we cannot determine the priority
37       */
38      double DEFAULT_PRIORITY = 0.5;
39  
40      /***
41       * DOCUMENT ME!
42       * 
43       * @param node
44       *            DOCUMENT ME!
45       * 
46       * @return true if the pattern matches the given DOM4J node.
47       */
48      boolean matches(Node node);
49  
50      /***
51       * Returns the default resolution policy of the pattern according to the <a
52       * href="http://www.w3.org/TR/xslt11/#conflict"> XSLT conflict resolution
53       * spec </a>.
54       * 
55       * @return DOCUMENT ME!
56       */
57      double getPriority();
58  
59      /***
60       * If this pattern is a union pattern then this method should return an
61       * array of patterns which describe the union pattern, which should contain
62       * more than one pattern. Otherwise this method should return null.
63       * 
64       * @return an array of the patterns which make up this union pattern or null
65       *         if this pattern is not a union pattern
66       */
67      Pattern[] getUnionPatterns();
68  
69      /***
70       * DOCUMENT ME!
71       * 
72       * @return the type of node the pattern matches which by default should
73       *         return ANY_NODE if it can match any kind of node.
74       */
75      short getMatchType();
76  
77      /***
78       * For patterns which only match an ATTRIBUTE_NODE or an ELEMENT_NODE then
79       * this pattern may return the name of the element or attribute it matches.
80       * This allows a more efficient rule matching algorithm to be performed,
81       * rather than a brute force approach of evaluating every pattern for a
82       * given Node.
83       * 
84       * @return the name of the element or attribute this pattern matches or null
85       *         if this pattern matches any or more than one name.
86       */
87      String getMatchesNodeName();
88  }
89  
90  /*
91   * Redistribution and use of this software and associated documentation
92   * ("Software"), with or without modification, are permitted provided that the
93   * following conditions are met:
94   * 
95   * 1. Redistributions of source code must retain copyright statements and
96   * notices. Redistributions must also contain a copy of this document.
97   * 
98   * 2. Redistributions in binary form must reproduce the above copyright notice,
99   * this list of conditions and the following disclaimer in the documentation
100  * and/or other materials provided with the distribution.
101  * 
102  * 3. The name "DOM4J" must not be used to endorse or promote products derived
103  * from this Software without prior written permission of MetaStuff, Ltd. For
104  * written permission, please contact dom4j-info@metastuff.com.
105  * 
106  * 4. Products derived from this Software may not be called "DOM4J" nor may
107  * "DOM4J" appear in their names without prior written permission of MetaStuff,
108  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
109  * 
110  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
111  * 
112  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
113  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
114  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
115  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
116  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
117  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
118  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
119  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
120  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
121  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
122  * POSSIBILITY OF SUCH DAMAGE.
123  * 
124  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
125  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/rule/package-summary.html0000644000175000017500000000605210242117742022512 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.rule

Class Summary
Action
Mode
NullAction
Pattern
Rule
RuleManager
RuleSet
Stylesheet
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref/org/dom4j/rule/package-frame.html0000644000175000017500000000264510242117677022122 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.rule

org.dom4j.rule

Classes

  • Action
  • Mode
  • NullAction
  • Pattern
  • Rule
  • RuleManager
  • RuleSet
  • Stylesheet
dom4j-1.6.1/docs/xref/org/dom4j/rule/RuleSet.html0000644000175000017500000003053110242117747021013 0ustar ebourgebourg RuleSet xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.rule;
9   
10  import java.util.ArrayList;
11  import java.util.Collections;
12  
13  import org.dom4j.Node;
14  
15  /***
16   * <p>
17   * <code>RuleSet</code> manages a set of rules which are sorted in order of
18   * relevance according to the XSLT defined conflict resolution policy. This
19   * makes finding the correct rule for a DOM4J Node using the XSLT processing
20   * model efficient as the rules can be evaluated in order of priority.
21   * </p>
22   * 
23   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
24   * @version $Revision: 1.10 $
25   */
26  public class RuleSet {
27      /*** An unordered list of Rule objects */
28      private ArrayList rules = new ArrayList();
29  
30      /*** A lazily evaluated and cached array of rules sorted */
31      private Rule[] ruleArray;
32  
33      public RuleSet() {
34      }
35  
36      public String toString() {
37          return super.toString() + " [RuleSet: " + rules + " ]";
38      }
39  
40      /***
41       * Performs an XSLT processing model match for the rule which matches the
42       * given Node the best.
43       * 
44       * @param node
45       *            is the DOM4J Node to match against
46       * 
47       * @return the matching Rule or no rule if none matched
48       */
49      public Rule getMatchingRule(Node node) {
50          Rule[] matches = getRuleArray();
51  
52          for (int i = matches.length - 1; i >= 0; i--) {
53              Rule rule = matches[i];
54  
55              if (rule.matches(node)) {
56                  return rule;
57              }
58          }
59  
60          return null;
61      }
62  
63      public void addRule(Rule rule) {
64          rules.add(rule);
65          ruleArray = null;
66      }
67  
68      public void removeRule(Rule rule) {
69          rules.remove(rule);
70          ruleArray = null;
71      }
72  
73      /***
74       * Adds all the rules to this RuleSet from the given other rule set.
75       * 
76       * @param that
77       *            DOCUMENT ME!
78       */
79      public void addAll(RuleSet that) {
80          rules.addAll(that.rules);
81          ruleArray = null;
82      }
83  
84      /***
85       * Returns an array of sorted rules.
86       * 
87       * @return the rules as a sorted array in ascending precendence so that the
88       *         rules at the end of the array should be used first
89       */
90      protected Rule[] getRuleArray() {
91          if (ruleArray == null) {
92              Collections.sort(rules);
93  
94              int size = rules.size();
95              ruleArray = new Rule[size];
96              rules.toArray(ruleArray);
97          }
98  
99          return ruleArray;
100     }
101 }
102 
103 /*
104  * Redistribution and use of this software and associated documentation
105  * ("Software"), with or without modification, are permitted provided that the
106  * following conditions are met:
107  * 
108  * 1. Redistributions of source code must retain copyright statements and
109  * notices. Redistributions must also contain a copy of this document.
110  * 
111  * 2. Redistributions in binary form must reproduce the above copyright notice,
112  * this list of conditions and the following disclaimer in the documentation
113  * and/or other materials provided with the distribution.
114  * 
115  * 3. The name "DOM4J" must not be used to endorse or promote products derived
116  * from this Software without prior written permission of MetaStuff, Ltd. For
117  * written permission, please contact dom4j-info@metastuff.com.
118  * 
119  * 4. Products derived from this Software may not be called "DOM4J" nor may
120  * "DOM4J" appear in their names without prior written permission of MetaStuff,
121  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
122  * 
123  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
124  * 
125  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
126  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
127  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
128  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
129  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
130  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
131  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
132  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
133  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
134  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
135  * POSSIBILITY OF SUCH DAMAGE.
136  * 
137  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
138  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/rule/RuleManager.html0000644000175000017500000005046010242117722021626 0ustar ebourgebourg RuleManager xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.rule;
9   
10  import java.util.HashMap;
11  
12  import org.dom4j.Document;
13  import org.dom4j.Element;
14  import org.dom4j.Node;
15  import org.dom4j.rule.pattern.NodeTypePattern;
16  
17  /***
18   * <p>
19   * <code>RuleManager</code> manages a set of rules such that a rule can be
20   * found for a given DOM4J Node using the XSLT processing model.
21   * </p>
22   * 
23   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
24   * @version $Revision: 1.9 $
25   */
26  public class RuleManager {
27      /*** Map of modes indexed by mode */
28      private HashMap modes = new HashMap();
29  
30      /***
31       * A counter so that rules can be ordered by the order in which they were
32       * added to the rule base
33       */
34      private int appearenceCount;
35  
36      /*** Holds value of property valueOfAction. */
37      private Action valueOfAction;
38  
39      public RuleManager() {
40      }
41  
42      /***
43       * DOCUMENT ME!
44       * 
45       * @param modeName
46       *            DOCUMENT ME!
47       * 
48       * @return the Mode instance for the given mode name. If one does not exist
49       *         then it will be created.
50       */
51      public Mode getMode(String modeName) {
52          Mode mode = (Mode) modes.get(modeName);
53  
54          if (mode == null) {
55              mode = createMode();
56              modes.put(modeName, mode);
57          }
58  
59          return mode;
60      }
61  
62      public void addRule(Rule rule) {
63          rule.setAppearenceCount(++appearenceCount);
64  
65          Mode mode = getMode(rule.getMode());
66          Rule[] childRules = rule.getUnionRules();
67  
68          if (childRules != null) {
69              for (int i = 0, size = childRules.length; i < size; i++) {
70                  mode.addRule(childRules[i]);
71              }
72          } else {
73              mode.addRule(rule);
74          }
75      }
76  
77      public void removeRule(Rule rule) {
78          Mode mode = getMode(rule.getMode());
79          Rule[] childRules = rule.getUnionRules();
80  
81          if (childRules != null) {
82              for (int i = 0, size = childRules.length; i < size; i++) {
83                  mode.removeRule(childRules[i]);
84              }
85          } else {
86              mode.removeRule(rule);
87          }
88      }
89  
90      /***
91       * Performs an XSLT processing model match for the rule which matches the
92       * given Node the best.
93       * 
94       * @param modeName
95       *            is the name of the mode associated with the rule if any
96       * @param node
97       *            is the DOM4J Node to match against
98       * 
99       * @return the matching Rule or no rule if none matched
100      */
101     public Rule getMatchingRule(String modeName, Node node) {
102         Mode mode = (Mode) modes.get(modeName);
103 
104         if (mode != null) {
105             return mode.getMatchingRule(node);
106         } else {
107             System.out.println("Warning: No Mode for mode: " + mode);
108 
109             return null;
110         }
111     }
112 
113     public void clear() {
114         modes.clear();
115         appearenceCount = 0;
116     }
117 
118     // Properties
119     // -------------------------------------------------------------------------
120 
121     /***
122      * DOCUMENT ME!
123      * 
124      * @return the default value-of action which is used in the default rules
125      *         for the pattern "text()|&#64;"
126      */
127     public Action getValueOfAction() {
128         return valueOfAction;
129     }
130 
131     /***
132      * Sets the default value-of action which is used in the default rules for
133      * the pattern "text()|&#64;"
134      * 
135      * @param valueOfAction
136      *            DOCUMENT ME!
137      */
138     public void setValueOfAction(Action valueOfAction) {
139         this.valueOfAction = valueOfAction;
140     }
141 
142     // Implementation methods
143     // -------------------------------------------------------------------------
144 
145     /***
146      * A factory method to return a new {@link Mode}instance which should add
147      * the necessary default rules
148      * 
149      * @return DOCUMENT ME!
150      */
151     protected Mode createMode() {
152         Mode mode = new Mode();
153         addDefaultRules(mode);
154 
155         return mode;
156     }
157 
158     /***
159      * Adds the default stylesheet rules to the given {@link Mode}instance
160      * 
161      * @param mode
162      *            DOCUMENT ME!
163      */
164     protected void addDefaultRules(final Mode mode) {
165         // add an apply templates rule
166         Action applyTemplates = new Action() {
167             public void run(Node node) throws Exception {
168                 if (node instanceof Element) {
169                     mode.applyTemplates((Element) node);
170                 } else if (node instanceof Document) {
171                     mode.applyTemplates((Document) node);
172                 }
173             }
174         };
175 
176         Action valueOf = getValueOfAction();
177 
178         addDefaultRule(mode, NodeTypePattern.ANY_DOCUMENT, applyTemplates);
179         addDefaultRule(mode, NodeTypePattern.ANY_ELEMENT, applyTemplates);
180 
181         if (valueOf != null) {
182             addDefaultRule(mode, NodeTypePattern.ANY_ATTRIBUTE, valueOf);
183             addDefaultRule(mode, NodeTypePattern.ANY_TEXT, valueOf);
184         }
185     }
186 
187     protected void addDefaultRule(Mode mode, Pattern pattern, Action action) {
188         Rule rule = createDefaultRule(pattern, action);
189         mode.addRule(rule);
190     }
191 
192     protected Rule createDefaultRule(Pattern pattern, Action action) {
193         Rule rule = new Rule(pattern, action);
194         rule.setImportPrecedence(-1);
195 
196         return rule;
197     }
198 }
199 
200 /*
201  * Redistribution and use of this software and associated documentation
202  * ("Software"), with or without modification, are permitted provided that the
203  * following conditions are met:
204  * 
205  * 1. Redistributions of source code must retain copyright statements and
206  * notices. Redistributions must also contain a copy of this document.
207  * 
208  * 2. Redistributions in binary form must reproduce the above copyright notice,
209  * this list of conditions and the following disclaimer in the documentation
210  * and/or other materials provided with the distribution.
211  * 
212  * 3. The name "DOM4J" must not be used to endorse or promote products derived
213  * from this Software without prior written permission of MetaStuff, Ltd. For
214  * written permission, please contact dom4j-info@metastuff.com.
215  * 
216  * 4. Products derived from this Software may not be called "DOM4J" nor may
217  * "DOM4J" appear in their names without prior written permission of MetaStuff,
218  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
219  * 
220  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
221  * 
222  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
223  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
224  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
225  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
226  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
227  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
228  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
229  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
230  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
231  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
232  * POSSIBILITY OF SUCH DAMAGE.
233  * 
234  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
235  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/rule/pattern/0000755000175000017500000000000012133227266020214 5ustar ebourgebourgdom4j-1.6.1/docs/xref/org/dom4j/rule/pattern/package-summary.html0000644000175000017500000000426110242117636024171 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.rule.pattern

Class Summary
DefaultPattern
NodeTypePattern
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref/org/dom4j/rule/pattern/package-frame.html0000644000175000017500000000151610242117723023563 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.rule.pattern

org.dom4j.rule.pattern

Classes

  • DefaultPattern
  • NodeTypePattern
dom4j-1.6.1/docs/xref/org/dom4j/rule/pattern/DefaultPattern.html0000644000175000017500000002166310242117550024025 0ustar ebourgebourg DefaultPattern xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.rule.pattern;
9   
10  import org.dom4j.Node;
11  import org.dom4j.NodeFilter;
12  import org.dom4j.rule.Pattern;
13  
14  /***
15   * <p>
16   * <code>DefaultPattern</code> a default implementation of Pattern which can
17   * take any XPath implementation or NodeFilter for defining the pattern.
18   * <b>WARNING </b> this implementation causes a worst case, brute force XSLT
19   * rule evaluation to be performed. Wherever possible the methods {@link
20   * #getPriority}, {@link #getMatchType}and {@link #getMatchesNodeName}should
21   * be overloaded to allow more rule filtering to occur.
22   * </p>
23   * 
24   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
25   * @version $Revision: 1.6 $
26   */
27  public class DefaultPattern implements Pattern {
28      private NodeFilter filter;
29  
30      public DefaultPattern(NodeFilter filter) {
31          this.filter = filter;
32      }
33  
34      public boolean matches(Node node) {
35          return filter.matches(node);
36      }
37  
38      public double getPriority() {
39          return Pattern.DEFAULT_PRIORITY;
40      }
41  
42      public Pattern[] getUnionPatterns() {
43          return null;
44      }
45  
46      public short getMatchType() {
47          return ANY_NODE;
48      }
49  
50      public String getMatchesNodeName() {
51          return null;
52      }
53  }
54  
55  /*
56   * Redistribution and use of this software and associated documentation
57   * ("Software"), with or without modification, are permitted provided that the
58   * following conditions are met:
59   * 
60   * 1. Redistributions of source code must retain copyright statements and
61   * notices. Redistributions must also contain a copy of this document.
62   * 
63   * 2. Redistributions in binary form must reproduce the above copyright notice,
64   * this list of conditions and the following disclaimer in the documentation
65   * and/or other materials provided with the distribution.
66   * 
67   * 3. The name "DOM4J" must not be used to endorse or promote products derived
68   * from this Software without prior written permission of MetaStuff, Ltd. For
69   * written permission, please contact dom4j-info@metastuff.com.
70   * 
71   * 4. Products derived from this Software may not be called "DOM4J" nor may
72   * "DOM4J" appear in their names without prior written permission of MetaStuff,
73   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
74   * 
75   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
76   * 
77   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
78   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
79   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
80   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
81   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
82   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
83   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
84   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
85   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
86   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
87   * POSSIBILITY OF SUCH DAMAGE.
88   * 
89   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
90   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/rule/pattern/NodeTypePattern.html0000644000175000017500000002732210242117553024171 0ustar ebourgebourg NodeTypePattern xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.rule.pattern;
9   
10  import org.dom4j.Node;
11  import org.dom4j.rule.Pattern;
12  
13  /***
14   * <p>
15   * <code>NodeTypePattern</code> implements a Pattern which matches any node of
16   * the given node type.
17   * </p>
18   * 
19   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
20   * @version $Revision: 1.7 $
21   */
22  public class NodeTypePattern implements Pattern {
23      /*** A pattern which matches any Attribute node */
24      public static final NodeTypePattern ANY_ATTRIBUTE = new NodeTypePattern(
25              Node.ATTRIBUTE_NODE);
26  
27      /*** A pattern which matches any Comment node */
28      public static final NodeTypePattern ANY_COMMENT = new NodeTypePattern(
29              Node.COMMENT_NODE);
30  
31      /*** A pattern which matches any Document node */
32      public static final NodeTypePattern ANY_DOCUMENT = new NodeTypePattern(
33              Node.DOCUMENT_NODE);
34  
35      /*** A pattern which matches any Element node */
36      public static final NodeTypePattern ANY_ELEMENT = new NodeTypePattern(
37              Node.ELEMENT_NODE);
38  
39      /*** A pattern which matches any ProcessingInstruction node */
40      public static final NodeTypePattern ANY_PROCESSING_INSTRUCTION = 
41              new NodeTypePattern(Node.PROCESSING_INSTRUCTION_NODE);
42  
43      /*** A pattern which matches any Text node */
44      public static final NodeTypePattern ANY_TEXT = new NodeTypePattern(
45              Node.TEXT_NODE);
46  
47      private short nodeType;
48  
49      public NodeTypePattern(short nodeType) {
50          this.nodeType = nodeType;
51      }
52  
53      public boolean matches(Node node) {
54          return node.getNodeType() == nodeType;
55      }
56  
57      public double getPriority() {
58          return Pattern.DEFAULT_PRIORITY;
59      }
60  
61      public Pattern[] getUnionPatterns() {
62          return null;
63      }
64  
65      public short getMatchType() {
66          return nodeType;
67      }
68  
69      public String getMatchesNodeName() {
70          return null;
71      }
72  }
73  
74  /*
75   * Redistribution and use of this software and associated documentation
76   * ("Software"), with or without modification, are permitted provided that the
77   * following conditions are met:
78   * 
79   * 1. Redistributions of source code must retain copyright statements and
80   * notices. Redistributions must also contain a copy of this document.
81   * 
82   * 2. Redistributions in binary form must reproduce the above copyright notice,
83   * this list of conditions and the following disclaimer in the documentation
84   * and/or other materials provided with the distribution.
85   * 
86   * 3. The name "DOM4J" must not be used to endorse or promote products derived
87   * from this Software without prior written permission of MetaStuff, Ltd. For
88   * written permission, please contact dom4j-info@metastuff.com.
89   * 
90   * 4. Products derived from this Software may not be called "DOM4J" nor may
91   * "DOM4J" appear in their names without prior written permission of MetaStuff,
92   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
93   * 
94   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
95   * 
96   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
97   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
98   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
99   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
100  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
101  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
102  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
103  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
104  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
105  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
106  * POSSIBILITY OF SUCH DAMAGE.
107  * 
108  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
109  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/rule/Mode.html0000644000175000017500000006262210242117616020315 0ustar ebourgebourg Mode xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.rule;
9   
10  import java.util.HashMap;
11  import java.util.Map;
12  
13  import org.dom4j.Attribute;
14  import org.dom4j.Document;
15  import org.dom4j.Element;
16  import org.dom4j.Node;
17  
18  /***
19   * <p>
20   * <code>Mode</code> manages a number of RuleSet instances for the mode in a
21   * stylesheet. It is responsible for finding the correct rule for a given DOM4J
22   * Node using the XSLT processing model uses the smallest possible RuleSet to
23   * reduce the number of Rule evaluations.
24   * </p>
25   * 
26   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
27   * @version $Revision: 1.9 $
28   */
29  public class Mode {
30      private RuleSet[] ruleSets = new RuleSet[Pattern.NUMBER_OF_TYPES];
31  
32      /*** Map of exact (local) element names to RuleSet instances */
33      private Map elementNameRuleSets;
34  
35      /*** Map of exact (local) attribute names to RuleSet instances */
36      private Map attributeNameRuleSets;
37  
38      public Mode() {
39      }
40  
41      /***
42       * Runs the actions associated with the given node
43       * 
44       * @param node
45       *            DOCUMENT ME!
46       * 
47       * @throws Exception
48       *             DOCUMENT ME!
49       */
50      public void fireRule(Node node) throws Exception {
51          if (node != null) {
52              Rule rule = getMatchingRule(node);
53  
54              if (rule != null) {
55                  Action action = rule.getAction();
56  
57                  if (action != null) {
58                      action.run(node);
59                  }
60              }
61          }
62      }
63  
64      public void applyTemplates(Element element) throws Exception {
65          for (int i = 0, size = element.attributeCount(); i < size; i++) {
66              Attribute attribute = element.attribute(i);
67              fireRule(attribute);
68          }
69  
70          for (int i = 0, size = element.nodeCount(); i < size; i++) {
71              Node node = element.node(i);
72              fireRule(node);
73          }
74      }
75  
76      public void applyTemplates(Document document) throws Exception {
77          for (int i = 0, size = document.nodeCount(); i < size; i++) {
78              Node node = document.node(i);
79              fireRule(node);
80          }
81      }
82  
83      public void addRule(Rule rule) {
84          int matchType = rule.getMatchType();
85          String name = rule.getMatchesNodeName();
86  
87          if (name != null) {
88              if (matchType == Node.ELEMENT_NODE) {
89                  elementNameRuleSets = addToNameMap(elementNameRuleSets, name,
90                          rule);
91              } else if (matchType == Node.ATTRIBUTE_NODE) {
92                  attributeNameRuleSets = addToNameMap(attributeNameRuleSets,
93                          name, rule);
94              }
95          }
96  
97          if (matchType >= Pattern.NUMBER_OF_TYPES) {
98              matchType = Pattern.ANY_NODE;
99          }
100 
101         if (matchType == Pattern.ANY_NODE) {
102             // add rule to all other RuleSets if they exist
103             for (int i = 1, size = ruleSets.length; i < size; i++) {
104                 RuleSet ruleSet = ruleSets[i];
105 
106                 if (ruleSet != null) {
107                     ruleSet.addRule(rule);
108                 }
109             }
110         }
111 
112         getRuleSet(matchType).addRule(rule);
113     }
114 
115     public void removeRule(Rule rule) {
116         int matchType = rule.getMatchType();
117         String name = rule.getMatchesNodeName();
118 
119         if (name != null) {
120             if (matchType == Node.ELEMENT_NODE) {
121                 removeFromNameMap(elementNameRuleSets, name, rule);
122             } else if (matchType == Node.ATTRIBUTE_NODE) {
123                 removeFromNameMap(attributeNameRuleSets, name, rule);
124             }
125         }
126 
127         if (matchType >= Pattern.NUMBER_OF_TYPES) {
128             matchType = Pattern.ANY_NODE;
129         }
130 
131         getRuleSet(matchType).removeRule(rule);
132 
133         if (matchType != Pattern.ANY_NODE) {
134             getRuleSet(Pattern.ANY_NODE).removeRule(rule);
135         }
136     }
137 
138     /***
139      * Performs an XSLT processing model match for the rule which matches the
140      * given Node the best.
141      * 
142      * @param node
143      *            is the DOM4J Node to match against
144      * 
145      * @return the matching Rule or no rule if none matched
146      */
147     public Rule getMatchingRule(Node node) {
148         int matchType = node.getNodeType();
149 
150         if (matchType == Node.ELEMENT_NODE) {
151             if (elementNameRuleSets != null) {
152                 String name = node.getName();
153                 RuleSet ruleSet = (RuleSet) elementNameRuleSets.get(name);
154 
155                 if (ruleSet != null) {
156                     Rule answer = ruleSet.getMatchingRule(node);
157 
158                     if (answer != null) {
159                         return answer;
160                     }
161                 }
162             }
163         } else if (matchType == Node.ATTRIBUTE_NODE) {
164             if (attributeNameRuleSets != null) {
165                 String name = node.getName();
166                 RuleSet ruleSet = (RuleSet) attributeNameRuleSets.get(name);
167 
168                 if (ruleSet != null) {
169                     Rule answer = ruleSet.getMatchingRule(node);
170 
171                     if (answer != null) {
172                         return answer;
173                     }
174                 }
175             }
176         }
177 
178         if ((matchType < 0) || (matchType >= ruleSets.length)) {
179             matchType = Pattern.ANY_NODE;
180         }
181 
182         Rule answer = null;
183         RuleSet ruleSet = ruleSets[matchType];
184 
185         if (ruleSet != null) {
186             // try rules that match this kind of node first
187             answer = ruleSet.getMatchingRule(node);
188         }
189 
190         if ((answer == null) && (matchType != Pattern.ANY_NODE)) {
191             // try general rules that match any kind of node
192             ruleSet = ruleSets[Pattern.ANY_NODE];
193 
194             if (ruleSet != null) {
195                 answer = ruleSet.getMatchingRule(node);
196             }
197         }
198 
199         return answer;
200     }
201 
202     /***
203      * DOCUMENT ME!
204      * 
205      * @param matchType
206      *            DOCUMENT ME!
207      * 
208      * @return the RuleSet for the given matching type. This method will never
209      *         return null, a new instance will be created.
210      */
211     protected RuleSet getRuleSet(int matchType) {
212         RuleSet ruleSet = ruleSets[matchType];
213 
214         if (ruleSet == null) {
215             ruleSet = new RuleSet();
216             ruleSets[matchType] = ruleSet;
217 
218             // add the patterns that match any node
219             if (matchType != Pattern.ANY_NODE) {
220                 RuleSet allRules = ruleSets[Pattern.ANY_NODE];
221 
222                 if (allRules != null) {
223                     ruleSet.addAll(allRules);
224                 }
225             }
226         }
227 
228         return ruleSet;
229     }
230 
231     /***
232      * Adds the Rule to a RuleSet for the given name.
233      * 
234      * @param map
235      *            DOCUMENT ME!
236      * @param name
237      *            DOCUMENT ME!
238      * @param rule
239      *            DOCUMENT ME!
240      * 
241      * @return the Map (which will be created if the given map was null
242      */
243     protected Map addToNameMap(Map map, String name, Rule rule) {
244         if (map == null) {
245             map = new HashMap();
246         }
247 
248         RuleSet ruleSet = (RuleSet) map.get(name);
249 
250         if (ruleSet == null) {
251             ruleSet = new RuleSet();
252             map.put(name, ruleSet);
253         }
254 
255         ruleSet.addRule(rule);
256 
257         return map;
258     }
259 
260     protected void removeFromNameMap(Map map, String name, Rule rule) {
261         if (map != null) {
262             RuleSet ruleSet = (RuleSet) map.get(name);
263 
264             if (ruleSet != null) {
265                 ruleSet.removeRule(rule);
266             }
267         }
268     }
269 }
270 
271 /*
272  * Redistribution and use of this software and associated documentation
273  * ("Software"), with or without modification, are permitted provided that the
274  * following conditions are met:
275  * 
276  * 1. Redistributions of source code must retain copyright statements and
277  * notices. Redistributions must also contain a copy of this document.
278  * 
279  * 2. Redistributions in binary form must reproduce the above copyright notice,
280  * this list of conditions and the following disclaimer in the documentation
281  * and/or other materials provided with the distribution.
282  * 
283  * 3. The name "DOM4J" must not be used to endorse or promote products derived
284  * from this Software without prior written permission of MetaStuff, Ltd. For
285  * written permission, please contact dom4j-info@metastuff.com.
286  * 
287  * 4. Products derived from this Software may not be called "DOM4J" nor may
288  * "DOM4J" appear in their names without prior written permission of MetaStuff,
289  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
290  * 
291  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
292  * 
293  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
294  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
295  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
296  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
297  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
298  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
299  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
300  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
301  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
302  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
303  * POSSIBILITY OF SUCH DAMAGE.
304  * 
305  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
306  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/rule/Rule.html0000644000175000017500000006466310242117667020355 0ustar ebourgebourg Rule xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.rule;
9   
10  import org.dom4j.Node;
11  
12  /***
13   * <p>
14   * <code>Rule</code> matches against DOM4J Node so that some action can be
15   * performed such as in the XSLT processing model.
16   * </p>
17   * 
18   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
19   * @version $Revision: 1.7 $
20   */
21  public class Rule implements Comparable {
22      /*** Holds value of property mode. */
23      private String mode;
24  
25      /*** Holds value of property importPrecedence. */
26      private int importPrecedence;
27  
28      /*** Holds value of property priority. */
29      private double priority;
30  
31      /*** Holds value of property appearenceCount. */
32      private int appearenceCount;
33  
34      /*** Holds value of property pattern. */
35      private Pattern pattern;
36  
37      /*** Holds value of property action. */
38      private Action action;
39  
40      public Rule() {
41          this.priority = Pattern.DEFAULT_PRIORITY;
42      }
43  
44      public Rule(Pattern pattern) {
45          this.pattern = pattern;
46          this.priority = pattern.getPriority();
47      }
48  
49      public Rule(Pattern pattern, Action action) {
50          this(pattern);
51          this.action = action;
52      }
53  
54      /***
55       * Constructs a new Rule with the same instance data as the given rule but a
56       * different pattern.
57       * 
58       * @param that
59       *            DOCUMENT ME!
60       * @param pattern
61       *            DOCUMENT ME!
62       */
63      public Rule(Rule that, Pattern pattern) {
64          this.mode = that.mode;
65          this.importPrecedence = that.importPrecedence;
66          this.priority = that.priority;
67          this.appearenceCount = that.appearenceCount;
68          this.action = that.action;
69          this.pattern = pattern;
70      }
71  
72      public boolean equals(Object that) {
73          if (that instanceof Rule) {
74              return compareTo((Rule) that) == 0;
75          }
76  
77          return false;
78      }
79  
80      public int hashCode() {
81          return importPrecedence + appearenceCount;
82      }
83  
84      public int compareTo(Object that) {
85          if (that instanceof Rule) {
86              return compareTo((Rule) that);
87          }
88  
89          return getClass().getName().compareTo(that.getClass().getName());
90      }
91  
92      /***
93       * Compares two rules in XSLT processing model order assuming that the modes
94       * are equal.
95       * 
96       * @param that
97       *            DOCUMENT ME!
98       * 
99       * @return DOCUMENT ME!
100      */
101     public int compareTo(Rule that) {
102         int answer = this.importPrecedence - that.importPrecedence;
103 
104         if (answer == 0) {
105             answer = (int) Math.round(this.priority - that.priority);
106 
107             if (answer == 0) {
108                 answer = this.appearenceCount - that.appearenceCount;
109             }
110         }
111 
112         return answer;
113     }
114 
115     public String toString() {
116         return super.toString() + "[ pattern: " + getPattern() + " action: "
117                 + getAction() + " ]";
118     }
119 
120     /***
121      * DOCUMENT ME!
122      * 
123      * @param node
124      *            DOCUMENT ME!
125      * 
126      * @return true if the pattern matches the given DOM4J node.
127      */
128     public final boolean matches(Node node) {
129         return pattern.matches(node);
130     }
131 
132     /***
133      * If this rule contains a union pattern then this method should return an
134      * array of Rules which describe the union rule, which should contain more
135      * than one rule. Otherwise this method should return null.
136      * 
137      * @return an array of the rules which make up this union rule or null if
138      *         this rule is not a union rule
139      */
140     public Rule[] getUnionRules() {
141         Pattern[] patterns = pattern.getUnionPatterns();
142 
143         if (patterns == null) {
144             return null;
145         }
146 
147         int size = patterns.length;
148         Rule[] answer = new Rule[size];
149 
150         for (int i = 0; i < size; i++) {
151             answer[i] = new Rule(this, patterns[i]);
152         }
153 
154         return answer;
155     }
156 
157     /***
158      * DOCUMENT ME!
159      * 
160      * @return the type of node the pattern matches which by default should
161      *         return ANY_NODE if it can match any kind of node.
162      */
163     public final short getMatchType() {
164         return pattern.getMatchType();
165     }
166 
167     /***
168      * For patterns which only match an ATTRIBUTE_NODE or an ELEMENT_NODE then
169      * this pattern may return the name of the element or attribute it matches.
170      * This allows a more efficient rule matching algorithm to be performed,
171      * rather than a brute force approach of evaluating every pattern for a
172      * given Node.
173      * 
174      * @return the name of the element or attribute this pattern matches or null
175      *         if this pattern matches any or more than one name.
176      */
177     public final String getMatchesNodeName() {
178         return pattern.getMatchesNodeName();
179     }
180 
181     /***
182      * Getter for property mode.
183      * 
184      * @return Value of property mode.
185      */
186     public String getMode() {
187         return mode;
188     }
189 
190     /***
191      * Setter for property mode.
192      * 
193      * @param mode
194      *            New value of property mode.
195      */
196     public void setMode(String mode) {
197         this.mode = mode;
198     }
199 
200     /***
201      * Getter for property importPrecedence.
202      * 
203      * @return Value of property importPrecedence.
204      */
205     public int getImportPrecedence() {
206         return importPrecedence;
207     }
208 
209     /***
210      * Setter for property importPrecedence.
211      * 
212      * @param importPrecedence
213      *            New value of property importPrecedence.
214      */
215     public void setImportPrecedence(int importPrecedence) {
216         this.importPrecedence = importPrecedence;
217     }
218 
219     /***
220      * Getter for property priority.
221      * 
222      * @return Value of property priority.
223      */
224     public double getPriority() {
225         return priority;
226     }
227 
228     /***
229      * Setter for property priority.
230      * 
231      * @param priority
232      *            New value of property priority.
233      */
234     public void setPriority(double priority) {
235         this.priority = priority;
236     }
237 
238     /***
239      * Getter for property appearenceCount.
240      * 
241      * @return Value of property appearenceCount.
242      */
243     public int getAppearenceCount() {
244         return appearenceCount;
245     }
246 
247     /***
248      * Setter for property appearenceCount.
249      * 
250      * @param appearenceCount
251      *            New value of property appearenceCount.
252      */
253     public void setAppearenceCount(int appearenceCount) {
254         this.appearenceCount = appearenceCount;
255     }
256 
257     /***
258      * Getter for property pattern.
259      * 
260      * @return Value of property pattern.
261      */
262     public Pattern getPattern() {
263         return pattern;
264     }
265 
266     /***
267      * Setter for property pattern.
268      * 
269      * @param pattern
270      *            New value of property pattern.
271      */
272     public void setPattern(Pattern pattern) {
273         this.pattern = pattern;
274     }
275 
276     /***
277      * Getter for property action.
278      * 
279      * @return Value of property action.
280      */
281     public Action getAction() {
282         return action;
283     }
284 
285     /***
286      * Setter for property action.
287      * 
288      * @param action
289      *            New value of property action.
290      */
291     public void setAction(Action action) {
292         this.action = action;
293     }
294 }
295 
296 /*
297  * Redistribution and use of this software and associated documentation
298  * ("Software"), with or without modification, are permitted provided that the
299  * following conditions are met:
300  * 
301  * 1. Redistributions of source code must retain copyright statements and
302  * notices. Redistributions must also contain a copy of this document.
303  * 
304  * 2. Redistributions in binary form must reproduce the above copyright notice,
305  * this list of conditions and the following disclaimer in the documentation
306  * and/or other materials provided with the distribution.
307  * 
308  * 3. The name "DOM4J" must not be used to endorse or promote products derived
309  * from this Software without prior written permission of MetaStuff, Ltd. For
310  * written permission, please contact dom4j-info@metastuff.com.
311  * 
312  * 4. Products derived from this Software may not be called "DOM4J" nor may
313  * "DOM4J" appear in their names without prior written permission of MetaStuff,
314  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
315  * 
316  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
317  * 
318  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
319  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
320  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
321  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
322  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
323  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
324  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
325  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
326  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
327  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
328  * POSSIBILITY OF SUCH DAMAGE.
329  * 
330  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
331  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/rule/NullAction.html0000644000175000017500000001557510242117737021512 0ustar ebourgebourg NullAction xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.rule;
9   
10  import org.dom4j.Node;
11  
12  /***
13   * <p>
14   * <code>NullAction</code> represents an empty action that does nothing.
15   * </p>
16   * 
17   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
18   * @version $Revision: 1.7 $
19   */
20  public class NullAction implements Action {
21      /*** Singleton instance */
22      public static final NullAction SINGLETON = new NullAction();
23  
24      public void run(Node node) throws Exception {
25      }
26  }
27  
28  /*
29   * Redistribution and use of this software and associated documentation
30   * ("Software"), with or without modification, are permitted provided that the
31   * following conditions are met:
32   * 
33   * 1. Redistributions of source code must retain copyright statements and
34   * notices. Redistributions must also contain a copy of this document.
35   * 
36   * 2. Redistributions in binary form must reproduce the above copyright notice,
37   * this list of conditions and the following disclaimer in the documentation
38   * and/or other materials provided with the distribution.
39   * 
40   * 3. The name "DOM4J" must not be used to endorse or promote products derived
41   * from this Software without prior written permission of MetaStuff, Ltd. For
42   * written permission, please contact dom4j-info@metastuff.com.
43   * 
44   * 4. Products derived from this Software may not be called "DOM4J" nor may
45   * "DOM4J" appear in their names without prior written permission of MetaStuff,
46   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
47   * 
48   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
49   * 
50   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
51   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
54   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
55   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
56   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
57   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
58   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
59   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
60   * POSSIBILITY OF SUCH DAMAGE.
61   * 
62   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
63   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/InvalidXPathException.html0000644000175000017500000001711410242117637022673 0ustar ebourgebourg InvalidXPathException xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  /***
11   * <p>
12   * <code>InvalidXPathException</code> is thrown when an invalid XPath
13   * expression is used to traverse an XML document
14   * </p>
15   * 
16   * @version $Revision: 1.6.2.1 $
17   */
18  public class InvalidXPathException extends IllegalArgumentException {
19  	/*** The <code>serialVersionUID</code>. */
20  	private static final long serialVersionUID = 3257009869058881592L;
21  
22  	public InvalidXPathException(String xpath) {
23          super("Invalid XPath expression: " + xpath);
24      }
25  
26      public InvalidXPathException(String xpath, String reason) {
27          super("Invalid XPath expression: " + xpath + " " + reason);
28      }
29  
30      public InvalidXPathException(String xpath, Throwable t) {
31          super("Invalid XPath expression: '" + xpath 
32          		+ "'. Caused by: " + t.getMessage());
33      }
34  }
35  
36  /*
37   * Redistribution and use of this software and associated documentation
38   * ("Software"), with or without modification, are permitted provided that the
39   * following conditions are met:
40   * 
41   * 1. Redistributions of source code must retain copyright statements and
42   * notices. Redistributions must also contain a copy of this document.
43   * 
44   * 2. Redistributions in binary form must reproduce the above copyright notice,
45   * this list of conditions and the following disclaimer in the documentation
46   * and/or other materials provided with the distribution.
47   * 
48   * 3. The name "DOM4J" must not be used to endorse or promote products derived
49   * from this Software without prior written permission of MetaStuff, Ltd. For
50   * written permission, please contact dom4j-info@metastuff.com.
51   * 
52   * 4. Products derived from this Software may not be called "DOM4J" nor may
53   * "DOM4J" appear in their names without prior written permission of MetaStuff,
54   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
55   * 
56   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
57   * 
58   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
59   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
62   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
63   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
64   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
65   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
66   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
67   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
68   * POSSIBILITY OF SUCH DAMAGE.
69   * 
70   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
71   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/package-frame.html0000644000175000017500000000672610242117712021145 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j

org.dom4j

Classes

  • Attribute
  • Branch
  • CDATA
  • CharacterData
  • Comment
  • Document
  • DocumentException
  • DocumentFactory
  • DocumentHelper
  • DocumentType
  • Element
  • ElementHandler
  • ElementPath
  • Entity
  • IllegalAddException
  • InvalidXPathException
  • Namespace
  • Node
  • NodeFilter
  • ProcessingInstruction
  • QName
  • Text
  • Visitor
  • VisitorSupport
  • XPath
  • XPathException
dom4j-1.6.1/docs/xref/org/dom4j/DocumentType.html0000644000175000017500000002413110242117724021073 0ustar ebourgebourg DocumentType xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import java.util.List;
11  
12  /***
13   * <p>
14   * <code>DocumentType</code> defines an XML DOCTYPE declaration.
15   * </p>
16   * 
17   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
18   * @version $Revision: 1.10 $
19   */
20  public interface DocumentType extends Node {
21      /***
22       * This method is the equivalent to the {@link #getName}method. It is added
23       * for clarity.
24       * 
25       * @return the root element name for the document type.
26       */
27      String getElementName();
28  
29      /***
30       * This method is the equivalent to the {@link #setName}method. It is added
31       * for clarity.
32       * 
33       * @param elementName
34       *            DOCUMENT ME!
35       */
36      void setElementName(String elementName);
37  
38      String getPublicID();
39  
40      void setPublicID(String publicID);
41  
42      String getSystemID();
43  
44      void setSystemID(String systemID);
45  
46      /***
47       * Returns a list of internal DTD declaration objects, defined in the
48       * {@link org.dom4j.dtd}package
49       * 
50       * @return DOCUMENT ME!
51       */
52      List getInternalDeclarations();
53  
54      /***
55       * Sets the list of internal DTD declaration objects, defined in the
56       * {@link org.dom4j.dtd}package
57       * 
58       * @param declarations
59       *            DOCUMENT ME!
60       */
61      void setInternalDeclarations(List declarations);
62  
63      /***
64       * Returns a list of internal DTD declaration objects, defined in the
65       * {@link org.dom4j.dtd}package
66       * 
67       * @return DOCUMENT ME!
68       */
69      List getExternalDeclarations();
70  
71      /***
72       * Sets the list of internal DTD declaration objects, defined in the
73       * {@link org.dom4j.dtd}package
74       * 
75       * @param declarations
76       *            DOCUMENT ME!
77       */
78      void setExternalDeclarations(List declarations);
79  }
80  
81  /*
82   * Redistribution and use of this software and associated documentation
83   * ("Software"), with or without modification, are permitted provided that the
84   * following conditions are met:
85   * 
86   * 1. Redistributions of source code must retain copyright statements and
87   * notices. Redistributions must also contain a copy of this document.
88   * 
89   * 2. Redistributions in binary form must reproduce the above copyright notice,
90   * this list of conditions and the following disclaimer in the documentation
91   * and/or other materials provided with the distribution.
92   * 
93   * 3. The name "DOM4J" must not be used to endorse or promote products derived
94   * from this Software without prior written permission of MetaStuff, Ltd. For
95   * written permission, please contact dom4j-info@metastuff.com.
96   * 
97   * 4. Products derived from this Software may not be called "DOM4J" nor may
98   * "DOM4J" appear in their names without prior written permission of MetaStuff,
99   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
100  * 
101  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
102  * 
103  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
104  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
105  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
106  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
107  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
108  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
109  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
110  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
111  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
112  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
113  * POSSIBILITY OF SUCH DAMAGE.
114  * 
115  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
116  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/0000755000175000017500000000000012133227266016177 5ustar ebourgebourgdom4j-1.6.1/docs/xref/org/dom4j/io/JAXPHelper.html0000644000175000017500000002311510242117604020762 0ustar ebourgebourg JAXPHelper xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import javax.xml.parsers.DocumentBuilder;
11  import javax.xml.parsers.DocumentBuilderFactory;
12  import javax.xml.parsers.SAXParser;
13  import javax.xml.parsers.SAXParserFactory;
14  
15  import org.xml.sax.XMLReader;
16  
17  /***
18   * <code>JAXPHelper</code> contains some helper methods for working with JAXP.
19   * These methods are kept in a seperate class to avoid class loading issues,
20   * such that dom4j can work without JAXP on the CLASSPATH
21   * 
22   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
23   * @version $Revision: 1.7 $
24   */
25  class JAXPHelper {
26      protected JAXPHelper() {
27      }
28  
29      /***
30       * This method attempts to use JAXP to locate the SAX2 XMLReader
31       * implementation. This method uses reflection to avoid being dependent
32       * directly on the JAXP classes.
33       * 
34       * @param validating
35       *            DOCUMENT ME!
36       * @param namespaceAware
37       *            DOCUMENT ME!
38       * 
39       * @return DOCUMENT ME!
40       * 
41       * @throws Exception
42       *             DOCUMENT ME!
43       */
44      public static XMLReader createXMLReader(boolean validating,
45              boolean namespaceAware) throws Exception {
46          SAXParserFactory factory = SAXParserFactory.newInstance();
47          factory.setValidating(validating);
48          factory.setNamespaceAware(namespaceAware);
49  
50          SAXParser parser = factory.newSAXParser();
51  
52          return parser.getXMLReader();
53      }
54  
55      public static org.w3c.dom.Document createDocument(boolean validating,
56              boolean namespaceAware) throws Exception {
57          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
58          factory.setValidating(validating);
59          factory.setNamespaceAware(namespaceAware);
60  
61          DocumentBuilder builder = factory.newDocumentBuilder();
62  
63          return builder.newDocument();
64      }
65  }
66  
67  /*
68   * Redistribution and use of this software and associated documentation
69   * ("Software"), with or without modification, are permitted provided that the
70   * following conditions are met:
71   * 
72   * 1. Redistributions of source code must retain copyright statements and
73   * notices. Redistributions must also contain a copy of this document.
74   * 
75   * 2. Redistributions in binary form must reproduce the above copyright notice,
76   * this list of conditions and the following disclaimer in the documentation
77   * and/or other materials provided with the distribution.
78   * 
79   * 3. The name "DOM4J" must not be used to endorse or promote products derived
80   * from this Software without prior written permission of MetaStuff, Ltd. For
81   * written permission, please contact dom4j-info@metastuff.com.
82   * 
83   * 4. Products derived from this Software may not be called "DOM4J" nor may
84   * "DOM4J" appear in their names without prior written permission of MetaStuff,
85   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
86   * 
87   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
88   * 
89   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
90   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
91   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
92   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
93   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
94   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
95   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
96   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
97   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
98   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
99   * POSSIBILITY OF SUCH DAMAGE.
100  * 
101  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
102  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/XMLWriter.html0000644000175000017500000045171510242117544020733 0ustar ebourgebourg XMLWriter xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.io.BufferedWriter;
11  import java.io.IOException;
12  import java.io.OutputStream;
13  import java.io.OutputStreamWriter;
14  import java.io.UnsupportedEncodingException;
15  import java.io.Writer;
16  import java.util.HashMap;
17  import java.util.Iterator;
18  import java.util.List;
19  import java.util.Map;
20  import java.util.StringTokenizer;
21  
22  import org.dom4j.Attribute;
23  import org.dom4j.CDATA;
24  import org.dom4j.Comment;
25  import org.dom4j.Document;
26  import org.dom4j.DocumentType;
27  import org.dom4j.Element;
28  import org.dom4j.Entity;
29  import org.dom4j.Namespace;
30  import org.dom4j.Node;
31  import org.dom4j.ProcessingInstruction;
32  import org.dom4j.Text;
33  import org.dom4j.tree.NamespaceStack;
34  
35  import org.xml.sax.Attributes;
36  import org.xml.sax.InputSource;
37  import org.xml.sax.Locator;
38  import org.xml.sax.SAXException;
39  import org.xml.sax.SAXNotRecognizedException;
40  import org.xml.sax.SAXNotSupportedException;
41  import org.xml.sax.XMLReader;
42  import org.xml.sax.ext.LexicalHandler;
43  import org.xml.sax.helpers.XMLFilterImpl;
44  
45  /***
46   * <p>
47   * <code>XMLWriter</code> takes a DOM4J tree and formats it to a stream as
48   * XML. It can also take SAX events too so can be used by SAX clients as this
49   * object implements the {@link org.xml.sax.ContentHandler}and {@link
50   * LexicalHandler} interfaces. as well. This formatter performs typical document
51   * formatting. The XML declaration and processing instructions are always on
52   * their own lines. An {@link OutputFormat}object can be used to define how
53   * whitespace is handled when printing and allows various configuration options,
54   * such as to allow suppression of the XML declaration, the encoding declaration
55   * or whether empty documents are collapsed.
56   * </p>
57   * 
58   * <p>
59   * There are <code>write(...)</code> methods to print any of the standard
60   * DOM4J classes, including <code>Document</code> and <code>Element</code>,
61   * to either a <code>Writer</code> or an <code>OutputStream</code>.
62   * Warning: using your own <code>Writer</code> may cause the writer's
63   * preferred character encoding to be ignored. If you use encodings other than
64   * UTF8, we recommend using the method that takes an OutputStream instead.
65   * </p>
66   * 
67   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
68   * @author Joseph Bowbeer
69   * @version $Revision: 1.83.2.2 $
70   */
71  public class XMLWriter extends XMLFilterImpl implements LexicalHandler {
72      private static final String PAD_TEXT = " ";
73  
74      protected static final String[] LEXICAL_HANDLER_NAMES = {
75              "http://xml.org/sax/properties/lexical-handler",
76              "http://xml.org/sax/handlers/LexicalHandler"};
77  
78      protected static final OutputFormat DEFAULT_FORMAT = new OutputFormat();
79  
80      /*** Should entityRefs by resolved when writing ? */
81      private boolean resolveEntityRefs = true;
82  
83      /***
84       * Stores the last type of node written so algorithms can refer to the
85       * previous node type
86       */
87      protected int lastOutputNodeType;
88  
89      /***
90       * Stores if the last written element node was a closing tag or an opening
91       * tag.
92       */
93      private boolean lastElementClosed = false;
94  
95      /*** Stores the xml:space attribute value of preserve for whitespace flag */
96      protected boolean preserve = false;
97  
98      /*** The Writer used to output to */
99      protected Writer writer;
100 
101     /*** The Stack of namespaceStack written so far */
102     private NamespaceStack namespaceStack = new NamespaceStack();
103 
104     /*** The format used by this writer */
105     private OutputFormat format;
106 
107     /*** whether we should escape text */
108     private boolean escapeText = true;
109 
110     /***
111      * The initial number of indentations (so you can print a whole document
112      * indented, if you like)
113      */
114     private int indentLevel = 0;
115 
116     /*** buffer used when escaping strings */
117     private StringBuffer buffer = new StringBuffer();
118 
119     /***
120      * whether we have added characters before from the same chunk of characters
121      */
122     private boolean charsAdded = false;
123 
124     private char lastChar;
125 
126     /*** Whether a flush should occur after writing a document */
127     private boolean autoFlush;
128 
129     /*** Lexical handler we should delegate to */
130     private LexicalHandler lexicalHandler;
131 
132     /***
133      * Whether comments should appear inside DTD declarations - defaults to
134      * false
135      */
136     private boolean showCommentsInDTDs;
137 
138     /*** Is the writer curerntly inside a DTD definition? */
139     private boolean inDTD;
140 
141     /*** The namespaces used for the current element when consuming SAX events */
142     private Map namespacesMap;
143 
144     /***
145      * what is the maximum allowed character code such as 127 in US-ASCII (7
146      * bit) or 255 in ISO- (8 bit) or -1 to not escape any characters (other
147      * than the special XML characters like &lt; &gt; &amp;)
148      */
149     private int maximumAllowedCharacter;
150 
151     public XMLWriter(Writer writer) {
152         this(writer, DEFAULT_FORMAT);
153     }
154 
155     public XMLWriter(Writer writer, OutputFormat format) {
156         this.writer = writer;
157         this.format = format;
158         namespaceStack.push(Namespace.NO_NAMESPACE);
159     }
160 
161     public XMLWriter() {
162         this.format = DEFAULT_FORMAT;
163         this.writer = new BufferedWriter(new OutputStreamWriter(System.out));
164         this.autoFlush = true;
165         namespaceStack.push(Namespace.NO_NAMESPACE);
166     }
167 
168     public XMLWriter(OutputStream out) throws UnsupportedEncodingException {
169         this.format = DEFAULT_FORMAT;
170         this.writer = createWriter(out, format.getEncoding());
171         this.autoFlush = true;
172         namespaceStack.push(Namespace.NO_NAMESPACE);
173     }
174 
175     public XMLWriter(OutputStream out, OutputFormat format)
176             throws UnsupportedEncodingException {
177         this.format = format;
178         this.writer = createWriter(out, format.getEncoding());
179         this.autoFlush = true;
180         namespaceStack.push(Namespace.NO_NAMESPACE);
181     }
182 
183     public XMLWriter(OutputFormat format) throws UnsupportedEncodingException {
184         this.format = format;
185         this.writer = createWriter(System.out, format.getEncoding());
186         this.autoFlush = true;
187         namespaceStack.push(Namespace.NO_NAMESPACE);
188     }
189 
190     public void setWriter(Writer writer) {
191         this.writer = writer;
192         this.autoFlush = false;
193     }
194 
195     public void setOutputStream(OutputStream out)
196             throws UnsupportedEncodingException {
197         this.writer = createWriter(out, format.getEncoding());
198         this.autoFlush = true;
199     }
200 
201     /***
202      * DOCUMENT ME!
203      * 
204      * @return true if text thats output should be escaped. This is enabled by
205      *         default. It could be disabled if the output format is textual,
206      *         like in XSLT where we can have xml, html or text output.
207      */
208     public boolean isEscapeText() {
209         return escapeText;
210     }
211 
212     /***
213      * Sets whether text output should be escaped or not. This is enabled by
214      * default. It could be disabled if the output format is textual, like in
215      * XSLT where we can have xml, html or text output.
216      * 
217      * @param escapeText
218      *            DOCUMENT ME!
219      */
220     public void setEscapeText(boolean escapeText) {
221         this.escapeText = escapeText;
222     }
223 
224     /***
225      * Set the initial indentation level. This can be used to output a document
226      * (or, more likely, an element) starting at a given indent level, so it's
227      * not always flush against the left margin. Default: 0
228      * 
229      * @param indentLevel
230      *            the number of indents to start with
231      */
232     public void setIndentLevel(int indentLevel) {
233         this.indentLevel = indentLevel;
234     }
235 
236     /***
237      * Returns the maximum allowed character code that should be allowed
238      * unescaped which defaults to 127 in US-ASCII (7 bit) or 255 in ISO- (8
239      * bit).
240      * 
241      * @return DOCUMENT ME!
242      */
243     public int getMaximumAllowedCharacter() {
244         if (maximumAllowedCharacter == 0) {
245             maximumAllowedCharacter = defaultMaximumAllowedCharacter();
246         }
247 
248         return maximumAllowedCharacter;
249     }
250 
251     /***
252      * Sets the maximum allowed character code that should be allowed unescaped
253      * such as 127 in US-ASCII (7 bit) or 255 in ISO- (8 bit) or -1 to not
254      * escape any characters (other than the special XML characters like &lt;
255      * &gt; &amp;) If this is not explicitly set then it is defaulted from the
256      * encoding.
257      * 
258      * @param maximumAllowedCharacter
259      *            The maximumAllowedCharacter to set
260      */
261     public void setMaximumAllowedCharacter(int maximumAllowedCharacter) {
262         this.maximumAllowedCharacter = maximumAllowedCharacter;
263     }
264 
265     /***
266      * Flushes the underlying Writer
267      * 
268      * @throws IOException
269      *             DOCUMENT ME!
270      */
271     public void flush() throws IOException {
272         writer.flush();
273     }
274 
275     /***
276      * Closes the underlying Writer
277      * 
278      * @throws IOException
279      *             DOCUMENT ME!
280      */
281     public void close() throws IOException {
282         writer.close();
283     }
284 
285     /***
286      * Writes the new line text to the underlying Writer
287      * 
288      * @throws IOException
289      *             DOCUMENT ME!
290      */
291     public void println() throws IOException {
292         writer.write(format.getLineSeparator());
293     }
294 
295     /***
296      * Writes the given {@link Attribute}.
297      * 
298      * @param attribute
299      *            <code>Attribute</code> to output.
300      * 
301      * @throws IOException
302      *             DOCUMENT ME!
303      */
304     public void write(Attribute attribute) throws IOException {
305         writeAttribute(attribute);
306 
307         if (autoFlush) {
308             flush();
309         }
310     }
311 
312     /***
313      * <p>
314      * This will print the <code>Document</code> to the current Writer.
315      * </p>
316      * 
317      * <p>
318      * Warning: using your own Writer may cause the writer's preferred character
319      * encoding to be ignored. If you use encodings other than UTF8, we
320      * recommend using the method that takes an OutputStream instead.
321      * </p>
322      * 
323      * <p>
324      * Note: as with all Writers, you may need to flush() yours after this
325      * method returns.
326      * </p>
327      * 
328      * @param doc
329      *            <code>Document</code> to format.
330      * 
331      * @throws IOException
332      *             if there's any problem writing.
333      */
334     public void write(Document doc) throws IOException {
335         writeDeclaration();
336 
337         if (doc.getDocType() != null) {
338             indent();
339             writeDocType(doc.getDocType());
340         }
341 
342         for (int i = 0, size = doc.nodeCount(); i < size; i++) {
343             Node node = doc.node(i);
344             writeNode(node);
345         }
346 
347         writePrintln();
348 
349         if (autoFlush) {
350             flush();
351         }
352     }
353 
354     /***
355      * <p>
356      * Writes the <code>{@link Element}</code>, including its <code>{@link
357      * Attribute}</code>
358      * s, and its value, and all its content (child nodes) to the current
359      * Writer.
360      * </p>
361      * 
362      * @param element
363      *            <code>Element</code> to output.
364      * 
365      * @throws IOException
366      *             DOCUMENT ME!
367      */
368     public void write(Element element) throws IOException {
369         writeElement(element);
370 
371         if (autoFlush) {
372             flush();
373         }
374     }
375 
376     /***
377      * Writes the given {@link CDATA}.
378      * 
379      * @param cdata
380      *            <code>CDATA</code> to output.
381      * 
382      * @throws IOException
383      *             DOCUMENT ME!
384      */
385     public void write(CDATA cdata) throws IOException {
386         writeCDATA(cdata.getText());
387 
388         if (autoFlush) {
389             flush();
390         }
391     }
392 
393     /***
394      * Writes the given {@link Comment}.
395      * 
396      * @param comment
397      *            <code>Comment</code> to output.
398      * 
399      * @throws IOException
400      *             DOCUMENT ME!
401      */
402     public void write(Comment comment) throws IOException {
403         writeComment(comment.getText());
404 
405         if (autoFlush) {
406             flush();
407         }
408     }
409 
410     /***
411      * Writes the given {@link DocumentType}.
412      * 
413      * @param docType
414      *            <code>DocumentType</code> to output.
415      * 
416      * @throws IOException
417      *             DOCUMENT ME!
418      */
419     public void write(DocumentType docType) throws IOException {
420         writeDocType(docType);
421 
422         if (autoFlush) {
423             flush();
424         }
425     }
426 
427     /***
428      * Writes the given {@link Entity}.
429      * 
430      * @param entity
431      *            <code>Entity</code> to output.
432      * 
433      * @throws IOException
434      *             DOCUMENT ME!
435      */
436     public void write(Entity entity) throws IOException {
437         writeEntity(entity);
438 
439         if (autoFlush) {
440             flush();
441         }
442     }
443 
444     /***
445      * Writes the given {@link Namespace}.
446      * 
447      * @param namespace
448      *            <code>Namespace</code> to output.
449      * 
450      * @throws IOException
451      *             DOCUMENT ME!
452      */
453     public void write(Namespace namespace) throws IOException {
454         writeNamespace(namespace);
455 
456         if (autoFlush) {
457             flush();
458         }
459     }
460 
461     /***
462      * Writes the given {@link ProcessingInstruction}.
463      * 
464      * @param processingInstruction
465      *            <code>ProcessingInstruction</code> to output.
466      * 
467      * @throws IOException
468      *             DOCUMENT ME!
469      */
470     public void write(ProcessingInstruction processingInstruction)
471             throws IOException {
472         writeProcessingInstruction(processingInstruction);
473 
474         if (autoFlush) {
475             flush();
476         }
477     }
478 
479     /***
480      * <p>
481      * Print out a {@link String}, Perfoms the necessary entity escaping and
482      * whitespace stripping.
483      * </p>
484      * 
485      * @param text
486      *            is the text to output
487      * 
488      * @throws IOException
489      *             DOCUMENT ME!
490      */
491     public void write(String text) throws IOException {
492         writeString(text);
493 
494         if (autoFlush) {
495             flush();
496         }
497     }
498 
499     /***
500      * Writes the given {@link Text}.
501      * 
502      * @param text
503      *            <code>Text</code> to output.
504      * 
505      * @throws IOException
506      *             DOCUMENT ME!
507      */
508     public void write(Text text) throws IOException {
509         writeString(text.getText());
510 
511         if (autoFlush) {
512             flush();
513         }
514     }
515 
516     /***
517      * Writes the given {@link Node}.
518      * 
519      * @param node
520      *            <code>Node</code> to output.
521      * 
522      * @throws IOException
523      *             DOCUMENT ME!
524      */
525     public void write(Node node) throws IOException {
526         writeNode(node);
527 
528         if (autoFlush) {
529             flush();
530         }
531     }
532 
533     /***
534      * Writes the given object which should be a String, a Node or a List of
535      * Nodes.
536      * 
537      * @param object
538      *            is the object to output.
539      * 
540      * @throws IOException
541      *             DOCUMENT ME!
542      */
543     public void write(Object object) throws IOException {
544         if (object instanceof Node) {
545             write((Node) object);
546         } else if (object instanceof String) {
547             write((String) object);
548         } else if (object instanceof List) {
549             List list = (List) object;
550 
551             for (int i = 0, size = list.size(); i < size; i++) {
552                 write(list.get(i));
553             }
554         } else if (object != null) {
555             throw new IOException("Invalid object: " + object);
556         }
557     }
558 
559     /***
560      * <p>
561      * Writes the opening tag of an {@link Element}, including its {@link
562      * Attribute}s but without its content.
563      * </p>
564      * 
565      * @param element
566      *            <code>Element</code> to output.
567      * 
568      * @throws IOException
569      *             DOCUMENT ME!
570      */
571     public void writeOpen(Element element) throws IOException {
572         writer.write("<");
573         writer.write(element.getQualifiedName());
574         writeAttributes(element);
575         writer.write(">");
576     }
577 
578     /***
579      * <p>
580      * Writes the closing tag of an {@link Element}
581      * </p>
582      * 
583      * @param element
584      *            <code>Element</code> to output.
585      * 
586      * @throws IOException
587      *             DOCUMENT ME!
588      */
589     public void writeClose(Element element) throws IOException {
590         writeClose(element.getQualifiedName());
591     }
592 
593     // XMLFilterImpl methods
594     // -------------------------------------------------------------------------
595     public void parse(InputSource source) throws IOException, SAXException {
596         installLexicalHandler();
597         super.parse(source);
598     }
599 
600     public void setProperty(String name, Object value)
601             throws SAXNotRecognizedException, SAXNotSupportedException {
602         for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
603             if (LEXICAL_HANDLER_NAMES[i].equals(name)) {
604                 setLexicalHandler((LexicalHandler) value);
605 
606                 return;
607             }
608         }
609 
610         super.setProperty(name, value);
611     }
612 
613     public Object getProperty(String name) throws SAXNotRecognizedException,
614             SAXNotSupportedException {
615         for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
616             if (LEXICAL_HANDLER_NAMES[i].equals(name)) {
617                 return getLexicalHandler();
618             }
619         }
620 
621         return super.getProperty(name);
622     }
623 
624     public void setLexicalHandler(LexicalHandler handler) {
625         if (handler == null) {
626             throw new NullPointerException("Null lexical handler");
627         } else {
628             this.lexicalHandler = handler;
629         }
630     }
631 
632     public LexicalHandler getLexicalHandler() {
633         return lexicalHandler;
634     }
635 
636     // ContentHandler interface
637     // -------------------------------------------------------------------------
638     public void setDocumentLocator(Locator locator) {
639         super.setDocumentLocator(locator);
640     }
641 
642     public void startDocument() throws SAXException {
643         try {
644             writeDeclaration();
645             super.startDocument();
646         } catch (IOException e) {
647             handleException(e);
648         }
649     }
650 
651     public void endDocument() throws SAXException {
652         super.endDocument();
653 
654         if (autoFlush) {
655             try {
656                 flush();
657             } catch (IOException e) {
658             }
659         }
660     }
661 
662     public void startPrefixMapping(String prefix, String uri)
663             throws SAXException {
664         if (namespacesMap == null) {
665             namespacesMap = new HashMap();
666         }
667 
668         namespacesMap.put(prefix, uri);
669         super.startPrefixMapping(prefix, uri);
670     }
671 
672     public void endPrefixMapping(String prefix) throws SAXException {
673         super.endPrefixMapping(prefix);
674     }
675 
676     public void startElement(String namespaceURI, String localName,
677             String qName, Attributes attributes) throws SAXException {
678         try {
679             charsAdded = false;
680 
681             writePrintln();
682             indent();
683             writer.write("<");
684             writer.write(qName);
685             writeNamespaces();
686             writeAttributes(attributes);
687             writer.write(">");
688             ++indentLevel;
689             lastOutputNodeType = Node.ELEMENT_NODE;
690             lastElementClosed = false;
691 
692             super.startElement(namespaceURI, localName, qName, attributes);
693         } catch (IOException e) {
694             handleException(e);
695         }
696     }
697 
698     public void endElement(String namespaceURI, String localName, String qName)
699             throws SAXException {
700         try {
701             charsAdded = false;
702             --indentLevel;
703 
704             if (lastElementClosed) {
705                 writePrintln();
706                 indent();
707             }
708 
709             // XXXX: need to determine this using a stack and checking for
710             // content / children
711             boolean hadContent = true;
712 
713             if (hadContent) {
714                 writeClose(qName);
715             } else {
716                 writeEmptyElementClose(qName);
717             }
718 
719             lastOutputNodeType = Node.ELEMENT_NODE;
720             lastElementClosed = true;
721 
722             super.endElement(namespaceURI, localName, qName);
723         } catch (IOException e) {
724             handleException(e);
725         }
726     }
727 
728     public void characters(char[] ch, int start, int length)
729             throws SAXException {
730         if ((ch == null) || (ch.length == 0) || (length <= 0)) {
731             return;
732         }
733 
734         try {
735             /*
736              * we can't use the writeString method here because it's possible we
737              * don't receive all characters at once and calling writeString
738              * would cause unwanted spaces to be added in between these chunks
739              * of character arrays.
740              */
741             String string = String.valueOf(ch, start, length);
742 
743             if (escapeText) {
744                 string = escapeElementEntities(string);
745             }
746 
747             if (format.isTrimText()) {
748                 if ((lastOutputNodeType == Node.TEXT_NODE) && !charsAdded) {
749                     writer.write(' ');
750                 } else if (charsAdded && Character.isWhitespace(lastChar)) {
751                     writer.write(' ');
752                 } else if (lastOutputNodeType == Node.ELEMENT_NODE
753                         && format.isPadText() && lastElementClosed
754                         && Character.isWhitespace(ch[0])) {
755                     writer.write(PAD_TEXT);
756                 }
757 
758                 String delim = "";
759                 StringTokenizer tokens = new StringTokenizer(string);
760 
761                 while (tokens.hasMoreTokens()) {
762                     writer.write(delim);
763                     writer.write(tokens.nextToken());
764                     delim = " ";
765                 }
766             } else {
767                 writer.write(string);
768             }
769 
770             charsAdded = true;
771             lastChar = ch[(start + length) - 1];
772             lastOutputNodeType = Node.TEXT_NODE;
773 
774             super.characters(ch, start, length);
775         } catch (IOException e) {
776             handleException(e);
777         }
778     }
779 
780     public void ignorableWhitespace(char[] ch, int start, int length)
781             throws SAXException {
782         super.ignorableWhitespace(ch, start, length);
783     }
784 
785     public void processingInstruction(String target, String data)
786             throws SAXException {
787         try {
788             indent();
789             writer.write("<?");
790             writer.write(target);
791             writer.write(" ");
792             writer.write(data);
793             writer.write("?>");
794             writePrintln();
795             lastOutputNodeType = Node.PROCESSING_INSTRUCTION_NODE;
796 
797             super.processingInstruction(target, data);
798         } catch (IOException e) {
799             handleException(e);
800         }
801     }
802 
803     // DTDHandler interface
804     // -------------------------------------------------------------------------
805     public void notationDecl(String name, String publicID, String systemID)
806             throws SAXException {
807         super.notationDecl(name, publicID, systemID);
808     }
809 
810     public void unparsedEntityDecl(String name, String publicID,
811             String systemID, String notationName) throws SAXException {
812         super.unparsedEntityDecl(name, publicID, systemID, notationName);
813     }
814 
815     // LexicalHandler interface
816     // -------------------------------------------------------------------------
817     public void startDTD(String name, String publicID, String systemID)
818             throws SAXException {
819         inDTD = true;
820 
821         try {
822             writeDocType(name, publicID, systemID);
823         } catch (IOException e) {
824             handleException(e);
825         }
826 
827         if (lexicalHandler != null) {
828             lexicalHandler.startDTD(name, publicID, systemID);
829         }
830     }
831 
832     public void endDTD() throws SAXException {
833         inDTD = false;
834 
835         if (lexicalHandler != null) {
836             lexicalHandler.endDTD();
837         }
838     }
839 
840     public void startCDATA() throws SAXException {
841         try {
842             writer.write("<![CDATA[");
843         } catch (IOException e) {
844             handleException(e);
845         }
846 
847         if (lexicalHandler != null) {
848             lexicalHandler.startCDATA();
849         }
850     }
851 
852     public void endCDATA() throws SAXException {
853         try {
854             writer.write("]]>");
855         } catch (IOException e) {
856             handleException(e);
857         }
858 
859         if (lexicalHandler != null) {
860             lexicalHandler.endCDATA();
861         }
862     }
863 
864     public void startEntity(String name) throws SAXException {
865         try {
866             writeEntityRef(name);
867         } catch (IOException e) {
868             handleException(e);
869         }
870 
871         if (lexicalHandler != null) {
872             lexicalHandler.startEntity(name);
873         }
874     }
875 
876     public void endEntity(String name) throws SAXException {
877         if (lexicalHandler != null) {
878             lexicalHandler.endEntity(name);
879         }
880     }
881 
882     public void comment(char[] ch, int start, int length) throws SAXException {
883         if (showCommentsInDTDs || !inDTD) {
884             try {
885                 charsAdded = false;
886                 writeComment(new String(ch, start, length));
887             } catch (IOException e) {
888                 handleException(e);
889             }
890         }
891 
892         if (lexicalHandler != null) {
893             lexicalHandler.comment(ch, start, length);
894         }
895     }
896 
897     // Implementation methods
898     // -------------------------------------------------------------------------
899     protected void writeElement(Element element) throws IOException {
900         int size = element.nodeCount();
901         String qualifiedName = element.getQualifiedName();
902 
903         writePrintln();
904         indent();
905 
906         writer.write("<");
907         writer.write(qualifiedName);
908 
909         int previouslyDeclaredNamespaces = namespaceStack.size();
910         Namespace ns = element.getNamespace();
911 
912         if (isNamespaceDeclaration(ns)) {
913             namespaceStack.push(ns);
914             writeNamespace(ns);
915         }
916 
917         // Print out additional namespace declarations
918         boolean textOnly = true;
919 
920         for (int i = 0; i < size; i++) {
921             Node node = element.node(i);
922 
923             if (node instanceof Namespace) {
924                 Namespace additional = (Namespace) node;
925 
926                 if (isNamespaceDeclaration(additional)) {
927                     namespaceStack.push(additional);
928                     writeNamespace(additional);
929                 }
930             } else if (node instanceof Element) {
931                 textOnly = false;
932             } else if (node instanceof Comment) {
933                 textOnly = false;
934             }
935         }
936 
937         writeAttributes(element);
938 
939         lastOutputNodeType = Node.ELEMENT_NODE;
940 
941         if (size <= 0) {
942             writeEmptyElementClose(qualifiedName);
943         } else {
944             writer.write(">");
945 
946             if (textOnly) {
947                 // we have at least one text node so lets assume
948                 // that its non-empty
949                 writeElementContent(element);
950             } else {
951                 // we know it's not null or empty from above
952                 ++indentLevel;
953 
954                 writeElementContent(element);
955 
956                 --indentLevel;
957 
958                 writePrintln();
959                 indent();
960             }
961 
962             writer.write("</");
963             writer.write(qualifiedName);
964             writer.write(">");
965         }
966 
967         // remove declared namespaceStack from stack
968         while (namespaceStack.size() > previouslyDeclaredNamespaces) {
969             namespaceStack.pop();
970         }
971 
972         lastOutputNodeType = Node.ELEMENT_NODE;
973     }
974 
975     /***
976      * Determines if element is a special case of XML elements where it contains
977      * an xml:space attribute of "preserve". If it does, then retain whitespace.
978      * 
979      * @param element
980      *            DOCUMENT ME!
981      * 
982      * @return DOCUMENT ME!
983      */
984     protected final boolean isElementSpacePreserved(Element element) {
985         final Attribute attr = (Attribute) element.attribute("space");
986         boolean preserveFound = preserve; // default to global state
987 
988         if (attr != null) {
989             if ("xml".equals(attr.getNamespacePrefix())
990                     && "preserve".equals(attr.getText())) {
991                 preserveFound = true;
992             } else {
993                 preserveFound = false;
994             }
995         }
996 
997         return preserveFound;
998     }
999 
1000     /***
1001      * Outputs the content of the given element. If whitespace trimming is
1002      * enabled then all adjacent text nodes are appended together before the
1003      * whitespace trimming occurs to avoid problems with multiple text nodes
1004      * being created due to text content that spans parser buffers in a SAX
1005      * parser.
1006      * 
1007      * @param element
1008      *            DOCUMENT ME!
1009      * 
1010      * @throws IOException
1011      *             DOCUMENT ME!
1012      */
1013     protected void writeElementContent(Element element) throws IOException {
1014         boolean trim = format.isTrimText();
1015         boolean oldPreserve = preserve;
1016 
1017         if (trim) { // verify we have to before more expensive test
1018             preserve = isElementSpacePreserved(element);
1019             trim = !preserve;
1020         }
1021 
1022         if (trim) {
1023             // concatenate adjacent text nodes together
1024             // so that whitespace trimming works properly
1025             Text lastTextNode = null;
1026             StringBuffer buff = null;
1027             boolean textOnly = true;
1028 
1029             for (int i = 0, size = element.nodeCount(); i < size; i++) {
1030                 Node node = element.node(i);
1031 
1032                 if (node instanceof Text) {
1033                     if (lastTextNode == null) {
1034                         lastTextNode = (Text) node;
1035                     } else {
1036                         if (buff == null) {
1037                             buff = new StringBuffer(lastTextNode.getText());
1038                         }
1039 
1040                         buff.append(((Text) node).getText());
1041                     }
1042                 } else {
1043                     if (!textOnly && format.isPadText()) {
1044                         // only add the PAD_TEXT if the text itself starts with
1045                         // whitespace
1046                         char firstChar = 'a';
1047                         if (buff != null) {
1048                             firstChar = buff.charAt(0);
1049                         } else if (lastTextNode != null) {
1050                             firstChar = lastTextNode.getText().charAt(0);
1051                         }
1052 
1053                         if (Character.isWhitespace(firstChar)) {
1054                             writer.write(PAD_TEXT);
1055                         }
1056                     }
1057 
1058                     if (lastTextNode != null) {
1059                         if (buff != null) {
1060                             writeString(buff.toString());
1061                             buff = null;
1062                         } else {
1063                             writeString(lastTextNode.getText());
1064                         }
1065 
1066                         if (format.isPadText()) {
1067                             // only add the PAD_TEXT if the text itself ends
1068                             // with whitespace
1069                             char lastTextChar = 'a';
1070                             if (buff != null) {
1071                                 lastTextChar = buff.charAt(buff.length() - 1);
1072                             } else if (lastTextNode != null) {
1073                                 String txt = lastTextNode.getText();
1074                                 lastTextChar = txt.charAt(txt.length() - 1);
1075                             }
1076 
1077                             if (Character.isWhitespace(lastTextChar)) {
1078                                 writer.write(PAD_TEXT);
1079                             }
1080                         }
1081 
1082                         lastTextNode = null;
1083                     }
1084 
1085                     textOnly = false;
1086                     writeNode(node);
1087                 }
1088             }
1089 
1090             if (lastTextNode != null) {
1091                 if (!textOnly && format.isPadText()) {
1092                     // only add the PAD_TEXT if the text itself starts with
1093                     // whitespace
1094                     char firstChar = 'a';
1095                     if (buff != null) {
1096                         firstChar = buff.charAt(0);
1097                     } else {
1098                         firstChar = lastTextNode.getText().charAt(0);
1099                     }
1100 
1101                     if (Character.isWhitespace(firstChar)) {
1102                         writer.write(PAD_TEXT);
1103                     }
1104                 }
1105 
1106                 if (buff != null) {
1107                     writeString(buff.toString());
1108                     buff = null;
1109                 } else {
1110                     writeString(lastTextNode.getText());
1111                 }
1112 
1113                 lastTextNode = null;
1114             }
1115         } else {
1116             Node lastTextNode = null;
1117 
1118             for (int i = 0, size = element.nodeCount(); i < size; i++) {
1119                 Node node = element.node(i);
1120 
1121                 if (node instanceof Text) {
1122                     writeNode(node);
1123                     lastTextNode = node;
1124                 } else {
1125                     if ((lastTextNode != null) && format.isPadText()) {
1126                         // only add the PAD_TEXT if the text itself ends with
1127                         // whitespace
1128                         String txt = lastTextNode.getText();
1129                         char lastTextChar = txt.charAt(txt.length() - 1);
1130 
1131                         if (Character.isWhitespace(lastTextChar)) {
1132                             writer.write(PAD_TEXT);
1133                         }
1134                     }
1135 
1136                     writeNode(node);
1137 
1138                     // if ((lastTextNode != null) && format.isPadText()) {
1139                     // writer.write(PAD_TEXT);
1140                     // }
1141 
1142                     lastTextNode = null;
1143                 }
1144             }
1145         }
1146 
1147         preserve = oldPreserve;
1148     }
1149 
1150     protected void writeCDATA(String text) throws IOException {
1151         writer.write("<![CDATA[");
1152 
1153         if (text != null) {
1154             writer.write(text);
1155         }
1156 
1157         writer.write("]]>");
1158 
1159         lastOutputNodeType = Node.CDATA_SECTION_NODE;
1160     }
1161 
1162     protected void writeDocType(DocumentType docType) throws IOException {
1163         if (docType != null) {
1164             docType.write(writer);
1165             writePrintln();
1166         }
1167     }
1168 
1169     protected void writeNamespace(Namespace namespace) throws IOException {
1170         if (namespace != null) {
1171             writeNamespace(namespace.getPrefix(), namespace.getURI());
1172         }
1173     }
1174 
1175     /***
1176      * Writes the SAX namepsaces
1177      * 
1178      * @throws IOException
1179      *             DOCUMENT ME!
1180      */
1181     protected void writeNamespaces() throws IOException {
1182         if (namespacesMap != null) {
1183             for (Iterator iter = namespacesMap.entrySet().iterator(); iter
1184                     .hasNext();) {
1185                 Map.Entry entry = (Map.Entry) iter.next();
1186                 String prefix = (String) entry.getKey();
1187                 String uri = (String) entry.getValue();
1188                 writeNamespace(prefix, uri);
1189             }
1190 
1191             namespacesMap = null;
1192         }
1193     }
1194 
1195     /***
1196      * Writes the SAX namepsaces
1197      * 
1198      * @param prefix
1199      *            the prefix
1200      * @param uri
1201      *            the namespace uri
1202      * 
1203      * @throws IOException
1204      */
1205     protected void writeNamespace(String prefix, String uri) 
1206             throws IOException {
1207         if ((prefix != null) && (prefix.length() > 0)) {
1208             writer.write(" xmlns:");
1209             writer.write(prefix);
1210             writer.write("=\"");
1211         } else {
1212             writer.write(" xmlns=\"");
1213         }
1214 
1215         writer.write(uri);
1216         writer.write("\"");
1217     }
1218 
1219     protected void writeProcessingInstruction(ProcessingInstruction pi)
1220             throws IOException {
1221         // indent();
1222         writer.write("<?");
1223         writer.write(pi.getName());
1224         writer.write(" ");
1225         writer.write(pi.getText());
1226         writer.write("?>");
1227         writePrintln();
1228 
1229         lastOutputNodeType = Node.PROCESSING_INSTRUCTION_NODE;
1230     }
1231 
1232     protected void writeString(String text) throws IOException {
1233         if ((text != null) && (text.length() > 0)) {
1234             if (escapeText) {
1235                 text = escapeElementEntities(text);
1236             }
1237 
1238             // if (format.isPadText()) {
1239             // if (lastOutputNodeType == Node.ELEMENT_NODE) {
1240             // writer.write(PAD_TEXT);
1241             // }
1242             // }
1243             if (format.isTrimText()) {
1244                 boolean first = true;
1245                 StringTokenizer tokenizer = new StringTokenizer(text);
1246 
1247                 while (tokenizer.hasMoreTokens()) {
1248                     String token = tokenizer.nextToken();
1249 
1250                     if (first) {
1251                         first = false;
1252 
1253                         if (lastOutputNodeType == Node.TEXT_NODE) {
1254                             writer.write(" ");
1255                         }
1256                     } else {
1257                         writer.write(" ");
1258                     }
1259 
1260                     writer.write(token);
1261                     lastOutputNodeType = Node.TEXT_NODE;
1262                     lastChar = token.charAt(token.length() - 1);
1263                 }
1264             } else {
1265                 lastOutputNodeType = Node.TEXT_NODE;
1266                 writer.write(text);
1267                 lastChar = text.charAt(text.length() - 1);
1268             }
1269         }
1270     }
1271 
1272     /***
1273      * This method is used to write out Nodes that contain text and still allow
1274      * for xml:space to be handled properly.
1275      * 
1276      * @param node
1277      *            DOCUMENT ME!
1278      * 
1279      * @throws IOException
1280      *             DOCUMENT ME!
1281      */
1282     protected void writeNodeText(Node node) throws IOException {
1283         String text = node.getText();
1284 
1285         if ((text != null) && (text.length() > 0)) {
1286             if (escapeText) {
1287                 text = escapeElementEntities(text);
1288             }
1289 
1290             lastOutputNodeType = Node.TEXT_NODE;
1291             writer.write(text);
1292             lastChar = text.charAt(text.length() - 1);
1293         }
1294     }
1295 
1296     protected void writeNode(Node node) throws IOException {
1297         int nodeType = node.getNodeType();
1298 
1299         switch (nodeType) {
1300             case Node.ELEMENT_NODE:
1301                 writeElement((Element) node);
1302 
1303                 break;
1304 
1305             case Node.ATTRIBUTE_NODE:
1306                 writeAttribute((Attribute) node);
1307 
1308                 break;
1309 
1310             case Node.TEXT_NODE:
1311                 writeNodeText(node);
1312 
1313                 // write((Text) node);
1314                 break;
1315 
1316             case Node.CDATA_SECTION_NODE:
1317                 writeCDATA(node.getText());
1318 
1319                 break;
1320 
1321             case Node.ENTITY_REFERENCE_NODE:
1322                 writeEntity((Entity) node);
1323 
1324                 break;
1325 
1326             case Node.PROCESSING_INSTRUCTION_NODE:
1327                 writeProcessingInstruction((ProcessingInstruction) node);
1328 
1329                 break;
1330 
1331             case Node.COMMENT_NODE:
1332                 writeComment(node.getText());
1333 
1334                 break;
1335 
1336             case Node.DOCUMENT_NODE:
1337                 write((Document) node);
1338 
1339                 break;
1340 
1341             case Node.DOCUMENT_TYPE_NODE:
1342                 writeDocType((DocumentType) node);
1343 
1344                 break;
1345 
1346             case Node.NAMESPACE_NODE:
1347 
1348                 // Will be output with attributes
1349                 // write((Namespace) node);
1350                 break;
1351 
1352             default:
1353                 throw new IOException("Invalid node type: " + node);
1354         }
1355     }
1356 
1357     protected void installLexicalHandler() {
1358         XMLReader parent = getParent();
1359 
1360         if (parent == null) {
1361             throw new NullPointerException("No parent for filter");
1362         }
1363 
1364         // try to register for lexical events
1365         for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
1366             try {
1367                 parent.setProperty(LEXICAL_HANDLER_NAMES[i], this);
1368 
1369                 break;
1370             } catch (SAXNotRecognizedException ex) {
1371                 // ignore
1372             } catch (SAXNotSupportedException ex) {
1373                 // ignore
1374             }
1375         }
1376     }
1377 
1378     protected void writeDocType(String name, String publicID, String systemID)
1379             throws IOException {
1380         boolean hasPublic = false;
1381 
1382         writer.write("<!DOCTYPE ");
1383         writer.write(name);
1384 
1385         if ((publicID != null) && (!publicID.equals(""))) {
1386             writer.write(" PUBLIC \"");
1387             writer.write(publicID);
1388             writer.write("\"");
1389             hasPublic = true;
1390         }
1391 
1392         if ((systemID != null) && (!systemID.equals(""))) {
1393             if (!hasPublic) {
1394                 writer.write(" SYSTEM");
1395             }
1396 
1397             writer.write(" \"");
1398             writer.write(systemID);
1399             writer.write("\"");
1400         }
1401 
1402         writer.write(">");
1403         writePrintln();
1404     }
1405 
1406     protected void writeEntity(Entity entity) throws IOException {
1407         if (!resolveEntityRefs()) {
1408             writeEntityRef(entity.getName());
1409         } else {
1410             writer.write(entity.getText());
1411         }
1412     }
1413 
1414     protected void writeEntityRef(String name) throws IOException {
1415         writer.write("&");
1416         writer.write(name);
1417         writer.write(";");
1418 
1419         lastOutputNodeType = Node.ENTITY_REFERENCE_NODE;
1420     }
1421 
1422     protected void writeComment(String text) throws IOException {
1423         if (format.isNewlines()) {
1424             println();
1425             indent();
1426         }
1427 
1428         writer.write("<!--");
1429         writer.write(text);
1430         writer.write("-->");
1431 
1432         lastOutputNodeType = Node.COMMENT_NODE;
1433     }
1434 
1435     /***
1436      * Writes the attributes of the given element
1437      * 
1438      * @param element
1439      *            DOCUMENT ME!
1440      * 
1441      * @throws IOException
1442      *             DOCUMENT ME!
1443      */
1444     protected void writeAttributes(Element element) throws IOException {
1445         // I do not yet handle the case where the same prefix maps to
1446         // two different URIs. For attributes on the same element
1447         // this is illegal; but as yet we don't throw an exception
1448         // if someone tries to do this
1449         for (int i = 0, size = element.attributeCount(); i < size; i++) {
1450             Attribute attribute = element.attribute(i);
1451             Namespace ns = attribute.getNamespace();
1452 
1453             if ((ns != null) && (ns != Namespace.NO_NAMESPACE)
1454                     && (ns != Namespace.XML_NAMESPACE)) {
1455                 String prefix = ns.getPrefix();
1456                 String uri = namespaceStack.getURI(prefix);
1457 
1458                 if (!ns.getURI().equals(uri)) {
1459                     writeNamespace(ns);
1460                     namespaceStack.push(ns);
1461                 }
1462             }
1463 
1464             // If the attribute is a namespace declaration, check if we have
1465             // already written that declaration elsewhere (if that's the case,
1466             // it must be in the namespace stack
1467             String attName = attribute.getName();
1468 
1469             if (attName.startsWith("xmlns:")) {
1470                 String prefix = attName.substring(6);
1471 
1472                 if (namespaceStack.getNamespaceForPrefix(prefix) == null) {
1473                     String uri = attribute.getValue();
1474                     namespaceStack.push(prefix, uri);
1475                     writeNamespace(prefix, uri);
1476                 }
1477             } else if (attName.equals("xmlns")) {
1478                 if (namespaceStack.getDefaultNamespace() == null) {
1479                     String uri = attribute.getValue();
1480                     namespaceStack.push(null, uri);
1481                     writeNamespace(null, uri);
1482                 }
1483             } else {
1484                 char quote = format.getAttributeQuoteCharacter();
1485                 writer.write(" ");
1486                 writer.write(attribute.getQualifiedName());
1487                 writer.write("=");
1488                 writer.write(quote);
1489                 writeEscapeAttributeEntities(attribute.getValue());
1490                 writer.write(quote);
1491             }
1492         }
1493     }
1494 
1495     protected void writeAttribute(Attribute attribute) throws IOException {
1496         writer.write(" ");
1497         writer.write(attribute.getQualifiedName());
1498         writer.write("=");
1499 
1500         char quote = format.getAttributeQuoteCharacter();
1501         writer.write(quote);
1502 
1503         writeEscapeAttributeEntities(attribute.getValue());
1504 
1505         writer.write(quote);
1506         lastOutputNodeType = Node.ATTRIBUTE_NODE;
1507     }
1508 
1509     protected void writeAttributes(Attributes attributes) throws IOException {
1510         for (int i = 0, size = attributes.getLength(); i < size; i++) {
1511             writeAttribute(attributes, i);
1512         }
1513     }
1514 
1515     protected void writeAttribute(Attributes attributes, int index)
1516             throws IOException {
1517         char quote = format.getAttributeQuoteCharacter();
1518         writer.write(" ");
1519         writer.write(attributes.getQName(index));
1520         writer.write("=");
1521         writer.write(quote);
1522         writeEscapeAttributeEntities(attributes.getValue(index));
1523         writer.write(quote);
1524     }
1525 
1526     protected void indent() throws IOException {
1527         String indent = format.getIndent();
1528 
1529         if ((indent != null) && (indent.length() > 0)) {
1530             for (int i = 0; i < indentLevel; i++) {
1531                 writer.write(indent);
1532             }
1533         }
1534     }
1535 
1536     /***
1537      * <p>
1538      * This will print a new line only if the newlines flag was set to true
1539      * </p>
1540      * 
1541      * @throws IOException
1542      *             DOCUMENT ME!
1543      */
1544     protected void writePrintln() throws IOException {
1545         if (format.isNewlines()) {
1546             String seperator = format.getLineSeparator();
1547             if (lastChar != seperator.charAt(seperator.length() - 1)) {
1548                 writer.write(format.getLineSeparator());
1549             }
1550         }
1551     }
1552 
1553     /***
1554      * Get an OutputStreamWriter, use preferred encoding.
1555      * 
1556      * @param outStream
1557      *            DOCUMENT ME!
1558      * @param encoding
1559      *            DOCUMENT ME!
1560      * 
1561      * @return DOCUMENT ME!
1562      * 
1563      * @throws UnsupportedEncodingException
1564      *             DOCUMENT ME!
1565      */
1566     protected Writer createWriter(OutputStream outStream, String encoding)
1567             throws UnsupportedEncodingException {
1568         return new BufferedWriter(new OutputStreamWriter(outStream, encoding));
1569     }
1570 
1571     /***
1572      * <p>
1573      * This will write the declaration to the given Writer. Assumes XML version
1574      * 1.0 since we don't directly know.
1575      * </p>
1576      * 
1577      * @throws IOException
1578      *             DOCUMENT ME!
1579      */
1580     protected void writeDeclaration() throws IOException {
1581         String encoding = format.getEncoding();
1582 
1583         // Only print of declaration is not suppressed
1584         if (!format.isSuppressDeclaration()) {
1585             // Assume 1.0 version
1586             if (encoding.equals("UTF8")) {
1587                 writer.write("<?xml version=\"1.0\"");
1588 
1589                 if (!format.isOmitEncoding()) {
1590                     writer.write(" encoding=\"UTF-8\"");
1591                 }
1592 
1593                 writer.write("?>");
1594             } else {
1595                 writer.write("<?xml version=\"1.0\"");
1596 
1597                 if (!format.isOmitEncoding()) {
1598                     writer.write(" encoding=\"" + encoding + "\"");
1599                 }
1600 
1601                 writer.write("?>");
1602             }
1603 
1604             if (format.isNewLineAfterDeclaration()) {
1605                 println();
1606             }
1607         }
1608     }
1609 
1610     protected void writeClose(String qualifiedName) throws IOException {
1611         writer.write("</");
1612         writer.write(qualifiedName);
1613         writer.write(">");
1614     }
1615 
1616     protected void writeEmptyElementClose(String qualifiedName)
1617             throws IOException {
1618         // Simply close up
1619         if (!format.isExpandEmptyElements()) {
1620             writer.write("/>");
1621         } else {
1622             writer.write("></");
1623             writer.write(qualifiedName);
1624             writer.write(">");
1625         }
1626     }
1627 
1628     protected boolean isExpandEmptyElements() {
1629         return format.isExpandEmptyElements();
1630     }
1631 
1632     /***
1633      * This will take the pre-defined entities in XML 1.0 and convert their
1634      * character representation to the appropriate entity reference, suitable
1635      * for XML attributes.
1636      * 
1637      * @param text
1638      *            DOCUMENT ME!
1639      * 
1640      * @return DOCUMENT ME!
1641      */
1642     protected String escapeElementEntities(String text) {
1643         char[] block = null;
1644         int i;
1645         int last = 0;
1646         int size = text.length();
1647 
1648         for (i = 0; i < size; i++) {
1649             String entity = null;
1650             char c = text.charAt(i);
1651 
1652             switch (c) {
1653                 case '<':
1654                     entity = "&lt;";
1655 
1656                     break;
1657 
1658                 case '>':
1659                     entity = "&gt;";
1660 
1661                     break;
1662 
1663                 case '&':
1664                     entity = "&amp;";
1665 
1666                     break;
1667 
1668                 case '\t':
1669                 case '\n':
1670                 case '\r':
1671 
1672                     // don't encode standard whitespace characters
1673                     if (preserve) {
1674                         entity = String.valueOf(c);
1675                     }
1676 
1677                     break;
1678 
1679                 default:
1680 
1681                     if ((c < 32) || shouldEncodeChar(c)) {
1682                         entity = "&#" + (int) c + ";";
1683                     }
1684 
1685                     break;
1686             }
1687 
1688             if (entity != null) {
1689                 if (block == null) {
1690                     block = text.toCharArray();
1691                 }
1692 
1693                 buffer.append(block, last, i - last);
1694                 buffer.append(entity);
1695                 last = i + 1;
1696             }
1697         }
1698 
1699         if (last == 0) {
1700             return text;
1701         }
1702 
1703         if (last < size) {
1704             if (block == null) {
1705                 block = text.toCharArray();
1706             }
1707 
1708             buffer.append(block, last, i - last);
1709         }
1710 
1711         String answer = buffer.toString();
1712         buffer.setLength(0);
1713 
1714         return answer;
1715     }
1716 
1717     protected void writeEscapeAttributeEntities(String txt) throws IOException {
1718         if (txt != null) {
1719             String escapedText = escapeAttributeEntities(txt);
1720             writer.write(escapedText);
1721         }
1722     }
1723 
1724     /***
1725      * This will take the pre-defined entities in XML 1.0 and convert their
1726      * character representation to the appropriate entity reference, suitable
1727      * for XML attributes.
1728      * 
1729      * @param text
1730      *            DOCUMENT ME!
1731      * 
1732      * @return DOCUMENT ME!
1733      */
1734     protected String escapeAttributeEntities(String text) {
1735         char quote = format.getAttributeQuoteCharacter();
1736 
1737         char[] block = null;
1738         int i;
1739         int last = 0;
1740         int size = text.length();
1741 
1742         for (i = 0; i < size; i++) {
1743             String entity = null;
1744             char c = text.charAt(i);
1745 
1746             switch (c) {
1747                 case '<':
1748                     entity = "&lt;";
1749 
1750                     break;
1751 
1752                 case '>':
1753                     entity = "&gt;";
1754 
1755                     break;
1756 
1757                 case '\'':
1758 
1759                     if (quote == '\'') {
1760                         entity = "&apos;";
1761                     }
1762 
1763                     break;
1764 
1765                 case '\"':
1766 
1767                     if (quote == '\"') {
1768                         entity = "&quot;";
1769                     }
1770 
1771                     break;
1772 
1773                 case '&':
1774                     entity = "&amp;";
1775 
1776                     break;
1777 
1778                 case '\t':
1779                 case '\n':
1780                 case '\r':
1781 
1782                     // don't encode standard whitespace characters
1783                     break;
1784 
1785                 default:
1786 
1787                     if ((c < 32) || shouldEncodeChar(c)) {
1788                         entity = "&#" + (int) c + ";";
1789                     }
1790 
1791                     break;
1792             }
1793 
1794             if (entity != null) {
1795                 if (block == null) {
1796                     block = text.toCharArray();
1797                 }
1798 
1799                 buffer.append(block, last, i - last);
1800                 buffer.append(entity);
1801                 last = i + 1;
1802             }
1803         }
1804 
1805         if (last == 0) {
1806             return text;
1807         }
1808 
1809         if (last < size) {
1810             if (block == null) {
1811                 block = text.toCharArray();
1812             }
1813 
1814             buffer.append(block, last, i - last);
1815         }
1816 
1817         String answer = buffer.toString();
1818         buffer.setLength(0);
1819 
1820         return answer;
1821     }
1822 
1823     /***
1824      * Should the given character be escaped. This depends on the encoding of
1825      * the document.
1826      * 
1827      * @param c
1828      *            DOCUMENT ME!
1829      * 
1830      * @return boolean
1831      */
1832     protected boolean shouldEncodeChar(char c) {
1833         int max = getMaximumAllowedCharacter();
1834 
1835         return (max > 0) && (c > max);
1836     }
1837 
1838     /***
1839      * Returns the maximum allowed character code that should be allowed
1840      * unescaped which defaults to 127 in US-ASCII (7 bit) or 255 in ISO- (8
1841      * bit).
1842      * 
1843      * @return DOCUMENT ME!
1844      */
1845     protected int defaultMaximumAllowedCharacter() {
1846         String encoding = format.getEncoding();
1847 
1848         if (encoding != null) {
1849             if (encoding.equals("US-ASCII")) {
1850                 return 127;
1851             }
1852         }
1853 
1854         // no encoding for things like ISO-*, UTF-8 or UTF-16
1855         return -1;
1856     }
1857 
1858     protected boolean isNamespaceDeclaration(Namespace ns) {
1859         if ((ns != null) && (ns != Namespace.XML_NAMESPACE)) {
1860             String uri = ns.getURI();
1861 
1862             if (uri != null) {
1863                 if (!namespaceStack.contains(ns)) {
1864                     return true;
1865                 }
1866             }
1867         }
1868 
1869         return false;
1870     }
1871 
1872     protected void handleException(IOException e) throws SAXException {
1873         throw new SAXException(e);
1874     }
1875 
1876     // Laramie Crocker 4/8/2002 10:38AM
1877 
1878     /***
1879      * Lets subclasses get at the current format object, so they can call
1880      * setTrimText, setNewLines, etc. Put in to support the HTMLWriter, in the
1881      * way that it pushes the current newline/trim state onto a stack and
1882      * overrides the state within preformatted tags.
1883      * 
1884      * @return DOCUMENT ME!
1885      */
1886     protected OutputFormat getOutputFormat() {
1887         return format;
1888     }
1889 
1890     public boolean resolveEntityRefs() {
1891         return resolveEntityRefs;
1892     }
1893 
1894     public void setResolveEntityRefs(boolean resolve) {
1895         this.resolveEntityRefs = resolve;
1896     }
1897 }
1898 
1899 /*
1900  * Redistribution and use of this software and associated documentation
1901  * ("Software"), with or without modification, are permitted provided that the
1902  * following conditions are met:
1903  * 
1904  * 1. Redistributions of source code must retain copyright statements and
1905  * notices. Redistributions must also contain a copy of this document.
1906  * 
1907  * 2. Redistributions in binary form must reproduce the above copyright notice,
1908  * this list of conditions and the following disclaimer in the documentation
1909  * and/or other materials provided with the distribution.
1910  * 
1911  * 3. The name "DOM4J" must not be used to endorse or promote products derived
1912  * from this Software without prior written permission of MetaStuff, Ltd. For
1913  * written permission, please contact dom4j-info@metastuff.com.
1914  * 
1915  * 4. Products derived from this Software may not be called "DOM4J" nor may
1916  * "DOM4J" appear in their names without prior written permission of MetaStuff,
1917  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
1918  * 
1919  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
1920  * 
1921  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
1922  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1923  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1924  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
1925  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
1926  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
1927  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
1928  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
1929  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
1930  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
1931  * POSSIBILITY OF SUCH DAMAGE.
1932  * 
1933  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
1934  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/DocumentResult.html0000644000175000017500000002337710242117715022052 0ustar ebourgebourg DocumentResult xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import javax.xml.transform.sax.SAXResult;
11  
12  import org.dom4j.Document;
13  
14  import org.xml.sax.ContentHandler;
15  import org.xml.sax.ext.LexicalHandler;
16  
17  /***
18   * <p>
19   * <code>DocumentResult</code> implements a JAXP {@link SAXResult}for a
20   * {@link Document}.
21   * </p>
22   * 
23   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
24   * @version $Revision: 1.8 $
25   */
26  public class DocumentResult extends SAXResult {
27      private SAXContentHandler contentHandler;
28  
29      public DocumentResult() {
30          this(new SAXContentHandler());
31      }
32  
33      public DocumentResult(SAXContentHandler contentHandler) {
34          this.contentHandler = contentHandler;
35          super.setHandler(this.contentHandler);
36          super.setLexicalHandler(this.contentHandler);
37      }
38  
39      /***
40       * DOCUMENT ME!
41       * 
42       * @return the Document created by the transformation
43       */
44      public Document getDocument() {
45          return contentHandler.getDocument();
46      }
47  
48      // Overloaded methods
49      // -------------------------------------------------------------------------
50      public void setHandler(ContentHandler handler) {
51          if (handler instanceof SAXContentHandler) {
52              this.contentHandler = (SAXContentHandler) handler;
53              super.setHandler(this.contentHandler);
54          }
55      }
56  
57      public void setLexicalHandler(LexicalHandler handler) {
58          if (handler instanceof SAXContentHandler) {
59              this.contentHandler = (SAXContentHandler) handler;
60              super.setLexicalHandler(this.contentHandler);
61          }
62      }
63  }
64  
65  /*
66   * Redistribution and use of this software and associated documentation
67   * ("Software"), with or without modification, are permitted provided that the
68   * following conditions are met:
69   * 
70   * 1. Redistributions of source code must retain copyright statements and
71   * notices. Redistributions must also contain a copy of this document.
72   * 
73   * 2. Redistributions in binary form must reproduce the above copyright notice,
74   * this list of conditions and the following disclaimer in the documentation
75   * and/or other materials provided with the distribution.
76   * 
77   * 3. The name "DOM4J" must not be used to endorse or promote products derived
78   * from this Software without prior written permission of MetaStuff, Ltd. For
79   * written permission, please contact dom4j-info@metastuff.com.
80   * 
81   * 4. Products derived from this Software may not be called "DOM4J" nor may
82   * "DOM4J" appear in their names without prior written permission of MetaStuff,
83   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
84   * 
85   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
86   * 
87   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
88   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
89   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
90   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
91   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
92   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
93   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
94   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
95   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
96   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
97   * POSSIBILITY OF SUCH DAMAGE.
98   * 
99   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
100  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/OutputFormat.html0000644000175000017500000014101410242117726021535 0ustar ebourgebourg OutputFormat xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  /***
11   * <p>
12   * <code>OutputFormat</code> represents the format configuration used by
13   * {@linkXMLWriter}and its base classes to format the XML output
14   * </p>
15   * 
16   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
17   * @version $Revision: 1.17 $
18   */
19  public class OutputFormat implements Cloneable {
20      /*** standard value to indent by, if we are indenting */
21      protected static final String STANDARD_INDENT = "  ";
22  
23      /***
24       * Whether or not to suppress the XML declaration - default is
25       * <code>false</code>
26       */
27      private boolean suppressDeclaration = false;
28  
29      /***
30       * Whether or not to print new line after the XML declaration - default is
31       * <code>true</code>
32       */
33      private boolean newLineAfterDeclaration = true;
34  
35      /*** The encoding format */
36      private String encoding = "UTF-8";
37  
38      /***
39       * Whether or not to output the encoding in the XML declaration - default is
40       * <code>false</code>
41       */
42      private boolean omitEncoding = false;
43  
44      /*** The default indent is no spaces (as original document) */
45      private String indent = null;
46  
47      /***
48       * Whether or not to expand empty elements to
49       * &lt;tagName&gt;&lt;/tagName&gt; - default is <code>false</code>
50       */
51      private boolean expandEmptyElements = false;
52  
53      /***
54       * The default new line flag, set to do new lines only as in original
55       * document
56       */
57      private boolean newlines = false;
58  
59      /*** New line separator */
60      private String lineSeparator = "\n";
61  
62      /*** should we preserve whitespace or not in text nodes? */
63      private boolean trimText = false;
64  
65      /*** pad string-element boundaries with whitespace */
66      private boolean padText = false;
67  
68      /*** Whether or not to use XHTML standard. */
69      private boolean doXHTML = false;
70  
71      /***
72       * Controls when to output a line.separtor every so many tags in case of no
73       * lines and total text trimming.
74       */
75      private int newLineAfterNTags = 0; // zero means don't bother.
76  
77      /*** Quote character to use when writing attributes. */
78      private char attributeQuoteChar = '\"';
79  
80      /***
81       * Creates an <code>OutputFormat</code> with no additional whitespace
82       * (indent or new lines) added. The whitespace from the element text content
83       * is fully preserved.
84       */
85      public OutputFormat() {
86      }
87  
88      /***
89       * Creates an <code>OutputFormat</code> with the given indent added but no
90       * new lines added. All whitespace from element text will be included.
91       * 
92       * @param indent
93       *            is the indent string to be used for indentation (usually a
94       *            number of spaces).
95       */
96      public OutputFormat(String indent) {
97          this.indent = indent;
98      }
99  
100     /***
101      * Creates an <code>OutputFormat</code> with the given indent added with
102      * optional newlines between the Elements. All whitespace from element text
103      * will be included.
104      * 
105      * @param indent
106      *            is the indent string to be used for indentation (usually a
107      *            number of spaces).
108      * @param newlines
109      *            whether new lines are added to layout the
110      */
111     public OutputFormat(String indent, boolean newlines) {
112         this.indent = indent;
113         this.newlines = newlines;
114     }
115 
116     /***
117      * Creates an <code>OutputFormat</code> with the given indent added with
118      * optional newlines between the Elements and the given encoding format.
119      * 
120      * @param indent
121      *            is the indent string to be used for indentation (usually a
122      *            number of spaces).
123      * @param newlines
124      *            whether new lines are added to layout the
125      * @param encoding
126      *            is the text encoding to use for writing the XML
127      */
128     public OutputFormat(String indent, boolean newlines, String encoding) {
129         this.indent = indent;
130         this.newlines = newlines;
131         this.encoding = encoding;
132     }
133 
134     public String getLineSeparator() {
135         return lineSeparator;
136     }
137 
138     /***
139      * <p>
140      * This will set the new-line separator. The default is <code>\n</code>.
141      * Note that if the "newlines" property is false, this value is irrelevant.
142      * To make it output the system default line ending string, call
143      * <code>setLineSeparator(System.getProperty("line.separator"))</code>
144      * </p>
145      * 
146      * @param separator
147      *            <code>String</code> line separator to use.
148      * 
149      * @see #setNewlines(boolean)
150      */
151     public void setLineSeparator(String separator) {
152         lineSeparator = separator;
153     }
154 
155     public boolean isNewlines() {
156         return newlines;
157     }
158 
159     /***
160      * DOCUMENT ME!
161      * 
162      * @param newlines
163      *            <code>true</code> indicates new lines should be printed,
164      *            else new lines are ignored (compacted).
165      * 
166      * @see #setLineSeparator(String)
167      */
168     public void setNewlines(boolean newlines) {
169         this.newlines = newlines;
170     }
171 
172     public String getEncoding() {
173         return encoding;
174     }
175 
176     /***
177      * DOCUMENT ME!
178      * 
179      * @param encoding
180      *            encoding format
181      */
182     public void setEncoding(String encoding) {
183         if (encoding != null) {
184             this.encoding = encoding;
185         }
186     }
187 
188     public boolean isOmitEncoding() {
189         return omitEncoding;
190     }
191 
192     /***
193      * <p>
194      * This will set whether the XML declaration (<code>&lt;?xml version="1.0"
195      * encoding="UTF-8"?&gt;</code>)
196      * includes the encoding of the document. It is common to suppress this in
197      * protocols such as WML and SOAP.
198      * </p>
199      * 
200      * @param omitEncoding
201      *            <code>boolean</code> indicating whether or not the XML
202      *            declaration should indicate the document encoding.
203      */
204     public void setOmitEncoding(boolean omitEncoding) {
205         this.omitEncoding = omitEncoding;
206     }
207 
208     /***
209      * <p>
210      * This will set whether the XML declaration (<code>&lt;?xml version="1.0"
211      * encoding="UTF-8"?&gt;</code>)
212      * is included or not. It is common to suppress this in protocols such as
213      * WML and SOAP.
214      * </p>
215      * 
216      * @param suppressDeclaration
217      *            <code>boolean</code> indicating whether or not the XML
218      *            declaration should be suppressed.
219      */
220     public void setSuppressDeclaration(boolean suppressDeclaration) {
221         this.suppressDeclaration = suppressDeclaration;
222     }
223 
224     /***
225      * DOCUMENT ME!
226      * 
227      * @return true if the output of the XML declaration (<code>&lt;?xml
228      *         version="1.0"?&gt;</code>)
229      *         should be suppressed else false.
230      */
231     public boolean isSuppressDeclaration() {
232         return suppressDeclaration;
233     }
234 
235     /***
236      * <p>
237      * This will set whether a new line is printed after the XML declaration
238      * (assuming it is not supressed.)
239      * </p>
240      * 
241      * @param newLineAfterDeclaration
242      *            <code>boolean</code> indicating whether or not to print new
243      *            line following the XML declaration. The default is true.
244      */
245     public void setNewLineAfterDeclaration(boolean newLineAfterDeclaration) {
246         this.newLineAfterDeclaration = newLineAfterDeclaration;
247     }
248 
249     /***
250      * DOCUMENT ME!
251      * 
252      * @return true if a new line should be printed following XML declaration
253      */
254     public boolean isNewLineAfterDeclaration() {
255         return newLineAfterDeclaration;
256     }
257 
258     public boolean isExpandEmptyElements() {
259         return expandEmptyElements;
260     }
261 
262     /***
263      * <p>
264      * This will set whether empty elements are expanded from
265      * <code>&lt;tagName&gt;</code> to
266      * <code>&lt;tagName&gt;&lt;/tagName&gt;</code>.
267      * </p>
268      * 
269      * @param expandEmptyElements
270      *            <code>boolean</code> indicating whether or not empty
271      *            elements should be expanded.
272      */
273     public void setExpandEmptyElements(boolean expandEmptyElements) {
274         this.expandEmptyElements = expandEmptyElements;
275     }
276 
277     public boolean isTrimText() {
278         return trimText;
279     }
280 
281     /***
282      * <p>
283      * This will set whether the text is output verbatim (false) or with
284      * whitespace stripped as per <code>{@link
285      * org.dom4j.Element#getTextTrim()}</code>.
286      * </p>
287      * 
288      * <p>
289      * </p>
290      * 
291      * <p>
292      * Default: false
293      * </p>
294      * 
295      * @param trimText
296      *            <code>boolean</code> true=>trim the whitespace, false=>use
297      *            text verbatim
298      */
299     public void setTrimText(boolean trimText) {
300         this.trimText = trimText;
301     }
302 
303     public boolean isPadText() {
304         return padText;
305     }
306 
307     /***
308      * <p>
309      * Ensure that text immediately preceded by or followed by an element will
310      * be "padded" with a single space. This is used to allow make
311      * browser-friendly HTML, avoiding trimText's transformation of, e.g.,
312      * <code>The quick &lt;b&gt;brown&lt;/b&gt; fox</code> into <code>The
313      * quick&lt;b&gt;brown&lt;/b&gt;fox</code>
314      * (the latter will run the three separate words together into a single
315      * word). This setting is not too useful if you haven't also called
316      * {@link #setTrimText}.
317      * </p>
318      * 
319      * <p>
320      * The padding string will only be added if the text itself starts or ends
321      * with some whitespace characters.
322      * </p>
323      * 
324      * <p>
325      * Default: false
326      * </p>
327      * 
328      * @param padText
329      *            <code>boolean</code> if true, pad string-element boundaries
330      */
331     public void setPadText(boolean padText) {
332         this.padText = padText;
333     }
334 
335     public String getIndent() {
336         return indent;
337     }
338 
339     /***
340      * <p>
341      * This will set the indent <code>String</code> to use; this is usually a
342      * <code>String</code> of empty spaces. If you pass null, or the empty
343      * string (""), then no indentation will happen.
344      * </p>
345      * Default: none (null)
346      * 
347      * @param indent
348      *            <code>String</code> to use for indentation.
349      */
350     public void setIndent(String indent) {
351         // nullify empty string to void unnecessary indentation code
352         if ((indent != null) && (indent.length() <= 0)) {
353             indent = null;
354         }
355 
356         this.indent = indent;
357     }
358 
359     /***
360      * Set the indent on or off. If setting on, will use the value of
361      * STANDARD_INDENT, which is usually two spaces.
362      * 
363      * @param doIndent
364      *            if true, set indenting on; if false, set indenting off
365      */
366     public void setIndent(boolean doIndent) {
367         if (doIndent) {
368             this.indent = STANDARD_INDENT;
369         } else {
370             this.indent = null;
371         }
372     }
373 
374     /***
375      * <p>
376      * This will set the indent <code>String</code>'s size; an indentSize of
377      * 4 would result in the indention being equivalent to the
378      * <code>String</code> "&nbsp;&nbsp;&nbsp;&nbsp;" (four space characters).
379      * </p>
380      * 
381      * @param indentSize
382      *            <code>int</code> number of spaces in indentation.
383      */
384     public void setIndentSize(int indentSize) {
385         StringBuffer indentBuffer = new StringBuffer();
386 
387         for (int i = 0; i < indentSize; i++) {
388             indentBuffer.append(" ");
389         }
390 
391         this.indent = indentBuffer.toString();
392     }
393 
394     /***
395      * <p>
396      * Whether or not to use the XHTML standard: like HTML but passes an XML
397      * parser with real, closed tags. Also, XHTML CDATA sections will be output
398      * with the CDATA delimiters: ( &quot; <b>&lt;![CDATA[ </b>&quot; and &quot;
399      * <b>]]&gt; </b>&quot; ) otherwise, the class HTMLWriter will output the
400      * CDATA text, but not the delimiters.
401      * </p>
402      * 
403      * <p>
404      * Default is <code>false</code>
405      * </p>
406      * 
407      * @return DOCUMENT ME!
408      */
409     public boolean isXHTML() {
410         return doXHTML;
411     }
412 
413     /***
414      * <p>
415      * This will set whether or not to use the XHTML standard: like HTML but
416      * passes an XML parser with real, closed tags. Also, XHTML CDATA sections
417      * will be output with the CDATA delimiters: ( &quot; <b>&lt;[CDATA[
418      * </b>&quot; and &quot; <b>]]&lt; </b>) otherwise, the class HTMLWriter
419      * will output the CDATA text, but not the delimiters.
420      * </p>
421      * 
422      * <p>
423      * Default: false
424      * </p>
425      * 
426      * @param xhtml
427      *            <code>boolean</code> true=>conform to XHTML, false=>conform
428      *            to HTML, can have unclosed tags, etc.
429      */
430     public void setXHTML(boolean xhtml) {
431         doXHTML = xhtml;
432     }
433 
434     public int getNewLineAfterNTags() {
435         return newLineAfterNTags;
436     }
437 
438     /***
439      * Controls output of a line.separator every tagCount tags when isNewlines
440      * is false. If tagCount equals zero, it means don't do anything special. If
441      * greater than zero, then a line.separator will be output after tagCount
442      * tags have been output. Used when you would like to squeeze the html as
443      * much as possible, but some browsers don't like really long lines. A tag
444      * count of 10 would produce a line.separator in the output after 10 close
445      * tags (including single tags).
446      * 
447      * @param tagCount
448      *            DOCUMENT ME!
449      */
450     public void setNewLineAfterNTags(int tagCount) {
451         newLineAfterNTags = tagCount;
452     }
453 
454     public char getAttributeQuoteCharacter() {
455         return attributeQuoteChar;
456     }
457 
458     /***
459      * Sets the character used to quote attribute values. The specified
460      * character must be a valid XML attribute quote character, otherwise an
461      * <code>IllegalArgumentException</code> will be thrown.
462      * 
463      * @param quoteChar
464      *            The character to use when quoting attribute values.
465      * 
466      * @throws IllegalArgumentException
467      *             If the specified character is not a valid XML attribute quote
468      *             character.
469      */
470     public void setAttributeQuoteCharacter(char quoteChar) {
471         if ((quoteChar == '\'') || (quoteChar == '"')) {
472             attributeQuoteChar = quoteChar;
473         } else {
474             throw new IllegalArgumentException("Invalid attribute quote "
475                     + "character (" + quoteChar + ")");
476         }
477     }
478 
479     /***
480      * Parses command line arguments of the form <code>-omitEncoding
481      * -indentSize 3 -newlines -trimText</code>
482      * 
483      * @param args
484      *            is the array of command line arguments
485      * @param i
486      *            is the index in args to start parsing options
487      * 
488      * @return the index of first parameter that we didn't understand
489      */
490     public int parseOptions(String[] args, int i) {
491         for (int size = args.length; i < size; i++) {
492             if (args[i].equals("-suppressDeclaration")) {
493                 setSuppressDeclaration(true);
494             } else if (args[i].equals("-omitEncoding")) {
495                 setOmitEncoding(true);
496             } else if (args[i].equals("-indent")) {
497                 setIndent(args[++i]);
498             } else if (args[i].equals("-indentSize")) {
499                 setIndentSize(Integer.parseInt(args[++i]));
500             } else if (args[i].startsWith("-expandEmpty")) {
501                 setExpandEmptyElements(true);
502             } else if (args[i].equals("-encoding")) {
503                 setEncoding(args[++i]);
504             } else if (args[i].equals("-newlines")) {
505                 setNewlines(true);
506             } else if (args[i].equals("-lineSeparator")) {
507                 setLineSeparator(args[++i]);
508             } else if (args[i].equals("-trimText")) {
509                 setTrimText(true);
510             } else if (args[i].equals("-padText")) {
511                 setPadText(true);
512             } else if (args[i].startsWith("-xhtml")) {
513                 setXHTML(true);
514             } else {
515                 return i;
516             }
517         }
518 
519         return i;
520     }
521 
522     /***
523      * A static helper method to create the default pretty printing format. This
524      * format consists of an indent of 2 spaces, newlines after each element and
525      * all other whitespace trimmed, and XMTML is false.
526      * 
527      * @return DOCUMENT ME!
528      */
529     public static OutputFormat createPrettyPrint() {
530         OutputFormat format = new OutputFormat();
531         format.setIndentSize(2);
532         format.setNewlines(true);
533         format.setTrimText(true);
534         format.setPadText(true);
535 
536         return format;
537     }
538 
539     /***
540      * A static helper method to create the default compact format. This format
541      * does not have any indentation or newlines after an alement and all other
542      * whitespace trimmed
543      * 
544      * @return DOCUMENT ME!
545      */
546     public static OutputFormat createCompactFormat() {
547         OutputFormat format = new OutputFormat();
548         format.setIndent(false);
549         format.setNewlines(false);
550         format.setTrimText(true);
551 
552         return format;
553     }
554 }
555 
556 /*
557  * Redistribution and use of this software and associated documentation
558  * ("Software"), with or without modification, are permitted provided that the
559  * following conditions are met:
560  * 
561  * 1. Redistributions of source code must retain copyright statements and
562  * notices. Redistributions must also contain a copy of this document.
563  * 
564  * 2. Redistributions in binary form must reproduce the above copyright notice,
565  * this list of conditions and the following disclaimer in the documentation
566  * and/or other materials provided with the distribution.
567  * 
568  * 3. The name "DOM4J" must not be used to endorse or promote products derived
569  * from this Software without prior written permission of MetaStuff, Ltd. For
570  * written permission, please contact dom4j-info@metastuff.com.
571  * 
572  * 4. Products derived from this Software may not be called "DOM4J" nor may
573  * "DOM4J" appear in their names without prior written permission of MetaStuff,
574  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
575  * 
576  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
577  * 
578  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
579  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
580  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
581  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
582  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
583  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
584  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
585  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
586  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
587  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
588  * POSSIBILITY OF SUCH DAMAGE.
589  * 
590  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
591  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/ElementModifier.html0000644000175000017500000001766510242117760022150 0ustar ebourgebourg ElementModifier xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import org.dom4j.Element;
11  
12  /***
13   * ElementModifier defines a modifier of {@link org.dom4j.Element}objects. <br>
14   * It can be used in the event based {@link org.dom4j.io.SAXModifier}, in order
15   * to modify elements on the fly, rather than waiting until the complete
16   * document is parsed.
17   * 
18   * @author Wonne Keysers (Realsoftware.be)
19   */
20  public interface ElementModifier {
21      /***
22       * Called by an event based processor when an elements closing tag is
23       * encountered. This method must return the modified version of the provided
24       * {@link org.dom4j.Element}or null if it has to be removed from the
25       * document. <br>
26       * The incoming {@link org.dom4j.Element}is disconnected from the DOM4J
27       * tree. This means that navigation to the elements parent {@link
28       * org.dom4j.Element} and {@link org.dom4j.Document}are not available. Only
29       * the element itself can be modified!
30       * 
31       * @param element
32       *            {@link org.dom4j.Element}to be parsed
33       * 
34       * @return the modified {@link org.dom4j.Element}
35       * 
36       * @throws Exception
37       *             of any kind
38       */
39      Element modifyElement(Element element) throws Exception;
40  }
41  
42  /*
43   * Redistribution and use of this software and associated documentation
44   * ("Software"), with or without modification, are permitted provided that the
45   * following conditions are met:
46   * 
47   * 1. Redistributions of source code must retain copyright statements and
48   * notices. Redistributions must also contain a copy of this document.
49   * 
50   * 2. Redistributions in binary form must reproduce the above copyright notice,
51   * this list of conditions and the following disclaimer in the documentation
52   * and/or other materials provided with the distribution.
53   * 
54   * 3. The name "DOM4J" must not be used to endorse or promote products derived
55   * from this Software without prior written permission of MetaStuff, Ltd. For
56   * written permission, please contact dom4j-info@metastuff.com.
57   * 
58   * 4. Products derived from this Software may not be called "DOM4J" nor may
59   * "DOM4J" appear in their names without prior written permission of MetaStuff,
60   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
61   * 
62   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
63   * 
64   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
65   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
66   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
67   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
68   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
69   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
70   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
71   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
72   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
73   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
74   * POSSIBILITY OF SUCH DAMAGE.
75   * 
76   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
77   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/SAXValidator.html0000644000175000017500000004211210242117703021357 0ustar ebourgebourg SAXValidator xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.io.IOException;
11  
12  import org.dom4j.Document;
13  
14  import org.xml.sax.ContentHandler;
15  import org.xml.sax.ErrorHandler;
16  import org.xml.sax.SAXException;
17  import org.xml.sax.XMLReader;
18  import org.xml.sax.helpers.DefaultHandler;
19  
20  /***
21   * <p>
22   * <code>SAXValidator</code> validates an XML document by writing the document
23   * to a text buffer and parsing it with a validating SAX parser. This could be
24   * implemented much more efficiently by validating against the dom4j object
25   * model directly but at least allows the reuse of existing SAX based validating
26   * parsers.
27   * </p>
28   * 
29   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
30   * @version $Revision: 1.10 $
31   */
32  public class SAXValidator {
33      /*** <code>XMLReader</code> used to parse the SAX events */
34      private XMLReader xmlReader;
35  
36      /*** ErrorHandler class to use */
37      private ErrorHandler errorHandler;
38  
39      public SAXValidator() {
40      }
41  
42      public SAXValidator(XMLReader xmlReader) {
43          this.xmlReader = xmlReader;
44      }
45  
46      /***
47       * Validates the given <code>Document</code> by writing it to a validating
48       * SAX Parser.
49       * 
50       * @param document
51       *            is the Document to validate
52       * 
53       * @throws SAXException
54       *             if a validation error occurs
55       * @throws RuntimeException
56       *             DOCUMENT ME!
57       */
58      public void validate(Document document) throws SAXException {
59          if (document != null) {
60              XMLReader reader = getXMLReader();
61  
62              if (errorHandler != null) {
63                  reader.setErrorHandler(errorHandler);
64              }
65  
66              try {
67                  reader.parse(new DocumentInputSource(document));
68              } catch (IOException e) {
69                  throw new RuntimeException("Caught and exception that should "
70                          + "never happen: " + e);
71              }
72          }
73      }
74  
75      // Properties
76      // -------------------------------------------------------------------------
77  
78      /***
79       * DOCUMENT ME!
80       * 
81       * @return the <code>XMLReader</code> used to parse SAX events
82       * 
83       * @throws SAXException
84       *             DOCUMENT ME!
85       */
86      public XMLReader getXMLReader() throws SAXException {
87          if (xmlReader == null) {
88              xmlReader = createXMLReader();
89              configureReader();
90          }
91  
92          return xmlReader;
93      }
94  
95      /***
96       * Sets the <code>XMLReader</code> used to parse SAX events
97       * 
98       * @param reader
99       *            is the <code>XMLReader</code> to parse SAX events
100      * 
101      * @throws SAXException
102      *             DOCUMENT ME!
103      */
104     public void setXMLReader(XMLReader reader) throws SAXException {
105         this.xmlReader = reader;
106         configureReader();
107     }
108 
109     /***
110      * DOCUMENT ME!
111      * 
112      * @return the <code>ErrorHandler</code> used by SAX
113      */
114     public ErrorHandler getErrorHandler() {
115         return errorHandler;
116     }
117 
118     /***
119      * Sets the <code>ErrorHandler</code> used by the SAX
120      * <code>XMLReader</code>.
121      * 
122      * @param errorHandler
123      *            is the <code>ErrorHandler</code> used by SAX
124      */
125     public void setErrorHandler(ErrorHandler errorHandler) {
126         this.errorHandler = errorHandler;
127     }
128 
129     // Implementation methods
130     // -------------------------------------------------------------------------
131 
132     /***
133      * Factory Method to allow alternate methods of creating and configuring
134      * XMLReader objects
135      * 
136      * @return DOCUMENT ME!
137      * 
138      * @throws SAXException
139      *             DOCUMENT ME!
140      */
141     protected XMLReader createXMLReader() throws SAXException {
142         return SAXHelper.createXMLReader(true);
143     }
144 
145     /***
146      * Configures the XMLReader before use
147      * 
148      * @throws SAXException
149      *             DOCUMENT ME!
150      */
151     protected void configureReader() throws SAXException {
152         ContentHandler handler = xmlReader.getContentHandler();
153 
154         if (handler == null) {
155             xmlReader.setContentHandler(new DefaultHandler());
156         }
157 
158         // configure validation support
159         xmlReader.setFeature("http://xml.org/sax/features/validation", true);
160 
161         // configure namespace support
162         xmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
163         xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes",
164                 false);
165     }
166 }
167 
168 /*
169  * Redistribution and use of this software and associated documentation
170  * ("Software"), with or without modification, are permitted provided that the
171  * following conditions are met:
172  * 
173  * 1. Redistributions of source code must retain copyright statements and
174  * notices. Redistributions must also contain a copy of this document.
175  * 
176  * 2. Redistributions in binary form must reproduce the above copyright notice,
177  * this list of conditions and the following disclaimer in the documentation
178  * and/or other materials provided with the distribution.
179  * 
180  * 3. The name "DOM4J" must not be used to endorse or promote products derived
181  * from this Software without prior written permission of MetaStuff, Ltd. For
182  * written permission, please contact dom4j-info@metastuff.com.
183  * 
184  * 4. Products derived from this Software may not be called "DOM4J" nor may
185  * "DOM4J" appear in their names without prior written permission of MetaStuff,
186  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
187  * 
188  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
189  * 
190  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
191  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
192  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
193  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
194  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
195  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
196  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
197  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
198  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
199  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
200  * POSSIBILITY OF SUCH DAMAGE.
201  * 
202  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
203  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/SAXModifier.html0000644000175000017500000011506310242117716021202 0ustar ebourgebourg SAXModifier xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.io.File;
11  import java.io.InputStream;
12  import java.io.Reader;
13  import java.net.URL;
14  import java.util.HashMap;
15  import java.util.Iterator;
16  import java.util.Map;
17  
18  import org.dom4j.Document;
19  import org.dom4j.DocumentException;
20  import org.dom4j.DocumentFactory;
21  
22  import org.xml.sax.InputSource;
23  import org.xml.sax.SAXException;
24  import org.xml.sax.XMLReader;
25  
26  /***
27   * The SAXModifier reads, modifies and writes XML documents using SAX.
28   * 
29   * <p>
30   * Registered {@link ElementModifier}objects can provide modifications to (part
31   * of) the xml tree, while the document is still being processed. This makes it
32   * possible to change large xml documents without having them in memory.
33   * </p>
34   * 
35   * <p>
36   * The modified document is written when the {@link XMLWriter}is specified.
37   * </p>
38   * 
39   * @author Wonne Keysers (Realsoftware.be)
40   * 
41   * @see org.dom4j.io.SAXReader
42   * @see org.dom4j.io.XMLWriter
43   */
44  public class SAXModifier {
45      private XMLWriter xmlWriter;
46  
47      private XMLReader xmlReader;
48  
49      private boolean pruneElements;
50  
51      private SAXModifyReader modifyReader;
52  
53      private HashMap modifiers = new HashMap();
54  
55      /***
56       * Creates a new modifier. <br>
57       * The XMLReader to parse the source will be created via the
58       * org.xml.sax.driver system property or JAXP if the system property is not
59       * set.
60       */
61      public SAXModifier() {
62      }
63  
64      /***
65       * Creates a new modifier. <br>
66       * The XMLReader to parse the source will be created via the
67       * org.xml.sax.driver system property or JAXP if the system property is not
68       * set.
69       * 
70       * @param pruneElements
71       *            Set to true when the modified document must NOT be kept in
72       *            memory.
73       */
74      public SAXModifier(boolean pruneElements) {
75          this.pruneElements = pruneElements;
76      }
77  
78      /***
79       * Creates a new modifier that will the specified {@link
80       * org.xml.sax.XMLReader} to parse the source.
81       * 
82       * @param xmlReader
83       *            The XMLReader to use
84       */
85      public SAXModifier(XMLReader xmlReader) {
86          this.xmlReader = xmlReader;
87      }
88  
89      /***
90       * Creates a new modifier that will the specified {@link
91       * org.xml.sax.XMLReader} to parse the source.
92       * 
93       * @param xmlReader
94       *            The XMLReader to use
95       * @param pruneElements
96       *            Set to true when the modified document must NOT be kept in
97       *            memory.
98       */
99      public SAXModifier(XMLReader xmlReader, boolean pruneElements) {
100         this.xmlReader = xmlReader;
101     }
102 
103     /***
104      * Reads a Document from the given {@link java.io.File}and writes it to the
105      * specified {@link XMLWriter}using SAX. Registered {@linkElementModifier}
106      * objects are invoked on the fly.
107      * 
108      * @param source
109      *            is the <code>File</code> to read from.
110      * 
111      * @return the newly created Document instance
112      * 
113      * @throws DocumentException
114      *             DocumentException org.dom4j.DocumentException} if an error
115      *             occurs during parsing.
116      */
117     public Document modify(File source) throws DocumentException {
118         try {
119             return installModifyReader().read(source);
120         } catch (SAXModifyException ex) {
121             Throwable cause = ex.getCause();
122             throw new DocumentException(cause.getMessage(), cause);
123         }
124     }
125 
126     /***
127      * Reads a Document from the given {@link org.xml.sax.InputSource}and
128      * writes it to the specified {@link XMLWriter}using SAX. Registered
129      * {@link ElementModifier}objects are invoked on the fly.
130      * 
131      * @param source
132      *            is the <code>org.xml.sax.InputSource</code> to read from.
133      * 
134      * @return the newly created Document instance
135      * 
136      * @throws DocumentException
137      *             DocumentException org.dom4j.DocumentException} if an error
138      *             occurs during parsing.
139      */
140     public Document modify(InputSource source) throws DocumentException {
141         try {
142             return installModifyReader().read(source);
143         } catch (SAXModifyException ex) {
144             Throwable cause = ex.getCause();
145             throw new DocumentException(cause.getMessage(), cause);
146         }
147     }
148 
149     /***
150      * Reads a Document from the given {@link java.io.InputStream}and writes it
151      * to the specified {@link XMLWriter}using SAX. Registered {@link
152      * ElementModifier} objects are invoked on the fly.
153      * 
154      * @param source
155      *            is the <code>java.io.InputStream</code> to read from.
156      * 
157      * @return the newly created Document instance
158      * 
159      * @throws DocumentException
160      *             DocumentException org.dom4j.DocumentException} if an error
161      *             occurs during parsing.
162      */
163     public Document modify(InputStream source) throws DocumentException {
164         try {
165             return installModifyReader().read(source);
166         } catch (SAXModifyException ex) {
167             Throwable cause = ex.getCause();
168             throw new DocumentException(cause.getMessage(), cause);
169         }
170     }
171 
172     /***
173      * Reads a Document from the given {@link java.io.InputStream}and writes it
174      * to the specified {@link XMLWriter}using SAX. Registered {@link
175      * ElementModifier} objects are invoked on the fly.
176      * 
177      * @param source
178      *            is the <code>java.io.InputStream</code> to read from.
179      * @param systemId
180      *            DOCUMENT ME!
181      * 
182      * @return the newly created Document instance
183      * 
184      * @throws DocumentException
185      *             DocumentException org.dom4j.DocumentException} if an error
186      *             occurs during parsing.
187      */
188     public Document modify(InputStream source, String systemId)
189             throws DocumentException {
190         try {
191             return installModifyReader().read(source);
192         } catch (SAXModifyException ex) {
193             Throwable cause = ex.getCause();
194             throw new DocumentException(cause.getMessage(), cause);
195         }
196     }
197 
198     /***
199      * Reads a Document from the given {@link java.io.Reader}and writes it to
200      * the specified {@link XMLWriter}using SAX. Registered {@link
201      * ElementModifier} objects are invoked on the fly.
202      * 
203      * @param source
204      *            is the <code>java.io.Reader</code> to read from.
205      * 
206      * @return the newly created Document instance
207      * 
208      * @throws DocumentException
209      *             DocumentException org.dom4j.DocumentException} if an error
210      *             occurs during parsing.
211      */
212     public Document modify(Reader source) throws DocumentException {
213         try {
214             return installModifyReader().read(source);
215         } catch (SAXModifyException ex) {
216             Throwable cause = ex.getCause();
217             throw new DocumentException(cause.getMessage(), cause);
218         }
219     }
220 
221     /***
222      * Reads a Document from the given {@link java.io.Reader}and writes it to
223      * the specified {@link XMLWriter}using SAX. Registered {@link
224      * ElementModifier} objects are invoked on the fly.
225      * 
226      * @param source
227      *            is the <code>java.io.Reader</code> to read from.
228      * @param systemId
229      *            DOCUMENT ME!
230      * 
231      * @return the newly created Document instance
232      * 
233      * @throws DocumentException
234      *             DocumentException org.dom4j.DocumentException} if an error
235      *             occurs during parsing.
236      */
237     public Document modify(Reader source, String systemId)
238             throws DocumentException {
239         try {
240             return installModifyReader().read(source);
241         } catch (SAXModifyException ex) {
242             Throwable cause = ex.getCause();
243             throw new DocumentException(cause.getMessage(), cause);
244         }
245     }
246 
247     /***
248      * Reads a Document from the given {@link java.net.URL}and writes it to the
249      * specified {@link XMLWriter}using SAX. Registered {@linkElementModifier}
250      * objects are invoked on the fly.
251      * 
252      * @param source
253      *            is the <code>java.net.URL</code> to read from.
254      * 
255      * @return the newly created Document instance
256      * 
257      * @throws DocumentException
258      *             DocumentException org.dom4j.DocumentException} if an error
259      *             occurs during parsing.
260      */
261     public Document modify(URL source) throws DocumentException {
262         try {
263             return installModifyReader().read(source);
264         } catch (SAXModifyException ex) {
265             Throwable cause = ex.getCause();
266             throw new DocumentException(cause.getMessage(), cause);
267         }
268     }
269 
270     /***
271      * Reads a Document from the given URL or filename and writes it to the
272      * specified {@link XMLWriter}using SAX. Registered {@linkElementModifier}
273      * objects are invoked on the fly.
274      * 
275      * @param source
276      *            is the URL or filename to read from.
277      * 
278      * @return the newly created Document instance
279      * 
280      * @throws DocumentException
281      *             DocumentException org.dom4j.DocumentException} if an error
282      *             occurs during parsing.
283      */
284     public Document modify(String source) throws DocumentException {
285         try {
286             return installModifyReader().read(source);
287         } catch (SAXModifyException ex) {
288             Throwable cause = ex.getCause();
289             throw new DocumentException(cause.getMessage(), cause);
290         }
291     }
292 
293     /***
294      * Adds the {@link ElementModifier}to be called when the specified element
295      * path is encounted while parsing the source.
296      * 
297      * @param path
298      *            The element path to be handled
299      * @param modifier
300      *            The {@link ElementModifier}to be called by the event based
301      *            processor.
302      */
303     public void addModifier(String path, ElementModifier modifier) {
304         this.modifiers.put(path, modifier);
305     }
306 
307     /***
308      * Removes all registered {@link ElementModifier}instances from the event
309      * based processor.
310      */
311     public void resetModifiers() {
312         this.modifiers.clear();
313         getSAXModifyReader().resetHandlers();
314     }
315 
316     /***
317      * Removes the {@link ElementModifier}from the event based processor, for
318      * the specified element path.
319      * 
320      * @param path
321      *            The path to remove the {@link ElementModifier}for.
322      */
323     public void removeModifier(String path) {
324         this.modifiers.remove(path);
325         getSAXModifyReader().removeHandler(path);
326     }
327 
328     /***
329      * Get the {@link org.dom4j.DocumentFactory}used to create the DOM4J
330      * document structure
331      * 
332      * @return <code>DocumentFactory</code> that will be used
333      */
334     public DocumentFactory getDocumentFactory() {
335         return getSAXModifyReader().getDocumentFactory();
336     }
337 
338     /***
339      * Sets the {@link org.dom4j.DocumentFactory}used to create the DOM4J
340      * document tree.
341      * 
342      * @param factory
343      *            <code>DocumentFactory</code> to be used
344      */
345     public void setDocumentFactory(DocumentFactory factory) {
346         getSAXModifyReader().setDocumentFactory(factory);
347     }
348 
349     /***
350      * Returns the current {@link XMLWriter}.
351      * 
352      * @return XMLWriter
353      */
354     public XMLWriter getXMLWriter() {
355         return this.xmlWriter;
356     }
357 
358     /***
359      * Sets the {@link XMLWriter}used to write the modified document.
360      * 
361      * @param writer
362      *            The writer to use.
363      */
364     public void setXMLWriter(XMLWriter writer) {
365         this.xmlWriter = writer;
366     }
367 
368     /***
369      * Returns true when xml elements are not kept in memory while parsing. The
370      * {@link org.dom4j.Document}returned by the modify methods will be null.
371      * 
372      * @return Returns the pruneElements.
373      */
374     public boolean isPruneElements() {
375         return pruneElements;
376     }
377 
378     private SAXReader installModifyReader() throws DocumentException {
379         try {
380             SAXModifyReader reader = getSAXModifyReader();
381 
382             if (isPruneElements()) {
383                 modifyReader.setDispatchHandler(new PruningDispatchHandler());
384             }
385 
386             reader.resetHandlers();
387 
388             Iterator modifierIt = this.modifiers.entrySet().iterator();
389 
390             while (modifierIt.hasNext()) {
391                 Map.Entry entry = (Map.Entry) modifierIt.next();
392 
393                 SAXModifyElementHandler handler = new SAXModifyElementHandler(
394                         (ElementModifier) entry.getValue());
395                 reader.addHandler((String) entry.getKey(), handler);
396             }
397 
398             reader.setXMLWriter(getXMLWriter());
399             reader.setXMLReader(getXMLReader());
400 
401             return reader;
402         } catch (SAXException ex) {
403             throw new DocumentException(ex.getMessage(), ex);
404         }
405     }
406 
407     private XMLReader getXMLReader() throws SAXException {
408         if (this.xmlReader == null) {
409             xmlReader = SAXHelper.createXMLReader(false);
410         }
411 
412         return this.xmlReader;
413     }
414 
415     private SAXModifyReader getSAXModifyReader() {
416         if (modifyReader == null) {
417             modifyReader = new SAXModifyReader();
418         }
419 
420         return modifyReader;
421     }
422 }
423 
424 /*
425  * Redistribution and use of this software and associated documentation
426  * ("Software"), with or without modification, are permitted provided that the
427  * following conditions are met:
428  * 
429  * 1. Redistributions of source code must retain copyright statements and
430  * notices. Redistributions must also contain a copy of this document.
431  * 
432  * 2. Redistributions in binary form must reproduce the above copyright notice,
433  * this list of conditions and the following disclaimer in the documentation
434  * and/or other materials provided with the distribution.
435  * 
436  * 3. The name "DOM4J" must not be used to endorse or promote products derived
437  * from this Software without prior written permission of MetaStuff, Ltd. For
438  * written permission, please contact dom4j-info@metastuff.com.
439  * 
440  * 4. Products derived from this Software may not be called "DOM4J" nor may
441  * "DOM4J" appear in their names without prior written permission of MetaStuff,
442  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
443  * 
444  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
445  * 
446  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
447  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
448  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
449  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
450  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
451  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
452  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
453  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
454  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
455  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
456  * POSSIBILITY OF SUCH DAMAGE.
457  * 
458  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
459  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/DispatchHandler.html0000644000175000017500000005363510242117724022132 0ustar ebourgebourg DispatchHandler xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.util.ArrayList;
11  import java.util.HashMap;
12  
13  import org.dom4j.Element;
14  import org.dom4j.ElementHandler;
15  import org.dom4j.ElementPath;
16  
17  /***
18   * <p>
19   * <code>DispatchHandler</code> implements the <code>ElementHandler</code>
20   * interface and provides a means to register multiple
21   * <code>ElementHandler</code> instances to be used by an event based
22   * processor. This is a special <code>ElementHandler</code> in that it's
23   * <b>onStart </b> and <b>onEnd </b> implementation methods are called for every
24   * element encountered during the parse. It then delegates to other
25   * <code>ElementHandler</code> instances registered with it to process the
26   * elements encountered.
27   * </p>
28   * 
29   * @author <a href="mailto:dwhite@equipecom.com">Dave White </a>
30   * @version $Revision: 1.11 $
31   */
32  class DispatchHandler implements ElementHandler {
33      /*** Whether the parser is at the root element or not */
34      private boolean atRoot;
35  
36      /*** The current path in the XML tree (i.e. /a/b/c) */
37      private String path;
38  
39      /*** maintains a stack of previously encountered paths */
40      private ArrayList pathStack;
41  
42      /*** maintains a stack of previously encountered handlers */
43      private ArrayList handlerStack;
44  
45      /***
46       * <code>HashMap</code> maintains the mapping between element paths and
47       * handlers
48       */
49      private HashMap handlers;
50  
51      /***
52       * <code>ElementHandler</code> to use by default for element paths with no
53       * handlers registered
54       */
55      private ElementHandler defaultHandler;
56  
57      public DispatchHandler() {
58          atRoot = true;
59          path = "/";
60          pathStack = new ArrayList();
61          handlerStack = new ArrayList();
62          handlers = new HashMap();
63      }
64  
65      /***
66       * Adds the <code>ElementHandler</code> to be called when the specified
67       * path is encounted.
68       * 
69       * @param handlerPath
70       *            is the path to be handled
71       * @param handler
72       *            is the <code>ElementHandler</code> to be called by the event
73       *            based processor.
74       */
75      public void addHandler(String handlerPath, ElementHandler handler) {
76          handlers.put(handlerPath, handler);
77      }
78  
79      /***
80       * Removes the <code>ElementHandler</code> from the event based processor,
81       * for the specified path.
82       * 
83       * @param handlerPath
84       *            is the path to remove the <code>ElementHandler</code> for.
85       * 
86       * @return DOCUMENT ME!
87       */
88      public ElementHandler removeHandler(String handlerPath) {
89          return (ElementHandler) handlers.remove(handlerPath);
90      }
91  
92      /***
93       * DOCUMENT ME!
94       * 
95       * @param handlerPath
96       *            DOCUMENT ME!
97       * 
98       * @return true when an <code>ElementHandler</code> is registered for the
99       *         specified path.
100      */
101     public boolean containsHandler(String handlerPath) {
102         return handlers.containsKey(handlerPath);
103     }
104 
105     /***
106      * Get the registered {@link ElementHandler}for the specified path.
107      * 
108      * @param handlerPath
109      *            XML path to get the handler for
110      * 
111      * @return the registered handler
112      */
113     public ElementHandler getHandler(String handlerPath) {
114         return (ElementHandler) handlers.get(handlerPath);
115     }
116 
117     /***
118      * Returns the number of {@link ElementHandler}objects that are waiting for
119      * their elements closing tag.
120      * 
121      * @return number of active handlers
122      */
123     public int getActiveHandlerCount() {
124         return handlerStack.size();
125     }
126 
127     /***
128      * When multiple <code>ElementHandler</code> instances have been
129      * registered, this will set a default <code>ElementHandler</code> to be
130      * called for any path which does <b>NOT </b> have a handler registered.
131      * 
132      * @param handler
133      *            is the <code>ElementHandler</code> to be called by the event
134      *            based processor.
135      */
136     public void setDefaultHandler(ElementHandler handler) {
137         defaultHandler = handler;
138     }
139 
140     /***
141      * Used to remove all the Element Handlers and return things back to the way
142      * they were when object was created.
143      */
144     public void resetHandlers() {
145         atRoot = true;
146         path = "/";
147         pathStack.clear();
148         handlerStack.clear();
149         handlers.clear();
150         defaultHandler = null;
151     }
152 
153     /***
154      * DOCUMENT ME!
155      * 
156      * @return the current path for the parse
157      */
158     public String getPath() {
159         return path;
160     }
161 
162     // The following methods implement the ElementHandler interface
163     public void onStart(ElementPath elementPath) {
164         Element element = elementPath.getCurrent();
165 
166         // Save the location of the last (i.e. parent) path
167         pathStack.add(path);
168 
169         // Calculate the new path
170         if (atRoot) {
171             path = path + element.getName();
172             atRoot = false;
173         } else {
174             path = path + "/" + element.getName();
175         }
176 
177         if ((handlers != null) && (handlers.containsKey(path))) {
178             // The current node has a handler associated with it.
179             // Find the handler and save it on the handler stack.
180             ElementHandler handler = (ElementHandler) handlers.get(path);
181             handlerStack.add(handler);
182 
183             // Call the handlers onStart method.
184             handler.onStart(elementPath);
185         } else {
186             // No handler is associated with this node, so use the
187             // defaultHandler it it exists.
188             if (handlerStack.isEmpty() && (defaultHandler != null)) {
189                 defaultHandler.onStart(elementPath);
190             }
191         }
192     }
193 
194     public void onEnd(ElementPath elementPath) {
195         if ((handlers != null) && (handlers.containsKey(path))) {
196             // This node has a handler associated with it.
197             // Find the handler and pop it from the handler stack.
198             ElementHandler handler = (ElementHandler) handlers.get(path);
199             handlerStack.remove(handlerStack.size() - 1);
200 
201             // Call the handlers onEnd method
202             handler.onEnd(elementPath);
203         } else {
204             // No handler is associated with this node, so use the
205             // defaultHandler it it exists.
206             if (handlerStack.isEmpty() && (defaultHandler != null)) {
207                 defaultHandler.onEnd(elementPath);
208             }
209         }
210 
211         // Set path back to its parent
212         path = (String) pathStack.remove(pathStack.size() - 1);
213 
214         if (pathStack.size() == 0) {
215             atRoot = true;
216         }
217     }
218 }
219 
220 /*
221  * Redistribution and use of this software and associated documentation
222  * ("Software"), with or without modification, are permitted provided that the
223  * following conditions are met:
224  * 
225  * 1. Redistributions of source code must retain copyright statements and
226  * notices. Redistributions must also contain a copy of this document.
227  * 
228  * 2. Redistributions in binary form must reproduce the above copyright notice,
229  * this list of conditions and the following disclaimer in the documentation
230  * and/or other materials provided with the distribution.
231  * 
232  * 3. The name "DOM4J" must not be used to endorse or promote products derived
233  * from this Software without prior written permission of MetaStuff, Ltd. For
234  * written permission, please contact dom4j-info@metastuff.com.
235  * 
236  * 4. Products derived from this Software may not be called "DOM4J" nor may
237  * "DOM4J" appear in their names without prior written permission of MetaStuff,
238  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
239  * 
240  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
241  * 
242  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
243  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
244  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
245  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
246  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
247  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
248  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
249  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
250  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
251  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
252  * POSSIBILITY OF SUCH DAMAGE.
253  * 
254  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
255  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/SAXContentHandler.html0000644000175000017500000024023410242117704022350 0ustar ebourgebourg SAXContentHandler xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.lang.reflect.Method;
11  import java.util.ArrayList;
12  import java.util.HashMap;
13  import java.util.List;
14  import java.util.Map;
15  
16  import org.dom4j.Branch;
17  import org.dom4j.Document;
18  import org.dom4j.DocumentFactory;
19  import org.dom4j.DocumentType;
20  import org.dom4j.Element;
21  import org.dom4j.ElementHandler;
22  import org.dom4j.Namespace;
23  import org.dom4j.QName;
24  import org.dom4j.dtd.AttributeDecl;
25  import org.dom4j.dtd.ElementDecl;
26  import org.dom4j.dtd.ExternalEntityDecl;
27  import org.dom4j.dtd.InternalEntityDecl;
28  import org.dom4j.tree.AbstractElement;
29  import org.dom4j.tree.NamespaceStack;
30  
31  import org.xml.sax.Attributes;
32  import org.xml.sax.DTDHandler;
33  import org.xml.sax.EntityResolver;
34  import org.xml.sax.InputSource;
35  import org.xml.sax.Locator;
36  import org.xml.sax.SAXException;
37  import org.xml.sax.SAXParseException;
38  import org.xml.sax.ext.DeclHandler;
39  import org.xml.sax.ext.LexicalHandler;
40  import org.xml.sax.helpers.DefaultHandler;
41  
42  /***
43   * <p>
44   * <code>SAXContentHandler</code> builds a dom4j tree via SAX events.
45   * </p>
46   * 
47   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
48   * @version $Revision: 1.61 $
49   */
50  public class SAXContentHandler extends DefaultHandler implements
51          LexicalHandler, DeclHandler, DTDHandler {
52      /*** The factory used to create new <code>Document</code> instances */
53      private DocumentFactory documentFactory;
54  
55      /*** The document that is being built */
56      private Document document;
57  
58      /*** stack of <code>Element</code> objects */
59      private ElementStack elementStack;
60  
61      /*** stack of <code>Namespace</code> and <code>QName</code> objects */
62      private NamespaceStack namespaceStack;
63  
64      /*** the <code>ElementHandler</code> called as the elements are complete */
65      private ElementHandler elementHandler;
66  
67      /*** the Locator */
68      private Locator locator;
69  
70      /*** The name of the current entity */
71      private String entity;
72  
73      /*** Flag used to indicate that we are inside a DTD section */
74      private boolean insideDTDSection;
75  
76      /*** Flag used to indicate that we are inside a CDATA section */
77      private boolean insideCDATASection;
78  
79      /***
80       * buffer to hold contents of cdata section across multiple characters
81       * events
82       */
83      private StringBuffer cdataText;
84  
85      /*** namespaces that are available for use */
86      private Map availableNamespaceMap = new HashMap();
87  
88      /*** declared namespaces that are not yet available for use */
89      private List declaredNamespaceList = new ArrayList();
90  
91      /*** internal DTD declarations */
92      private List internalDTDDeclarations;
93  
94      /*** external DTD declarations */
95      private List externalDTDDeclarations;
96  
97      /*** The number of namespaces that are declared in the current scope */
98      private int declaredNamespaceIndex;
99  
100     /*** The entity resolver */
101     private EntityResolver entityResolver;
102 
103     private InputSource inputSource;
104 
105     /*** The current element we are on */
106     private Element currentElement;
107 
108     /*** Should internal DTD declarations be expanded into a List in the DTD */
109     private boolean includeInternalDTDDeclarations = false;
110 
111     /*** Should external DTD declarations be expanded into a List in the DTD */
112     private boolean includeExternalDTDDeclarations = false;
113 
114     /*** The number of levels deep we are inside a startEntity/endEntity call */
115     private int entityLevel;
116 
117     /*** Are we in an internal DTD subset? */
118     private boolean internalDTDsubset = false;
119 
120     /*** Whether adjacent text nodes should be merged */
121     private boolean mergeAdjacentText = false;
122 
123     /*** Have we added text to the buffer */
124     private boolean textInTextBuffer = false;
125 
126     /*** Should we ignore comments */
127     private boolean ignoreComments = false;
128 
129     /*** Buffer used to concatenate text together */
130     private StringBuffer textBuffer;
131 
132     /*** Holds value of property stripWhitespaceText. */
133     private boolean stripWhitespaceText = false;
134 
135     public SAXContentHandler() {
136         this(DocumentFactory.getInstance());
137     }
138 
139     public SAXContentHandler(DocumentFactory documentFactory) {
140         this(documentFactory, null);
141     }
142 
143     public SAXContentHandler(DocumentFactory documentFactory,
144             ElementHandler elementHandler) {
145         this(documentFactory, elementHandler, null);
146         this.elementStack = createElementStack();
147     }
148 
149     public SAXContentHandler(DocumentFactory documentFactory,
150             ElementHandler elementHandler, ElementStack elementStack) {
151         this.documentFactory = documentFactory;
152         this.elementHandler = elementHandler;
153         this.elementStack = elementStack;
154         this.namespaceStack = new NamespaceStack(documentFactory);
155     }
156 
157     /***
158      * DOCUMENT ME!
159      * 
160      * @return the document that has been or is being built
161      */
162     public Document getDocument() {
163         if (document == null) {
164             document = createDocument();
165         }
166 
167         return document;
168     }
169 
170     // ContentHandler interface
171     // -------------------------------------------------------------------------
172     public void setDocumentLocator(Locator documentLocator) {
173         this.locator = documentLocator;
174     }
175 
176     public void processingInstruction(String target, String data)
177             throws SAXException {
178         if (mergeAdjacentText && textInTextBuffer) {
179             completeCurrentTextNode();
180         }
181 
182         if (currentElement != null) {
183             currentElement.addProcessingInstruction(target, data);
184         } else {
185             getDocument().addProcessingInstruction(target, data);
186         }
187     }
188 
189     public void startPrefixMapping(String prefix, String uri)
190             throws SAXException {
191         namespaceStack.push(prefix, uri);
192     }
193 
194     public void endPrefixMapping(String prefix) throws SAXException {
195         namespaceStack.pop(prefix);
196         declaredNamespaceIndex = namespaceStack.size();
197     }
198 
199     public void startDocument() throws SAXException {
200         // document = createDocument();
201         document = null;
202         currentElement = null;
203 
204         elementStack.clear();
205 
206         if ((elementHandler != null)
207                 && (elementHandler instanceof DispatchHandler)) {
208             elementStack.setDispatchHandler((DispatchHandler) elementHandler);
209         }
210 
211         namespaceStack.clear();
212         declaredNamespaceIndex = 0;
213 
214         if (mergeAdjacentText && (textBuffer == null)) {
215             textBuffer = new StringBuffer();
216         }
217 
218         textInTextBuffer = false;
219     }
220 
221     public void endDocument() throws SAXException {
222         namespaceStack.clear();
223         elementStack.clear();
224         currentElement = null;
225         textBuffer = null;
226     }
227 
228     public void startElement(String namespaceURI, String localName,
229             String qualifiedName, Attributes attributes) throws SAXException {
230         if (mergeAdjacentText && textInTextBuffer) {
231             completeCurrentTextNode();
232         }
233 
234         QName qName = namespaceStack.getQName(namespaceURI, localName,
235                 qualifiedName);
236 
237         Branch branch = currentElement;
238 
239         if (branch == null) {
240             branch = getDocument();
241         }
242 
243         Element element = branch.addElement(qName);
244 
245         // add all declared namespaces
246         addDeclaredNamespaces(element);
247 
248         // now lets add all attribute values
249         addAttributes(element, attributes);
250 
251         elementStack.pushElement(element);
252         currentElement = element;
253 
254         entity = null; // fixes bug527062
255 
256         if (elementHandler != null) {
257             elementHandler.onStart(elementStack);
258         }
259     }
260 
261     public void endElement(String namespaceURI, String localName, String qName)
262             throws SAXException {
263         if (mergeAdjacentText && textInTextBuffer) {
264             completeCurrentTextNode();
265         }
266 
267         if ((elementHandler != null) && (currentElement != null)) {
268             elementHandler.onEnd(elementStack);
269         }
270 
271         elementStack.popElement();
272         currentElement = elementStack.peekElement();
273     }
274 
275     public void characters(char[] ch, int start, int end) throws SAXException {
276         if (end == 0) {
277             return;
278         }
279 
280         if (currentElement != null) {
281             if (entity != null) {
282                 if (mergeAdjacentText && textInTextBuffer) {
283                     completeCurrentTextNode();
284                 }
285 
286                 currentElement.addEntity(entity, new String(ch, start, end));
287                 entity = null;
288             } else if (insideCDATASection) {
289                 if (mergeAdjacentText && textInTextBuffer) {
290                     completeCurrentTextNode();
291                 }
292 
293                 cdataText.append(new String(ch, start, end));
294             } else {
295                 if (mergeAdjacentText) {
296                     textBuffer.append(ch, start, end);
297                     textInTextBuffer = true;
298                 } else {
299                     currentElement.addText(new String(ch, start, end));
300                 }
301             }
302         }
303     }
304 
305     // ErrorHandler interface
306     // -------------------------------------------------------------------------
307 
308     /***
309      * This method is called when a warning occurs during the parsing of the
310      * document. This method does nothing.
311      * 
312      * @param exception
313      *            DOCUMENT ME!
314      * 
315      * @throws SAXException
316      *             DOCUMENT ME!
317      */
318     public void warning(SAXParseException exception) throws SAXException {
319         // ignore warnings by default
320     }
321 
322     /***
323      * This method is called when an error is detected during parsing such as a
324      * validation error. This method rethrows the exception
325      * 
326      * @param exception
327      *            DOCUMENT ME!
328      * 
329      * @throws SAXException
330      *             DOCUMENT ME!
331      */
332     public void error(SAXParseException exception) throws SAXException {
333         throw exception;
334     }
335 
336     /***
337      * This method is called when a fatal error occurs during parsing. This
338      * method rethrows the exception
339      * 
340      * @param exception
341      *            DOCUMENT ME!
342      * 
343      * @throws SAXException
344      *             DOCUMENT ME!
345      */
346     public void fatalError(SAXParseException exception) throws SAXException {
347         throw exception;
348     }
349 
350     // LexicalHandler interface
351     // -------------------------------------------------------------------------
352     public void startDTD(String name, String publicId, String systemId)
353             throws SAXException {
354         getDocument().addDocType(name, publicId, systemId);
355         insideDTDSection = true;
356         internalDTDsubset = true;
357     }
358 
359     public void endDTD() throws SAXException {
360         insideDTDSection = false;
361 
362         DocumentType docType = getDocument().getDocType();
363 
364         if (docType != null) {
365             if (internalDTDDeclarations != null) {
366                 docType.setInternalDeclarations(internalDTDDeclarations);
367             }
368 
369             if (externalDTDDeclarations != null) {
370                 docType.setExternalDeclarations(externalDTDDeclarations);
371             }
372         }
373 
374         internalDTDDeclarations = null;
375         externalDTDDeclarations = null;
376     }
377 
378     public void startEntity(String name) throws SAXException {
379         ++entityLevel;
380 
381         // Ignore DTD references
382         entity = null;
383 
384         if (!insideDTDSection) {
385             if (!isIgnorableEntity(name)) {
386                 entity = name;
387             }
388         }
389 
390         // internal DTD subsets can only appear outside of a
391         // startEntity/endEntity block
392         // see the startDTD method in
393         // http://dom4j.org/javadoc/org/xml/sax/ext/LexicalHandler.html
394         internalDTDsubset = false;
395     }
396 
397     public void endEntity(String name) throws SAXException {
398         --entityLevel;
399         entity = null;
400 
401         if (entityLevel == 0) {
402             internalDTDsubset = true;
403         }
404     }
405 
406     public void startCDATA() throws SAXException {
407         insideCDATASection = true;
408         cdataText = new StringBuffer();
409     }
410 
411     public void endCDATA() throws SAXException {
412         insideCDATASection = false;
413         currentElement.addCDATA(cdataText.toString());
414     }
415 
416     public void comment(char[] ch, int start, int end) throws SAXException {
417         if (!ignoreComments) {
418             if (mergeAdjacentText && textInTextBuffer) {
419                 completeCurrentTextNode();
420             }
421 
422             String text = new String(ch, start, end);
423 
424             if (!insideDTDSection && (text.length() > 0)) {
425                 if (currentElement != null) {
426                     currentElement.addComment(text);
427                 } else {
428                     getDocument().addComment(text);
429                 }
430             }
431         }
432     }
433 
434     // DeclHandler interface
435     // -------------------------------------------------------------------------
436 
437     /***
438      * Report an element type declaration.
439      * 
440      * <p>
441      * The content model will consist of the string "EMPTY", the string "ANY",
442      * or a parenthesised group, optionally followed by an occurrence indicator.
443      * The model will be normalized so that all parameter entities are fully
444      * resolved and all whitespace is removed,and will include the enclosing
445      * parentheses. Other normalization (such as removing redundant parentheses
446      * or simplifying occurrence indicators) is at the discretion of the parser.
447      * </p>
448      * 
449      * @param name
450      *            The element type name.
451      * @param model
452      *            The content model as a normalized string.
453      * 
454      * @exception SAXException
455      *                The application may raise an exception.
456      */
457     public void elementDecl(String name, String model) throws SAXException {
458         if (internalDTDsubset) {
459             if (includeInternalDTDDeclarations) {
460                 addDTDDeclaration(new ElementDecl(name, model));
461             }
462         } else {
463             if (includeExternalDTDDeclarations) {
464                 addExternalDTDDeclaration(new ElementDecl(name, model));
465             }
466         }
467     }
468 
469     /***
470      * Report an attribute type declaration.
471      * 
472      * <p>
473      * Only the effective (first) declaration for an attribute will be reported.
474      * The type will be one of the strings "CDATA", "ID", "IDREF", "IDREFS",
475      * "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", a parenthesized token group
476      * with the separator "|" and all whitespace removed, or the word "NOTATION"
477      * followed by a space followed by a parenthesized token group with all
478      * whitespace removed.
479      * </p>
480      * 
481      * <p>
482      * Any parameter entities in the attribute value will be expanded, but
483      * general entities will not.
484      * </p>
485      * 
486      * @param eName
487      *            The name of the associated element.
488      * @param aName
489      *            The name of the attribute.
490      * @param type
491      *            A string representing the attribute type.
492      * @param valueDefault
493      *            A string representing the attribute default ("#IMPLIED",
494      *            "#REQUIRED", or "#FIXED") or null if none of these applies.
495      * @param val
496      *            A string representing the attribute's default value, or null
497      *            if there is none.
498      * 
499      * @exception SAXException
500      *                The application may raise an exception.
501      */
502     public void attributeDecl(String eName, String aName, String type,
503             String valueDefault, String val) throws SAXException {
504         if (internalDTDsubset) {
505             if (includeInternalDTDDeclarations) {
506                 addDTDDeclaration(new AttributeDecl(eName, aName, type,
507                         valueDefault, val));
508             }
509         } else {
510             if (includeExternalDTDDeclarations) {
511                 addExternalDTDDeclaration(new AttributeDecl(eName, aName, type,
512                         valueDefault, val));
513             }
514         }
515     }
516 
517     /***
518      * Report an internal entity declaration.
519      * 
520      * <p>
521      * Only the effective (first) declaration for each entity will be reported.
522      * All parameter entities in the value will be expanded, but general
523      * entities will not.
524      * </p>
525      * 
526      * @param name
527      *            The name of the entity. If it is a parameter entity, the name
528      *            will begin with '%'.
529      * @param value
530      *            The replacement text of the entity.
531      * 
532      * @exception SAXException
533      *                The application may raise an exception.
534      * 
535      * @see #externalEntityDecl
536      * @see org.xml.sax.DTDHandler#unparsedEntityDecl
537      */
538     public void internalEntityDecl(String name, String value)
539             throws SAXException {
540         if (internalDTDsubset) {
541             if (includeInternalDTDDeclarations) {
542                 addDTDDeclaration(new InternalEntityDecl(name, value));
543             }
544         } else {
545             if (includeExternalDTDDeclarations) {
546                 addExternalDTDDeclaration(new InternalEntityDecl(name, value));
547             }
548         }
549     }
550 
551     /***
552      * Report a parsed external entity declaration.
553      * 
554      * <p>
555      * Only the effective (first) declaration for each entity will be reported.
556      * </p>
557      * 
558      * @param name
559      *            The name of the entity. If it is a parameter entity, the name
560      *            will begin with '%'.
561      * @param publicId
562      *            The declared public identifier of the entity, or null if none
563      *            was declared.
564      * @param sysId
565      *            The declared system identifier of the entity.
566      * 
567      * @exception SAXException
568      *                The application may raise an exception.
569      * 
570      * @see #internalEntityDecl
571      * @see org.xml.sax.DTDHandler#unparsedEntityDecl
572      */
573     public void externalEntityDecl(String name, String publicId, String sysId)
574             throws SAXException {
575         ExternalEntityDecl declaration = new ExternalEntityDecl(name, publicId,
576                 sysId);
577 
578         if (internalDTDsubset) {
579             if (includeInternalDTDDeclarations) {
580                 addDTDDeclaration(declaration);
581             }
582         } else {
583             if (includeExternalDTDDeclarations) {
584                 addExternalDTDDeclaration(declaration);
585             }
586         }
587     }
588 
589     // DTDHandler interface
590     // -------------------------------------------------------------------------
591 
592     /***
593      * Receive notification of a notation declaration event.
594      * 
595      * <p>
596      * It is up to the application to record the notation for later reference,
597      * if necessary.
598      * </p>
599      * 
600      * <p>
601      * At least one of publicId and systemId must be non-null. If a system
602      * identifier is present, and it is a URL, the SAX parser must resolve it
603      * fully before passing it to the application through this event.
604      * </p>
605      * 
606      * <p>
607      * There is no guarantee that the notation declaration will be reported
608      * before any unparsed entities that use it.
609      * </p>
610      * 
611      * @param name
612      *            The notation name.
613      * @param publicId
614      *            The notation's public identifier, or null if none was given.
615      * @param systemId
616      *            The notation's system identifier, or null if none was given.
617      * 
618      * @exception SAXException
619      *                Any SAX exception, possibly wrapping another exception.
620      * 
621      * @see #unparsedEntityDecl
622      * @see org.xml.sax.AttributeList
623      */
624     public void notationDecl(String name, String publicId, String systemId)
625             throws SAXException {
626         // #### not supported yet!
627     }
628 
629     /***
630      * Receive notification of an unparsed entity declaration event.
631      * 
632      * <p>
633      * Note that the notation name corresponds to a notation reported by the
634      * {@link #notationDecl notationDecl}event. It is up to the application to
635      * record the entity for later reference, if necessary.
636      * </p>
637      * 
638      * <p>
639      * If the system identifier is a URL, the parser must resolve it fully
640      * before passing it to the application.
641      * </p>
642      * 
643      * @param name
644      *            The unparsed entity's name.
645      * @param publicId
646      *            The entity's public identifier, or null if none was given.
647      * @param systemId
648      *            The entity's system identifier.
649      * @param notationName
650      *            The name of the associated notation.
651      * 
652      * @exception SAXException
653      *                Any SAX exception, possibly wrapping another exception.
654      * 
655      * @see #notationDecl
656      * @see org.xml.sax.AttributeList
657      */
658     public void unparsedEntityDecl(String name, String publicId,
659             String systemId, String notationName) throws SAXException {
660         // #### not supported yet!
661     }
662 
663     // Properties
664     // -------------------------------------------------------------------------
665     public ElementStack getElementStack() {
666         return elementStack;
667     }
668 
669     public void setElementStack(ElementStack elementStack) {
670         this.elementStack = elementStack;
671     }
672 
673     public EntityResolver getEntityResolver() {
674         return entityResolver;
675     }
676 
677     public void setEntityResolver(EntityResolver entityResolver) {
678         this.entityResolver = entityResolver;
679     }
680 
681     public InputSource getInputSource() {
682         return inputSource;
683     }
684 
685     public void setInputSource(InputSource inputSource) {
686         this.inputSource = inputSource;
687     }
688 
689     /***
690      * DOCUMENT ME!
691      * 
692      * @return whether internal DTD declarations should be expanded into the
693      *         DocumentType object or not.
694      */
695     public boolean isIncludeInternalDTDDeclarations() {
696         return includeInternalDTDDeclarations;
697     }
698 
699     /***
700      * Sets whether internal DTD declarations should be expanded into the
701      * DocumentType object or not.
702      * 
703      * @param include
704      *            whether or not DTD declarations should be expanded and
705      *            included into the DocumentType object.
706      */
707     public void setIncludeInternalDTDDeclarations(boolean include) {
708         this.includeInternalDTDDeclarations = include;
709     }
710 
711     /***
712      * DOCUMENT ME!
713      * 
714      * @return whether external DTD declarations should be expanded into the
715      *         DocumentType object or not.
716      */
717     public boolean isIncludeExternalDTDDeclarations() {
718         return includeExternalDTDDeclarations;
719     }
720 
721     /***
722      * Sets whether DTD external declarations should be expanded into the
723      * DocumentType object or not.
724      * 
725      * @param include
726      *            whether or not DTD declarations should be expanded and
727      *            included into the DocumentType object.
728      */
729     public void setIncludeExternalDTDDeclarations(boolean include) {
730         this.includeExternalDTDDeclarations = include;
731     }
732 
733     /***
734      * Returns whether adjacent text nodes should be merged together.
735      * 
736      * @return Value of property mergeAdjacentText.
737      */
738     public boolean isMergeAdjacentText() {
739         return mergeAdjacentText;
740     }
741 
742     /***
743      * Sets whether or not adjacent text nodes should be merged together when
744      * parsing.
745      * 
746      * @param mergeAdjacentText
747      *            New value of property mergeAdjacentText.
748      */
749     public void setMergeAdjacentText(boolean mergeAdjacentText) {
750         this.mergeAdjacentText = mergeAdjacentText;
751     }
752 
753     /***
754      * Sets whether whitespace between element start and end tags should be
755      * ignored
756      * 
757      * @return Value of property stripWhitespaceText.
758      */
759     public boolean isStripWhitespaceText() {
760         return stripWhitespaceText;
761     }
762 
763     /***
764      * Sets whether whitespace between element start and end tags should be
765      * ignored.
766      * 
767      * @param stripWhitespaceText
768      *            New value of property stripWhitespaceText.
769      */
770     public void setStripWhitespaceText(boolean stripWhitespaceText) {
771         this.stripWhitespaceText = stripWhitespaceText;
772     }
773 
774     /***
775      * Returns whether we should ignore comments or not.
776      * 
777      * @return boolean
778      */
779     public boolean isIgnoreComments() {
780         return ignoreComments;
781     }
782 
783     /***
784      * Sets whether we should ignore comments or not.
785      * 
786      * @param ignoreComments
787      *            whether we should ignore comments or not.
788      */
789     public void setIgnoreComments(boolean ignoreComments) {
790         this.ignoreComments = ignoreComments;
791     }
792 
793     // Implementation methods
794     // -------------------------------------------------------------------------
795 
796     /***
797      * If the current text buffer contains any text then create a new text node
798      * with it and add it to the current element
799      */
800     protected void completeCurrentTextNode() {
801         if (stripWhitespaceText) {
802             boolean whitespace = true;
803 
804             for (int i = 0, size = textBuffer.length(); i < size; i++) {
805                 if (!Character.isWhitespace(textBuffer.charAt(i))) {
806                     whitespace = false;
807 
808                     break;
809                 }
810             }
811 
812             if (!whitespace) {
813                 currentElement.addText(textBuffer.toString());
814             }
815         } else {
816             currentElement.addText(textBuffer.toString());
817         }
818 
819         textBuffer.setLength(0);
820         textInTextBuffer = false;
821     }
822 
823     /***
824      * DOCUMENT ME!
825      * 
826      * @return the current document
827      */
828     protected Document createDocument() {
829         String encoding = getEncoding();
830         Document doc = documentFactory.createDocument(encoding);
831 
832         // set the EntityResolver
833         doc.setEntityResolver(entityResolver);
834 
835         if (inputSource != null) {
836             doc.setName(inputSource.getSystemId());
837         }
838 
839         return doc;
840     }
841 
842     private String getEncoding() {
843         if (locator == null) {
844             return null;
845         }
846 
847         // use reflection to avoid dependency on Locator2
848         // or other locator implemenations.
849         try {
850             Method m = locator.getClass().getMethod("getEncoding",
851                     new Class[] {});
852 
853             if (m != null) {
854                 return (String) m.invoke(locator, null);
855             }
856         } catch (Exception e) {
857             // do nothing
858         }
859 
860         // couldn't determine encoding, returning null...
861         return null;
862     }
863 
864     /***
865      * a Strategy Method to determine if a given entity name is ignorable
866      * 
867      * @param name
868      *            DOCUMENT ME!
869      * 
870      * @return DOCUMENT ME!
871      */
872     protected boolean isIgnorableEntity(String name) {
873         return "amp".equals(name) || "apos".equals(name) || "gt".equals(name)
874                 || "lt".equals(name) || "quot".equals(name);
875     }
876 
877     /***
878      * Add all namespaces declared before the startElement() SAX event to the
879      * current element so that they are available to child elements and
880      * attributes
881      * 
882      * @param element
883      *            DOCUMENT ME!
884      */
885     protected void addDeclaredNamespaces(Element element) {
886         Namespace elementNamespace = element.getNamespace();
887 
888         for (int size = namespaceStack.size(); declaredNamespaceIndex < size; 
889                 declaredNamespaceIndex++) {
890             Namespace namespace = namespaceStack
891                     .getNamespace(declaredNamespaceIndex);
892 
893             // if ( namespace != elementNamespace ) {
894             element.add(namespace);
895 
896             // }
897         }
898     }
899 
900     /***
901      * Add all the attributes to the given elements
902      * 
903      * @param element
904      *            DOCUMENT ME!
905      * @param attributes
906      *            DOCUMENT ME!
907      */
908     protected void addAttributes(Element element, Attributes attributes) {
909         // XXXX: as an optimisation, we could deduce this value from the current
910         // SAX parser settings, the SAX namespaces-prefixes feature
911         boolean noNamespaceAttributes = false;
912 
913         if (element instanceof AbstractElement) {
914             // optimised method
915             AbstractElement baseElement = (AbstractElement) element;
916             baseElement.setAttributes(attributes, namespaceStack,
917                     noNamespaceAttributes);
918         } else {
919             int size = attributes.getLength();
920 
921             for (int i = 0; i < size; i++) {
922                 String attributeQName = attributes.getQName(i);
923 
924                 if (noNamespaceAttributes
925                         || !attributeQName.startsWith("xmlns")) {
926                     String attributeURI = attributes.getURI(i);
927                     String attributeLocalName = attributes.getLocalName(i);
928                     String attributeValue = attributes.getValue(i);
929 
930                     QName qName = namespaceStack.getAttributeQName(
931                             attributeURI, attributeLocalName, attributeQName);
932                     element.addAttribute(qName, attributeValue);
933                 }
934             }
935         }
936     }
937 
938     /***
939      * Adds an internal DTD declaration to the list of declarations
940      * 
941      * @param declaration
942      *            DOCUMENT ME!
943      */
944     protected void addDTDDeclaration(Object declaration) {
945         if (internalDTDDeclarations == null) {
946             internalDTDDeclarations = new ArrayList();
947         }
948 
949         internalDTDDeclarations.add(declaration);
950     }
951 
952     /***
953      * Adds an external DTD declaration to the list of declarations
954      * 
955      * @param declaration
956      *            DOCUMENT ME!
957      */
958     protected void addExternalDTDDeclaration(Object declaration) {
959         if (externalDTDDeclarations == null) {
960             externalDTDDeclarations = new ArrayList();
961         }
962 
963         externalDTDDeclarations.add(declaration);
964     }
965 
966     protected ElementStack createElementStack() {
967         return new ElementStack();
968     }
969 }
970 
971 /*
972  * Redistribution and use of this software and associated documentation
973  * ("Software"), with or without modification, are permitted provided that the
974  * following conditions are met:
975  * 
976  * 1. Redistributions of source code must retain copyright statements and
977  * notices. Redistributions must also contain a copy of this document.
978  * 
979  * 2. Redistributions in binary form must reproduce the above copyright notice,
980  * this list of conditions and the following disclaimer in the documentation
981  * and/or other materials provided with the distribution.
982  * 
983  * 3. The name "DOM4J" must not be used to endorse or promote products derived
984  * from this Software without prior written permission of MetaStuff, Ltd. For
985  * written permission, please contact dom4j-info@metastuff.com.
986  * 
987  * 4. Products derived from this Software may not be called "DOM4J" nor may
988  * "DOM4J" appear in their names without prior written permission of MetaStuff,
989  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
990  * 
991  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
992  * 
993  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
994  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
995  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
996  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
997  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
998  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
999  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
1000  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
1001  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
1002  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
1003  * POSSIBILITY OF SUCH DAMAGE.
1004  * 
1005  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
1006  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/STAXEventReader.html0000644000175000017500000016106010242117706021771 0ustar ebourgebourg STAXEventReader xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.io.InputStream;
11  import java.io.Reader;
12  import java.util.Iterator;
13  
14  import javax.xml.namespace.QName;
15  import javax.xml.stream.XMLEventReader;
16  import javax.xml.stream.XMLInputFactory;
17  import javax.xml.stream.XMLStreamConstants;
18  import javax.xml.stream.XMLStreamException;
19  import javax.xml.stream.events.Attribute;
20  import javax.xml.stream.events.Characters;
21  import javax.xml.stream.events.Comment;
22  import javax.xml.stream.events.EndElement;
23  import javax.xml.stream.events.EntityReference;
24  import javax.xml.stream.events.Namespace;
25  import javax.xml.stream.events.ProcessingInstruction;
26  import javax.xml.stream.events.StartDocument;
27  import javax.xml.stream.events.StartElement;
28  import javax.xml.stream.events.XMLEvent;
29  
30  import org.dom4j.CharacterData;
31  import org.dom4j.Document;
32  import org.dom4j.DocumentFactory;
33  import org.dom4j.Element;
34  import org.dom4j.Entity;
35  import org.dom4j.Node;
36  
37  /***
38   * Reads a DOM4J {@link Document}, as well as other {@link Node}s, from a StAX
39   * {@link XMLEventReader}.
40   * 
41   * @author Christian Niles
42   */
43  public class STAXEventReader {
44      /*** Reference to the DocumentFactory used to build DOM4J nodes. */
45      private DocumentFactory factory;
46  
47      /*** A StAX input factory, used to construct streams from IO streams. */
48      private XMLInputFactory inputFactory = XMLInputFactory.newInstance();
49  
50      /***
51       * Constructs a default <code>STAXEventReader</code> instance with a
52       * default {@link DocumentFactory}.
53       */
54      public STAXEventReader() {
55          this.factory = DocumentFactory.getInstance();
56      }
57  
58      /***
59       * Constructs a <code>STAXEventReader</code> instance that uses the
60       * specified {@link DocumentFactory}to construct DOM4J {@link Node}s.
61       * 
62       * @param factory
63       *            The DocumentFactory to use when constructing DOM4J nodes, or
64       *            <code>null</code> if a default should be used.
65       */
66      public STAXEventReader(DocumentFactory factory) {
67          if (factory != null) {
68              this.factory = factory;
69          } else {
70              this.factory = DocumentFactory.getInstance();
71          }
72      }
73  
74      /***
75       * Sets the DocumentFactory to be used when constructing DOM4J nodes.
76       * 
77       * @param documentFactory
78       *            The DocumentFactory to use when constructing DOM4J nodes, or
79       *            <code>null</code> if a default should be used.
80       */
81      public void setDocumentFactory(DocumentFactory documentFactory) {
82          if (documentFactory != null) {
83              this.factory = documentFactory;
84          } else {
85              this.factory = DocumentFactory.getInstance();
86          }
87      }
88  
89      /***
90       * Constructs a StAX event stream from the provided I/O stream and reads a
91       * DOM4J document from it.
92       * 
93       * @param is
94       *            The I/O stream from which the Document will be read.
95       * 
96       * @return The Document that was read from the stream.
97       * 
98       * @throws XMLStreamException
99       *             If an error occurs reading content from the stream.
100      */
101     public Document readDocument(InputStream is) throws XMLStreamException {
102         return readDocument(is, null);
103     }
104 
105     /***
106      * Constructs a StAX event stream from the provided I/O character stream and
107      * reads a DOM4J document from it.
108      * 
109      * @param reader
110      *            The character stream from which the Document will be read.
111      * 
112      * @return The Document that was read from the stream.
113      * 
114      * @throws XMLStreamException
115      *             If an error occurs reading content from the stream.
116      */
117     public Document readDocument(Reader reader) throws XMLStreamException {
118         return readDocument(reader, null);
119     }
120 
121     /***
122      * Constructs a StAX event stream from the provided I/O stream and reads a
123      * DOM4J document from it.
124      * 
125      * @param is
126      *            The I/O stream from which the Document will be read.
127      * @param systemId
128      *            A system id used to resolve entities.
129      * 
130      * @return The Document that was read from the stream.
131      * 
132      * @throws XMLStreamException
133      *             If an error occurs reading content from the stream.
134      */
135     public Document readDocument(InputStream is, String systemId)
136             throws XMLStreamException {
137         XMLEventReader eventReader = inputFactory.createXMLEventReader(
138                 systemId, is);
139 
140         try {
141             return readDocument(eventReader);
142         } finally {
143             eventReader.close();
144         }
145     }
146 
147     /***
148      * Constructs a StAX event stream from the provided I/O character stream and
149      * reads a DOM4J document from it.
150      * 
151      * @param reader
152      *            The character stream from which the Document will be read.
153      * @param systemId
154      *            A system id used to resolve entities.
155      * 
156      * @return The Document that was read from the stream.
157      * 
158      * @throws XMLStreamException
159      *             If an error occurs reading content from the stream.
160      */
161     public Document readDocument(Reader reader, String systemId)
162             throws XMLStreamException {
163         XMLEventReader eventReader = inputFactory.createXMLEventReader(
164                 systemId, reader);
165 
166         try {
167             return readDocument(eventReader);
168         } finally {
169             eventReader.close();
170         }
171     }
172 
173     /***
174      * Reads a {@link Node}from the event stream. If the next event is a
175      * {@link StartElement}, all events until the closing {@link EndElement}
176      * will be read, and the resulting nodes will be added to the returned
177      * {@link Element}.
178      * 
179      * <p>
180      * <strong>Pre-Conditions </strong>: The stream must be positioned before an
181      * event other than an <code>EndElement</code>,<code>EndDocument</code>,
182      * or any DTD-related events, which are not currently supported.
183      * </p>
184      * 
185      * @param reader
186      *            The reader from which events will be read.
187      * 
188      * @return A DOM4J {@link Node}constructed from the read events.
189      * 
190      * @throws XMLStreamException
191      *             If an error occurs reading from the stream, or the stream was
192      *             positioned before an unsupported event.
193      */
194     public Node readNode(XMLEventReader reader) throws XMLStreamException {
195         XMLEvent event = reader.peek();
196 
197         if (event.isStartElement()) {
198             return readElement(reader);
199         } else if (event.isCharacters()) {
200             return readCharacters(reader);
201         } else if (event.isStartDocument()) {
202             return readDocument(reader);
203         } else if (event.isProcessingInstruction()) {
204             return readProcessingInstruction(reader);
205         } else if (event.isEntityReference()) {
206             return readEntityReference(reader);
207         } else if (event.isAttribute()) {
208             return readAttribute(reader);
209         } else if (event.isNamespace()) {
210             return readNamespace(reader);
211         } else {
212             throw new XMLStreamException("Unsupported event: " + event);
213         }
214     }
215 
216     /***
217      * Reads a DOM4J {@link Document}from the provided stream. The stream
218      * should be positioned at the start of a document, or before a {@link
219      * StartElement} event.
220      * 
221      * @param reader
222      *            The event stream from which to read the {@link Document}.
223      * 
224      * @return The {@link Document}that was read from the stream.
225      * 
226      * @throws XMLStreamException
227      *             If an error occurs reading events from the stream.
228      */
229     public Document readDocument(XMLEventReader reader)
230             throws XMLStreamException {
231         Document doc = null;
232 
233         while (reader.hasNext()) {
234             XMLEvent nextEvent = reader.peek();
235             int type = nextEvent.getEventType();
236 
237             switch (type) {
238                 case XMLStreamConstants.START_DOCUMENT:
239 
240                     StartDocument event = (StartDocument) reader.nextEvent();
241 
242                     if (doc == null) {
243                         // create document
244                         if (event.encodingSet()) {
245                             String encodingScheme = event
246                                     .getCharacterEncodingScheme();
247                             doc = factory.createDocument(encodingScheme);
248                         } else {
249                             doc = factory.createDocument();
250                         }
251                     } else {
252                         // duplicate or misplaced xml declaration
253                         String msg = "Unexpected StartDocument event";
254                         throw new XMLStreamException(msg, event.getLocation());
255                     }
256 
257                     break;
258 
259                 case XMLStreamConstants.END_DOCUMENT:
260                 case XMLStreamConstants.SPACE:
261                 case XMLStreamConstants.CHARACTERS:
262 
263                     // skip end document and space outside the root element
264                     reader.nextEvent();
265 
266                     break;
267 
268                 default:
269 
270                     if (doc == null) {
271                         // create document
272                         doc = factory.createDocument();
273                     }
274 
275                     Node n = readNode(reader);
276                     doc.add(n);
277             }
278         }
279 
280         return doc;
281     }
282 
283     /***
284      * Reads a DOM4J Element from the provided event stream. The stream must be
285      * positioned before an {@link StartElement}event. In addition to the
286      * initial start event, all events up to and including the closing {@link
287      * EndElement} will be read, and included with the returned element.
288      * 
289      * @param eventReader
290      *            The event stream from which to read the Element.
291      * 
292      * @return The Element that was read from the stream.
293      * 
294      * @throws XMLStreamException
295      *             If an error occured reading events from the stream, or the
296      *             stream was not positioned before a {@linkStartElement}event.
297      */
298     public Element readElement(XMLEventReader eventReader)
299             throws XMLStreamException {
300         XMLEvent event = eventReader.peek();
301 
302         if (event.isStartElement()) {
303             // advance the reader and get the StartElement event
304             StartElement startTag = eventReader.nextEvent().asStartElement();
305             Element elem = createElement(startTag);
306 
307             // read element content
308             while (true) {
309                 if (!eventReader.hasNext()) {
310                     String msg = "Unexpected end of stream while reading"
311                             + " element content";
312                     throw new XMLStreamException(msg);
313                 }
314 
315                 XMLEvent nextEvent = eventReader.peek();
316 
317                 if (nextEvent.isEndElement()) {
318                     EndElement endElem = eventReader.nextEvent().asEndElement();
319 
320                     if (!endElem.getName().equals(startTag.getName())) {
321                         throw new XMLStreamException("Expected "
322                                 + startTag.getName() + " end-tag, but found"
323                                 + endElem.getName());
324                     }
325 
326                     break;
327                 }
328 
329                 Node child = readNode(eventReader);
330                 elem.add(child);
331             }
332 
333             return elem;
334         } else {
335             throw new XMLStreamException("Expected Element event, found: "
336                     + event);
337         }
338     }
339 
340     /***
341      * Constructs a DOM4J Attribute from the provided event stream. The stream
342      * must be positioned before an {@link Attribute}event.
343      * 
344      * @param reader
345      *            The event stream from which to read the Attribute.
346      * 
347      * @return The Attribute that was read from the stream.
348      * 
349      * @throws XMLStreamException
350      *             If an error occured reading events from the stream, or the
351      *             stream was not positioned before an {@linkAttribute}event.
352      */
353     public org.dom4j.Attribute readAttribute(XMLEventReader reader)
354             throws XMLStreamException {
355         XMLEvent event = reader.peek();
356 
357         if (event.isAttribute()) {
358             Attribute attr = (Attribute) reader.nextEvent();
359 
360             return createAttribute(null, attr);
361         } else {
362             throw new XMLStreamException("Expected Attribute event, found: "
363                     + event);
364         }
365     }
366 
367     /***
368      * Constructs a DOM4J Namespace from the provided event stream. The stream
369      * must be positioned before a {@link Namespace}event.
370      * 
371      * @param reader
372      *            The event stream from which to read the Namespace.
373      * 
374      * @return The Namespace that was read from the stream.
375      * 
376      * @throws XMLStreamException
377      *             If an error occured reading events from the stream, or the
378      *             stream was not positioned before a {@linkNamespace}event.
379      */
380     public org.dom4j.Namespace readNamespace(XMLEventReader reader)
381             throws XMLStreamException {
382         XMLEvent event = reader.peek();
383 
384         if (event.isNamespace()) {
385             Namespace ns = (Namespace) reader.nextEvent();
386 
387             return createNamespace(ns);
388         } else {
389             throw new XMLStreamException("Expected Namespace event, found: "
390                     + event);
391         }
392     }
393 
394     /***
395      * Constructs a DOM4J Text or CDATA section from the provided event stream.
396      * The stream must be positioned before a {@link Characters}event.
397      * 
398      * @param reader
399      *            The event stream from which to read the Text or CDATA.
400      * 
401      * @return The Text or CDATA that was read from the stream.
402      * 
403      * @throws XMLStreamException
404      *             If an error occured reading events from the stream, or the
405      *             stream was not positioned before a {@linkCharacters}event.
406      */
407     public CharacterData readCharacters(XMLEventReader reader)
408             throws XMLStreamException {
409         XMLEvent event = reader.peek();
410 
411         if (event.isCharacters()) {
412             Characters characters = reader.nextEvent().asCharacters();
413 
414             return createCharacterData(characters);
415         } else {
416             throw new XMLStreamException("Expected Characters event, found: "
417                     + event);
418         }
419     }
420 
421     /***
422      * Constructs a DOM4J Comment from the provided event stream. The stream
423      * must be positioned before a {@link Comment}event.
424      * 
425      * @param reader
426      *            The event stream from which to read the Comment.
427      * 
428      * @return The Comment that was read from the stream.
429      * 
430      * @throws XMLStreamException
431      *             If an error occured reading events from the stream, or the
432      *             stream was not positioned before a {@linkComment}event.
433      */
434     public org.dom4j.Comment readComment(XMLEventReader reader)
435             throws XMLStreamException {
436         XMLEvent event = reader.peek();
437 
438         if (event instanceof Comment) {
439             return createComment((Comment) reader.nextEvent());
440         } else {
441             throw new XMLStreamException("Expected Comment event, found: "
442                     + event);
443         }
444     }
445 
446     /***
447      * Constructs a DOM4J Entity from the provided event stream. The stream must
448      * be positioned before an {@link EntityReference}event.
449      * 
450      * @param reader
451      *            The event stream from which to read the {@link
452      *            EntityReference}.
453      * 
454      * @return The {@link org.dom4j.Entity}that was read from the stream.
455      * 
456      * @throws XMLStreamException
457      *             If an error occured reading events from the stream, or the
458      *             stream was not positioned before an {@linkEntityReference}
459      *             event.
460      */
461     public Entity readEntityReference(XMLEventReader reader)
462             throws XMLStreamException {
463         XMLEvent event = reader.peek();
464 
465         if (event.isEntityReference()) {
466             EntityReference entityRef = (EntityReference) reader.nextEvent();
467 
468             return createEntity(entityRef);
469         } else {
470             throw new XMLStreamException("Expected EntityRef event, found: "
471                     + event);
472         }
473     }
474 
475     /***
476      * Constructs a DOM4J ProcessingInstruction from the provided event stream.
477      * The stream must be positioned before a {@link ProcessingInstruction}
478      * event.
479      * 
480      * @param reader
481      *            The event stream from which to read the ProcessingInstruction.
482      * 
483      * @return The ProcessingInstruction that was read from the stream.
484      * 
485      * @throws XMLStreamException
486      *             If an error occured reading events from the stream, or the
487      *             stream was not positioned before a {@link
488      *             ProcessingInstruction} event.
489      */
490     public org.dom4j.ProcessingInstruction readProcessingInstruction(
491             XMLEventReader reader) throws XMLStreamException {
492         XMLEvent event = reader.peek();
493 
494         if (event.isProcessingInstruction()) {
495             ProcessingInstruction pi = (ProcessingInstruction) reader
496                     .nextEvent();
497 
498             return createProcessingInstruction(pi);
499         } else {
500             throw new XMLStreamException("Expected PI event, found: " + event);
501         }
502     }
503 
504     /***
505      * Constructs a new DOM4J Element from the provided StartElement event. All
506      * attributes and namespaces will be added to the returned element.
507      * 
508      * @param startEvent
509      *            The StartElement event from which to construct the new DOM4J
510      *            Element.
511      * 
512      * @return The Element constructed from the provided StartElement event.
513      */
514     public Element createElement(StartElement startEvent) {
515         QName qname = startEvent.getName();
516         org.dom4j.QName elemName = createQName(qname);
517 
518         Element elem = factory.createElement(elemName);
519 
520         // create attributes
521         for (Iterator i = startEvent.getAttributes(); i.hasNext();) {
522             Attribute attr = (Attribute) i.next();
523             elem.addAttribute(createQName(attr.getName()), attr.getValue());
524         }
525 
526         // create namespaces
527         for (Iterator i = startEvent.getNamespaces(); i.hasNext();) {
528             Namespace ns = (Namespace) i.next();
529             elem.addNamespace(ns.getPrefix(), ns.getNamespaceURI());
530         }
531 
532         return elem;
533     }
534 
535     /***
536      * Constructs a new DOM4J Attribute from the provided StAX Attribute event.
537      * 
538      * @param elem
539      *            DOCUMENT ME!
540      * @param attr
541      *            The Attribute event from which to construct the new DOM4J
542      *            Attribute.
543      * 
544      * @return The Attribute constructed from the provided Attribute event.
545      */
546     public org.dom4j.Attribute createAttribute(Element elem, Attribute attr) {
547         return factory.createAttribute(elem, createQName(attr.getName()), attr
548                 .getValue());
549     }
550 
551     /***
552      * Constructs a new DOM4J Namespace from the provided StAX Namespace event.
553      * 
554      * @param ns
555      *            The Namespace event from which to construct the new DOM4J
556      *            Namespace.
557      * 
558      * @return The Namespace constructed from the provided Namespace event.
559      */
560     public org.dom4j.Namespace createNamespace(Namespace ns) {
561         return factory.createNamespace(ns.getPrefix(), ns.getNamespaceURI());
562     }
563 
564     /***
565      * Constructs a new DOM4J Text or CDATA object from the provided Characters
566      * event.
567      * 
568      * @param characters
569      *            The Characters event from which to construct the new DOM4J
570      *            Text or CDATA object.
571      * 
572      * @return The Text or CDATA object constructed from the provided Characters
573      *         event.
574      */
575     public CharacterData createCharacterData(Characters characters) {
576         String data = characters.getData();
577 
578         if (characters.isCData()) {
579             return factory.createCDATA(data);
580         } else {
581             return factory.createText(data);
582         }
583     }
584 
585     /***
586      * Constructs a new DOM4J Comment from the provided StAX Comment event.
587      * 
588      * @param comment
589      *            The Comment event from which to construct the new DOM4J
590      *            Comment.
591      * 
592      * @return The Comment constructed from the provided Comment event.
593      */
594     public org.dom4j.Comment createComment(Comment comment) {
595         return factory.createComment(comment.getText());
596     }
597 
598     /***
599      * Constructs a new DOM4J Entity from the provided StAX EntityReference
600      * event.
601      * 
602      * @param entityRef
603      *            The EntityReference event from which to construct the new
604      *            DOM4J Entity.
605      * 
606      * @return The Entity constructed from the provided EntityReference event.
607      */
608     public org.dom4j.Entity createEntity(EntityReference entityRef) {
609         return factory.createEntity(entityRef.getName(), entityRef
610                 .getDeclaration().getReplacementText());
611     }
612 
613     /***
614      * Constructs a new DOM4J ProcessingInstruction from the provided StAX
615      * ProcessingInstruction event.
616      * 
617      * @param pi
618      *            The ProcessingInstruction event from which to construct the
619      *            new DOM4J ProcessingInstruction.
620      * 
621      * @return The ProcessingInstruction constructed from the provided
622      *         ProcessingInstruction event.
623      */
624     public org.dom4j.ProcessingInstruction createProcessingInstruction(
625             ProcessingInstruction pi) {
626         return factory
627                 .createProcessingInstruction(pi.getTarget(), pi.getData());
628     }
629 
630     /***
631      * Constructs a new DOM4J QName from the provided JAXP QName.
632      * 
633      * @param qname
634      *            The JAXP QName from which to create a DOM4J QName.
635      * 
636      * @return The newly constructed DOM4J QName.
637      */
638     public org.dom4j.QName createQName(QName qname) {
639         return factory.createQName(qname.getLocalPart(), qname.getPrefix(),
640                 qname.getNamespaceURI());
641     }
642 }
643 
644 /*
645  * Redistribution and use of this software and associated documentation
646  * ("Software"), with or without modification, are permitted provided that the
647  * following conditions are met:
648  * 
649  * 1. Redistributions of source code must retain copyright statements and
650  * notices. Redistributions must also contain a copy of this document.
651  * 
652  * 2. Redistributions in binary form must reproduce the above copyright notice,
653  * this list of conditions and the following disclaimer in the documentation
654  * and/or other materials provided with the distribution.
655  * 
656  * 3. The name "DOM4J" must not be used to endorse or promote products derived
657  * from this Software without prior written permission of MetaStuff, Ltd. For
658  * written permission, please contact dom4j-info@metastuff.com.
659  * 
660  * 4. Products derived from this Software may not be called "DOM4J" nor may
661  * "DOM4J" appear in their names without prior written permission of MetaStuff,
662  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
663  * 
664  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
665  * 
666  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
667  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
668  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
669  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
670  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
671  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
672  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
673  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
674  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
675  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
676  * POSSIBILITY OF SUCH DAMAGE.
677  * 
678  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
679  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/XPPReader.html0000644000175000017500000011624210242117725020662 0ustar ebourgebourg XPPReader xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.io.BufferedReader;
11  import java.io.File;
12  import java.io.FileReader;
13  import java.io.IOException;
14  import java.io.InputStream;
15  import java.io.InputStreamReader;
16  import java.io.Reader;
17  import java.net.URL;
18  
19  import org.dom4j.Document;
20  import org.dom4j.DocumentException;
21  import org.dom4j.DocumentFactory;
22  import org.dom4j.Element;
23  import org.dom4j.ElementHandler;
24  import org.dom4j.xpp.ProxyXmlStartTag;
25  
26  import org.gjt.xpp.XmlEndTag;
27  import org.gjt.xpp.XmlPullParser;
28  import org.gjt.xpp.XmlPullParserException;
29  import org.gjt.xpp.XmlPullParserFactory;
30  
31  /***
32   * <p>
33   * <code>XPPReader</code> is a Reader of DOM4J documents that uses the fast <a
34   * href="http://www.extreme.indiana.edu/soap/xpp/">XML Pull Parser 2.x </a>. It
35   * does not currently support comments, CDATA or ProcessingInstructions or
36   * validation but it is very fast for use in SOAP style environments.
37   * </p>
38   * 
39   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
40   * @version $Revision: 1.7 $
41   */
42  public class XPPReader {
43      /*** <code>DocumentFactory</code> used to create new document objects */
44      private DocumentFactory factory;
45  
46      /*** <code>XmlPullParser</code> used to parse XML */
47      private XmlPullParser xppParser;
48  
49      /*** <code>XmlPullParser</code> used to parse XML */
50      private XmlPullParserFactory xppFactory;
51  
52      /*** DispatchHandler to call when each <code>Element</code> is encountered */
53      private DispatchHandler dispatchHandler;
54  
55      public XPPReader() {
56      }
57  
58      public XPPReader(DocumentFactory factory) {
59          this.factory = factory;
60      }
61  
62      /***
63       * <p>
64       * Reads a Document from the given <code>File</code>
65       * </p>
66       * 
67       * @param file
68       *            is the <code>File</code> to read from.
69       * 
70       * @return the newly created Document instance
71       * 
72       * @throws DocumentException
73       *             if an error occurs during parsing.
74       * @throws IOException
75       *             if a URL could not be made for the given File
76       * @throws XmlPullParserException
77       *             DOCUMENT ME!
78       */
79      public Document read(File file) throws DocumentException, IOException,
80              XmlPullParserException {
81          String systemID = file.getAbsolutePath();
82  
83          return read(new BufferedReader(new FileReader(file)), systemID);
84      }
85  
86      /***
87       * <p>
88       * Reads a Document from the given <code>URL</code>
89       * </p>
90       * 
91       * @param url
92       *            <code>URL</code> to read from.
93       * 
94       * @return the newly created Document instance
95       * 
96       * @throws DocumentException
97       *             if an error occurs during parsing.
98       * @throws IOException
99       *             DOCUMENT ME!
100      * @throws XmlPullParserException
101      *             DOCUMENT ME!
102      */
103     public Document read(URL url) throws DocumentException, IOException,
104             XmlPullParserException {
105         String systemID = url.toExternalForm();
106 
107         return read(createReader(url.openStream()), systemID);
108     }
109 
110     /***
111      * <p>
112      * Reads a Document from the given URL or filename.
113      * </p>
114      * 
115      * <p>
116      * If the systemID contains a <code>':'</code> character then it is
117      * assumed to be a URL otherwise its assumed to be a file name. If you want
118      * finer grained control over this mechansim then please explicitly pass in
119      * either a {@link URL}or a {@link File}instance instead of a {@link
120      * String} to denote the source of the document.
121      * </p>
122      * 
123      * @param systemID
124      *            is a URL for a document or a file name.
125      * 
126      * @return the newly created Document instance
127      * 
128      * @throws DocumentException
129      *             if an error occurs during parsing.
130      * @throws IOException
131      *             if a URL could not be made for the given File
132      * @throws XmlPullParserException
133      *             DOCUMENT ME!
134      */
135     public Document read(String systemID) throws DocumentException,
136             IOException, XmlPullParserException {
137         if (systemID.indexOf(':') >= 0) {
138             // lets assume its a URL
139             return read(new URL(systemID));
140         } else {
141             // lets assume that we are given a file name
142             return read(new File(systemID));
143         }
144     }
145 
146     /***
147      * <p>
148      * Reads a Document from the given stream
149      * </p>
150      * 
151      * @param in
152      *            <code>InputStream</code> to read from.
153      * 
154      * @return the newly created Document instance
155      * 
156      * @throws DocumentException
157      *             if an error occurs during parsing.
158      * @throws IOException
159      *             DOCUMENT ME!
160      * @throws XmlPullParserException
161      *             DOCUMENT ME!
162      */
163     public Document read(InputStream in) throws DocumentException, IOException,
164             XmlPullParserException {
165         return read(createReader(in));
166     }
167 
168     /***
169      * <p>
170      * Reads a Document from the given <code>Reader</code>
171      * </p>
172      * 
173      * @param reader
174      *            is the reader for the input
175      * 
176      * @return the newly created Document instance
177      * 
178      * @throws DocumentException
179      *             if an error occurs during parsing.
180      * @throws IOException
181      *             DOCUMENT ME!
182      * @throws XmlPullParserException
183      *             DOCUMENT ME!
184      */
185     public Document read(Reader reader) throws DocumentException, IOException,
186             XmlPullParserException {
187         getXPPParser().setInput(reader);
188 
189         return parseDocument();
190     }
191 
192     /***
193      * <p>
194      * Reads a Document from the given array of characters
195      * </p>
196      * 
197      * @param text
198      *            is the text to parse
199      * 
200      * @return the newly created Document instance
201      * 
202      * @throws DocumentException
203      *             if an error occurs during parsing.
204      * @throws IOException
205      *             DOCUMENT ME!
206      * @throws XmlPullParserException
207      *             DOCUMENT ME!
208      */
209     public Document read(char[] text) throws DocumentException, IOException,
210             XmlPullParserException {
211         getXPPParser().setInput(text);
212 
213         return parseDocument();
214     }
215 
216     /***
217      * <p>
218      * Reads a Document from the given stream
219      * </p>
220      * 
221      * @param in
222      *            <code>InputStream</code> to read from.
223      * @param systemID
224      *            is the URI for the input
225      * 
226      * @return the newly created Document instance
227      * 
228      * @throws DocumentException
229      *             if an error occurs during parsing.
230      * @throws IOException
231      *             DOCUMENT ME!
232      * @throws XmlPullParserException
233      *             DOCUMENT ME!
234      */
235     public Document read(InputStream in, String systemID)
236             throws DocumentException, IOException, XmlPullParserException {
237         return read(createReader(in), systemID);
238     }
239 
240     /***
241      * <p>
242      * Reads a Document from the given <code>Reader</code>
243      * </p>
244      * 
245      * @param reader
246      *            is the reader for the input
247      * @param systemID
248      *            is the URI for the input
249      * 
250      * @return the newly created Document instance
251      * 
252      * @throws DocumentException
253      *             if an error occurs during parsing.
254      * @throws IOException
255      *             DOCUMENT ME!
256      * @throws XmlPullParserException
257      *             DOCUMENT ME!
258      */
259     public Document read(Reader reader, String systemID)
260             throws DocumentException, IOException, XmlPullParserException {
261         Document document = read(reader);
262         document.setName(systemID);
263 
264         return document;
265     }
266 
267     // Properties
268     // -------------------------------------------------------------------------
269     public XmlPullParser getXPPParser() throws XmlPullParserException {
270         if (xppParser == null) {
271             xppParser = getXPPFactory().newPullParser();
272         }
273 
274         return xppParser;
275     }
276 
277     public XmlPullParserFactory getXPPFactory() throws XmlPullParserException {
278         if (xppFactory == null) {
279             xppFactory = XmlPullParserFactory.newInstance();
280         }
281 
282         return xppFactory;
283     }
284 
285     public void setXPPFactory(XmlPullParserFactory xPPFactory) {
286         this.xppFactory = xPPFactory;
287     }
288 
289     /***
290      * DOCUMENT ME!
291      * 
292      * @return the <code>DocumentFactory</code> used to create document
293      *         objects
294      */
295     public DocumentFactory getDocumentFactory() {
296         if (factory == null) {
297             factory = DocumentFactory.getInstance();
298         }
299 
300         return factory;
301     }
302 
303     /***
304      * <p>
305      * This sets the <code>DocumentFactory</code> used to create new
306      * documents. This method allows the building of custom DOM4J tree objects
307      * to be implemented easily using a custom derivation of
308      * {@link DocumentFactory}
309      * </p>
310      * 
311      * @param documentFactory
312      *            <code>DocumentFactory</code> used to create DOM4J objects
313      */
314     public void setDocumentFactory(DocumentFactory documentFactory) {
315         this.factory = documentFactory;
316     }
317 
318     /***
319      * Adds the <code>ElementHandler</code> to be called when the specified
320      * path is encounted.
321      * 
322      * @param path
323      *            is the path to be handled
324      * @param handler
325      *            is the <code>ElementHandler</code> to be called by the event
326      *            based processor.
327      */
328     public void addHandler(String path, ElementHandler handler) {
329         getDispatchHandler().addHandler(path, handler);
330     }
331 
332     /***
333      * Removes the <code>ElementHandler</code> from the event based processor,
334      * for the specified path.
335      * 
336      * @param path
337      *            is the path to remove the <code>ElementHandler</code> for.
338      */
339     public void removeHandler(String path) {
340         getDispatchHandler().removeHandler(path);
341     }
342 
343     /***
344      * When multiple <code>ElementHandler</code> instances have been
345      * registered, this will set a default <code>ElementHandler</code> to be
346      * called for any path which does <b>NOT </b> have a handler registered.
347      * 
348      * @param handler
349      *            is the <code>ElementHandler</code> to be called by the event
350      *            based processor.
351      */
352     public void setDefaultHandler(ElementHandler handler) {
353         getDispatchHandler().setDefaultHandler(handler);
354     }
355 
356     // Implementation methods
357     // -------------------------------------------------------------------------
358     protected Document parseDocument() throws DocumentException, IOException,
359             XmlPullParserException {
360         Document document = getDocumentFactory().createDocument();
361         Element parent = null;
362         XmlPullParser parser = getXPPParser();
363         parser.setNamespaceAware(true);
364 
365         ProxyXmlStartTag startTag = new ProxyXmlStartTag();
366         XmlEndTag endTag = xppFactory.newEndTag();
367 
368         while (true) {
369             int type = parser.next();
370 
371             switch (type) {
372                 case XmlPullParser.END_DOCUMENT:
373                     return document;
374 
375                 case XmlPullParser.START_TAG: {
376                     parser.readStartTag(startTag);
377 
378                     Element newElement = startTag.getElement();
379 
380                     if (parent != null) {
381                         parent.add(newElement);
382                     } else {
383                         document.add(newElement);
384                     }
385 
386                     parent = newElement;
387 
388                     break;
389                 }
390 
391                 case XmlPullParser.END_TAG: {
392                     parser.readEndTag(endTag);
393 
394                     if (parent != null) {
395                         parent = parent.getParent();
396                     }
397 
398                     break;
399                 }
400 
401                 case XmlPullParser.CONTENT: {
402                     String text = parser.readContent();
403 
404                     if (parent != null) {
405                         parent.addText(text);
406                     } else {
407                         String msg = "Cannot have text content outside of the "
408                                 + "root document";
409                         throw new DocumentException(msg);
410                     }
411 
412                     break;
413                 }
414 
415                 default:
416                     throw new DocumentException("Error: unknown type: " + type);
417             }
418         }
419     }
420 
421     protected DispatchHandler getDispatchHandler() {
422         if (dispatchHandler == null) {
423             dispatchHandler = new DispatchHandler();
424         }
425 
426         return dispatchHandler;
427     }
428 
429     protected void setDispatchHandler(DispatchHandler dispatchHandler) {
430         this.dispatchHandler = dispatchHandler;
431     }
432 
433     /***
434      * Factory method to create a Reader from the given InputStream.
435      * 
436      * @param in
437      *            DOCUMENT ME!
438      * 
439      * @return DOCUMENT ME!
440      * 
441      * @throws IOException
442      *             DOCUMENT ME!
443      */
444     protected Reader createReader(InputStream in) throws IOException {
445         return new BufferedReader(new InputStreamReader(in));
446     }
447 }
448 
449 /*
450  * Redistribution and use of this software and associated documentation
451  * ("Software"), with or without modification, are permitted provided that the
452  * following conditions are met:
453  * 
454  * 1. Redistributions of source code must retain copyright statements and
455  * notices. Redistributions must also contain a copy of this document.
456  * 
457  * 2. Redistributions in binary form must reproduce the above copyright notice,
458  * this list of conditions and the following disclaimer in the documentation
459  * and/or other materials provided with the distribution.
460  * 
461  * 3. The name "DOM4J" must not be used to endorse or promote products derived
462  * from this Software without prior written permission of MetaStuff, Ltd. For
463  * written permission, please contact dom4j-info@metastuff.com.
464  * 
465  * 4. Products derived from this Software may not be called "DOM4J" nor may
466  * "DOM4J" appear in their names without prior written permission of MetaStuff,
467  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
468  * 
469  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
470  * 
471  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
472  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
473  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
474  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
475  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
476  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
477  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
478  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
479  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
480  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
481  * POSSIBILITY OF SUCH DAMAGE.
482  * 
483  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
484  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/package-summary.html0000644000175000017500000001543010242117733022152 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.io

Class Summary
DOMReader
DOMWriter
DispatchHandler
DocumentInputSource
DocumentResult
DocumentSource
ElementModifier
ElementStack
HTMLWriter
JAXPHelper
OutputFormat
PruningDispatchHandler
PruningElementStack
SAXContentHandler
SAXEventRecorder
SAXHelper
SAXModifier
SAXModifyContentHandler
SAXModifyElementHandler
SAXModifyException
SAXModifyReader
SAXReader
SAXValidator
SAXWriter
STAXEventReader
STAXEventWriter
XMLResult
XMLWriter
XPP3Reader
XPPReader
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref/org/dom4j/io/STAXEventWriter.html0000644000175000017500000015355110242117761022052 0ustar ebourgebourg STAXEventWriter xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.io.File;
11  import java.io.FileWriter;
12  import java.io.IOException;
13  import java.io.OutputStream;
14  import java.io.StringWriter;
15  import java.io.Writer;
16  import java.util.Iterator;
17  
18  import javax.xml.namespace.QName;
19  import javax.xml.stream.XMLEventFactory;
20  import javax.xml.stream.XMLOutputFactory;
21  import javax.xml.stream.XMLStreamException;
22  import javax.xml.stream.events.Characters;
23  import javax.xml.stream.events.DTD;
24  import javax.xml.stream.events.EndDocument;
25  import javax.xml.stream.events.EndElement;
26  import javax.xml.stream.events.EntityReference;
27  import javax.xml.stream.events.ProcessingInstruction;
28  import javax.xml.stream.events.StartDocument;
29  import javax.xml.stream.events.StartElement;
30  import javax.xml.stream.util.XMLEventConsumer;
31  
32  import org.dom4j.Attribute;
33  import org.dom4j.Branch;
34  import org.dom4j.CDATA;
35  import org.dom4j.Comment;
36  import org.dom4j.Document;
37  import org.dom4j.DocumentType;
38  import org.dom4j.Element;
39  import org.dom4j.Entity;
40  import org.dom4j.Namespace;
41  import org.dom4j.Node;
42  import org.dom4j.Text;
43  
44  /***
45   * Writes DOM4J {@link Node}s to a StAX event stream. In addition the
46   * <code>createXXX</code> methods are provided to directly create STAX events
47   * from DOM4J nodes.
48   * 
49   * @author Christian Niles
50   */
51  public class STAXEventWriter {
52      /*** The event stream to which events are written. */
53      private XMLEventConsumer consumer;
54  
55      /*** The event factory used to construct events. */
56      private XMLEventFactory factory = XMLEventFactory.newInstance();
57  
58      private XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
59  
60      public STAXEventWriter() {
61      }
62  
63      /***
64       * Constructs a <code>STAXEventWriter</code> that writes events to the
65       * provided file.
66       * 
67       * @param file
68       *            The file to which events will be written.
69       * 
70       * @throws XMLStreamException
71       *             If an error occurs creating an event writer from the file.
72       * @throws IOException
73       *             If an error occurs openin the file for writing.
74       */
75      public STAXEventWriter(File file) throws XMLStreamException, IOException {
76          consumer = outputFactory.createXMLEventWriter(new FileWriter(file));
77      }
78  
79      /***
80       * Constructs a <code>STAXEventWriter</code> that writes events to the
81       * provided character stream.
82       * 
83       * @param writer
84       *            The character stream to which events will be written.
85       * 
86       * @throws XMLStreamException
87       *             If an error occurs constructing an event writer from the
88       *             character stream.
89       */
90      public STAXEventWriter(Writer writer) throws XMLStreamException {
91          consumer = outputFactory.createXMLEventWriter(writer);
92      }
93  
94      /***
95       * Constructs a <code>STAXEventWriter</code> that writes events to the
96       * provided stream.
97       * 
98       * @param stream
99       *            The output stream to which events will be written.
100      * 
101      * @throws XMLStreamException
102      *             If an error occurs constructing an event writer from the
103      *             stream.
104      */
105     public STAXEventWriter(OutputStream stream) throws XMLStreamException {
106         consumer = outputFactory.createXMLEventWriter(stream);
107     }
108 
109     /***
110      * Constructs a <code>STAXEventWriter</code> that writes events to the
111      * provided event stream.
112      * 
113      * @param consumer
114      *            The event stream to which events will be written.
115      */
116     public STAXEventWriter(XMLEventConsumer consumer) {
117         this.consumer = consumer;
118     }
119 
120     /***
121      * Returns a reference to the underlying event consumer to which events are
122      * written.
123      * 
124      * @return The underlying event consumer to which events are written.
125      */
126     public XMLEventConsumer getConsumer() {
127         return consumer;
128     }
129 
130     /***
131      * Sets the underlying event consumer to which events are written.
132      * 
133      * @param consumer
134      *            The event consumer to which events should be written.
135      */
136     public void setConsumer(XMLEventConsumer consumer) {
137         this.consumer = consumer;
138     }
139 
140     /***
141      * Returns a reference to the event factory used to construct STAX events.
142      * 
143      * @return The event factory used to construct STAX events.
144      */
145     public XMLEventFactory getEventFactory() {
146         return factory;
147     }
148 
149     /***
150      * Sets the event factory used to construct STAX events.
151      * 
152      * @param eventFactory
153      *            The new event factory.
154      */
155     public void setEventFactory(XMLEventFactory eventFactory) {
156         this.factory = eventFactory;
157     }
158 
159     /***
160      * Writes a DOM4J {@link Node}to the stream. This method is simply a
161      * gateway to the overloaded methods such as {@link#writeElement(Element)}.
162      * 
163      * @param n
164      *            The DOM4J {@link Node}to write to the stream.
165      * 
166      * @throws XMLStreamException
167      *             If an error occurs writing to the stream.
168      */
169     public void writeNode(Node n) throws XMLStreamException {
170         switch (n.getNodeType()) {
171             case Node.ELEMENT_NODE:
172                 writeElement((Element) n);
173 
174                 break;
175 
176             case Node.TEXT_NODE:
177                 writeText((Text) n);
178 
179                 break;
180 
181             case Node.ATTRIBUTE_NODE:
182                 writeAttribute((Attribute) n);
183 
184                 break;
185 
186             case Node.NAMESPACE_NODE:
187                 writeNamespace((Namespace) n);
188 
189                 break;
190 
191             case Node.COMMENT_NODE:
192                 writeComment((Comment) n);
193 
194                 break;
195 
196             case Node.CDATA_SECTION_NODE:
197                 writeCDATA((CDATA) n);
198 
199                 break;
200 
201             case Node.PROCESSING_INSTRUCTION_NODE:
202                 writeProcessingInstruction((org.dom4j.ProcessingInstruction) n);
203 
204                 break;
205 
206             case Node.ENTITY_REFERENCE_NODE:
207                 writeEntity((Entity) n);
208 
209                 break;
210 
211             case Node.DOCUMENT_NODE:
212                 writeDocument((Document) n);
213 
214                 break;
215 
216             case Node.DOCUMENT_TYPE_NODE:
217                 writeDocumentType((DocumentType) n);
218 
219                 break;
220 
221             default:
222                 throw new XMLStreamException("Unsupported DOM4J Node: " + n);
223         }
224     }
225 
226     /***
227      * Writes each child node within the provided {@link Branch}instance. This
228      * method simply iterates through the {@link Branch}'s nodes and calls
229      * {@link #writeNode(Node)}.
230      * 
231      * @param branch
232      *            The node whose children will be written to the stream.
233      * 
234      * @throws XMLStreamException
235      *             If an error occurs writing to the stream.
236      */
237     public void writeChildNodes(Branch branch) throws XMLStreamException {
238         for (int i = 0, s = branch.nodeCount(); i < s; i++) {
239             Node n = branch.node(i);
240             writeNode(n);
241         }
242     }
243 
244     /***
245      * Writes a DOM4J {@link Element}node and its children to the stream.
246      * 
247      * @param elem
248      *            The {@link Element}node to write to the stream.
249      * 
250      * @throws XMLStreamException
251      *             If an error occurs writing to the stream.
252      */
253     public void writeElement(Element elem) throws XMLStreamException {
254         consumer.add(createStartElement(elem));
255         writeChildNodes(elem);
256         consumer.add(createEndElement(elem));
257     }
258 
259     /***
260      * Constructs a STAX {@link StartElement}event from a DOM4J {@link
261      * Element}.
262      * 
263      * @param elem
264      *            The {@link Element}from which to construct the event.
265      * 
266      * @return The newly constructed {@link StartElement}event.
267      */
268     public StartElement createStartElement(Element elem) {
269         // create name
270         QName tagName = createQName(elem.getQName());
271 
272         // create attribute & namespace iterators
273         Iterator attrIter = new AttributeIterator(elem.attributeIterator());
274         Iterator nsIter = new NamespaceIterator(elem.declaredNamespaces()
275                 .iterator());
276 
277         // create start event
278         return factory.createStartElement(tagName, attrIter, nsIter);
279     }
280 
281     /***
282      * Constructs a STAX {@link EndElement}event from a DOM4J {@link Element}.
283      * 
284      * @param elem
285      *            The {@link Element}from which to construct the event.
286      * 
287      * @return The newly constructed {@link EndElement}event.
288      */
289     public EndElement createEndElement(Element elem) {
290         QName tagName = createQName(elem.getQName());
291         Iterator nsIter = new NamespaceIterator(elem.declaredNamespaces()
292                 .iterator());
293 
294         return factory.createEndElement(tagName, nsIter);
295     }
296 
297     /***
298      * Writes a DOM4J {@link Attribute}to the stream.
299      * 
300      * @param attr
301      *            The {@link Attribute}to write to the stream.
302      * 
303      * @throws XMLStreamException
304      *             If an error occurs writing to the stream.
305      */
306     public void writeAttribute(Attribute attr) throws XMLStreamException {
307         consumer.add(createAttribute(attr));
308     }
309 
310     /***
311      * Constructs a STAX {@link javax.xml.stream.events.Attribute}event from a
312      * DOM4J {@link Attribute}.
313      * 
314      * @param attr
315      *            The {@link Attribute}from which to construct the event.
316      * 
317      * @return The newly constructed {@link javax.xml.stream.events.Attribute}
318      *         event.
319      */
320     public javax.xml.stream.events.Attribute createAttribute(Attribute attr) {
321         QName attrName = createQName(attr.getQName());
322         String value = attr.getValue();
323 
324         return factory.createAttribute(attrName, value);
325     }
326 
327     /***
328      * Writes a DOM4J {@link Namespace}to the stream.
329      * 
330      * @param ns
331      *            The {@link Namespace}to write to the stream.
332      * 
333      * @throws XMLStreamException
334      *             If an error occurs writing to the stream.
335      */
336     public void writeNamespace(Namespace ns) throws XMLStreamException {
337         consumer.add(createNamespace(ns));
338     }
339 
340     /***
341      * Constructs a STAX {@link javax.xml.stream.events.Namespace}event from a
342      * DOM4J {@link Namespace}.
343      * 
344      * @param ns
345      *            The {@link Namespace}from which to construct the event.
346      * 
347      * @return The constructed {@link javax.xml.stream.events.Namespace}event.
348      */
349     public javax.xml.stream.events.Namespace createNamespace(Namespace ns) {
350         String prefix = ns.getPrefix();
351         String uri = ns.getURI();
352 
353         return factory.createNamespace(prefix, uri);
354     }
355 
356     /***
357      * Writes a DOM4J {@link Text}to the stream.
358      * 
359      * @param text
360      *            The {@link Text}to write to the stream.
361      * 
362      * @throws XMLStreamException
363      *             If an error occurs writing to the stream.
364      */
365     public void writeText(Text text) throws XMLStreamException {
366         consumer.add(createCharacters(text));
367     }
368 
369     /***
370      * Constructs a STAX {@link Characters}event from a DOM4J {@link Text}.
371      * 
372      * @param text
373      *            The {@link Text}from which to construct the event.
374      * 
375      * @return The constructed {@link Characters}event.
376      */
377     public Characters createCharacters(Text text) {
378         return factory.createCharacters(text.getText());
379     }
380 
381     /***
382      * Writes a DOM4J {@link CDATA}to the event stream.
383      * 
384      * @param cdata
385      *            The {@link CDATA}to write to the stream.
386      * 
387      * @throws XMLStreamException
388      *             If an error occurs writing to the stream.
389      */
390     public void writeCDATA(CDATA cdata) throws XMLStreamException {
391         consumer.add(createCharacters(cdata));
392     }
393 
394     /***
395      * Constructs a STAX {@link Characters}event from a DOM4J {@link CDATA}.
396      * 
397      * @param cdata
398      *            The {@link CDATA}from which to construct the event.
399      * 
400      * @return The newly constructed {@link Characters}event.
401      */
402     public Characters createCharacters(CDATA cdata) {
403         return factory.createCData(cdata.getText());
404     }
405 
406     /***
407      * Writes a DOM4J {@link Comment}to the stream.
408      * 
409      * @param comment
410      *            The {@link Comment}to write to the stream.
411      * 
412      * @throws XMLStreamException
413      *             If an error occurs writing to the stream.
414      */
415     public void writeComment(Comment comment) throws XMLStreamException {
416         consumer.add(createComment(comment));
417     }
418 
419     /***
420      * Constructs a STAX {@link javax.xml.stream.events.Comment}event from a
421      * DOM4J {@link Comment}.
422      * 
423      * @param comment
424      *            The {@link Comment}from which to construct the event.
425      * 
426      * @return The constructed {@link javax.xml.stream.events.Comment}event.
427      */
428     public javax.xml.stream.events.Comment createComment(Comment comment) {
429         return factory.createComment(comment.getText());
430     }
431 
432     /***
433      * Writes a DOM4J {@link ProcessingInstruction}to the stream.
434      * 
435      * @param pi
436      *            The {@link ProcessingInstruction}to write to the stream.
437      * 
438      * @throws XMLStreamException
439      *             If an error occurs writing to the stream.
440      */
441     public void writeProcessingInstruction(org.dom4j.ProcessingInstruction pi)
442             throws XMLStreamException {
443         consumer.add(createProcessingInstruction(pi));
444     }
445 
446     /***
447      * Constructs a STAX {@link javax.xml.stream.events.ProcessingInstruction}
448      * event from a DOM4J {@link ProcessingInstruction}.
449      * 
450      * @param pi
451      *            The {@link ProcessingInstruction}from which to construct the
452      *            event.
453      * 
454      * @return The constructed {@link
455      *         javax.xml.stream.events.ProcessingInstruction} event.
456      */
457     public ProcessingInstruction createProcessingInstruction(
458             org.dom4j.ProcessingInstruction pi) {
459         String target = pi.getTarget();
460         String data = pi.getText();
461 
462         return factory.createProcessingInstruction(target, data);
463     }
464 
465     /***
466      * Writes a DOM4J {@link Entity}to the stream.
467      * 
468      * @param entity
469      *            The {@link Entity}to write to the stream.
470      * 
471      * @throws XMLStreamException
472      *             If an error occurs writing to the stream.
473      */
474     public void writeEntity(Entity entity) throws XMLStreamException {
475         consumer.add(createEntityReference(entity));
476     }
477 
478     /***
479      * Constructs a STAX {@link EntityReference}event from a DOM4J {@link
480      * Entity}.
481      * 
482      * @param entity
483      *            The {@link Entity}from which to construct the event.
484      * 
485      * @return The constructed {@link EntityReference}event.
486      */
487     private EntityReference createEntityReference(Entity entity) {
488         return factory.createEntityReference(entity.getName(), null);
489     }
490 
491     /***
492      * Writes a DOM4J {@link DocumentType}to the stream.
493      * 
494      * @param docType
495      *            The {@link DocumentType}to write to the stream.
496      * 
497      * @throws XMLStreamException
498      *             If an error occurs writing to the stream.
499      */
500     public void writeDocumentType(DocumentType docType)
501             throws XMLStreamException {
502         consumer.add(createDTD(docType));
503     }
504 
505     /***
506      * Constructs a STAX {@link DTD}event from a DOM4J {@link DocumentType}.
507      * 
508      * @param docType
509      *            The {@link DocumentType}from which to construct the event.
510      * 
511      * @return The constructed {@link DTD}event.
512      * 
513      * @throws RuntimeException
514      *             DOCUMENT ME!
515      */
516     public DTD createDTD(DocumentType docType) {
517         StringWriter decl = new StringWriter();
518 
519         try {
520             docType.write(decl);
521         } catch (IOException e) {
522             throw new RuntimeException("Error writing DTD", e);
523         }
524 
525         return factory.createDTD(decl.toString());
526     }
527 
528     /***
529      * Writes a DOM4J {@link Document}node, and all its contents, to the
530      * stream.
531      * 
532      * @param doc
533      *            The {@link Document}to write to the stream.
534      * 
535      * @throws XMLStreamException
536      *             If an error occurs writing to the stream.
537      */
538     public void writeDocument(Document doc) throws XMLStreamException {
539         consumer.add(createStartDocument(doc));
540 
541         writeChildNodes(doc);
542 
543         consumer.add(createEndDocument(doc));
544     }
545 
546     /***
547      * Constructs a STAX {@link StartDocument}event from a DOM4J {@link
548      * Document}.
549      * 
550      * @param doc
551      *            The {@link Document}from which to construct the event.
552      * 
553      * @return The constructed {@link StartDocument}event.
554      */
555     public StartDocument createStartDocument(Document doc) {
556         String encoding = doc.getXMLEncoding();
557 
558         if (encoding != null) {
559             return factory.createStartDocument(encoding);
560         } else {
561             return factory.createStartDocument();
562         }
563     }
564 
565     /***
566      * Constructs a STAX {@link EndDocument}event from a DOM4J {@link
567      * Document}.
568      * 
569      * @param doc
570      *            The {@link Document}from which to construct the event.
571      * 
572      * @return The constructed {@link EndDocument}event.
573      */
574     public EndDocument createEndDocument(Document doc) {
575         return factory.createEndDocument();
576     }
577 
578     /***
579      * Constructs a STAX {@link QName}from a DOM4J {@link org.dom4j.QName}.
580      * 
581      * @param qname
582      *            The {@link org.dom4j.QName}from which to construct the STAX
583      *            {@link QName}.
584      * 
585      * @return The constructed {@link QName}.
586      */
587     public QName createQName(org.dom4j.QName qname) {
588         return new QName(qname.getNamespaceURI(), qname.getName(), qname
589                 .getNamespacePrefix());
590     }
591 
592     /***
593      * Internal {@link Iterator}implementation used to pass DOM4J {@link
594      * Attribute}s to the stream.
595      */
596     private class AttributeIterator implements Iterator {
597         /*** The underlying DOm4J attribute iterator. */
598         private Iterator iter;
599 
600         public AttributeIterator(Iterator iter) {
601             this.iter = iter;
602         }
603 
604         public boolean hasNext() {
605             return iter.hasNext();
606         }
607 
608         public Object next() {
609             Attribute attr = (Attribute) iter.next();
610             QName attrName = createQName(attr.getQName());
611             String value = attr.getValue();
612 
613             return factory.createAttribute(attrName, value);
614         }
615 
616         public void remove() {
617             throw new UnsupportedOperationException();
618         }
619     }
620 
621     /***
622      * Internal {@link Iterator}implementation used to pass DOM4J {@link
623      * Namespace}s to the stream.
624      */
625     private class NamespaceIterator implements Iterator {
626         private Iterator iter;
627 
628         public NamespaceIterator(Iterator iter) {
629             this.iter = iter;
630         }
631 
632         public boolean hasNext() {
633             return iter.hasNext();
634         }
635 
636         public Object next() {
637             Namespace ns = (Namespace) iter.next();
638             String prefix = ns.getPrefix();
639             String nsURI = ns.getURI();
640 
641             return factory.createNamespace(prefix, nsURI);
642         }
643 
644         public void remove() {
645             throw new UnsupportedOperationException();
646         }
647     }
648 }
649 
650 /*
651  * Redistribution and use of this software and associated documentation
652  * ("Software"), with or without modification, are permitted provided that the
653  * following conditions are met:
654  * 
655  * 1. Redistributions of source code must retain copyright statements and
656  * notices. Redistributions must also contain a copy of this document.
657  * 
658  * 2. Redistributions in binary form must reproduce the above copyright notice,
659  * this list of conditions and the following disclaimer in the documentation
660  * and/or other materials provided with the distribution.
661  * 
662  * 3. The name "DOM4J" must not be used to endorse or promote products derived
663  * from this Software without prior written permission of MetaStuff, Ltd. For
664  * written permission, please contact dom4j-info@metastuff.com.
665  * 
666  * 4. Products derived from this Software may not be called "DOM4J" nor may
667  * "DOM4J" appear in their names without prior written permission of MetaStuff,
668  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
669  * 
670  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
671  * 
672  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
673  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
674  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
675  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
676  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
677  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
678  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
679  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
680  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
681  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
682  * POSSIBILITY OF SUCH DAMAGE.
683  * 
684  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
685  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/SAXHelper.html0000644000175000017500000004205510242117724020662 0ustar ebourgebourg SAXHelper xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import org.xml.sax.SAXException;
11  import org.xml.sax.SAXNotRecognizedException;
12  import org.xml.sax.SAXNotSupportedException;
13  import org.xml.sax.XMLReader;
14  import org.xml.sax.helpers.XMLReaderFactory;
15  
16  /***
17   * <p>
18   * <code>SAXHelper</code> contains some helper methods for working with SAX
19   * and XMLReader objects.
20   * </p>
21   * 
22   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
23   * @version $Revision: 1.18 $
24   */
25  class SAXHelper {
26      private static boolean loggedWarning = true;
27  
28      protected SAXHelper() {
29      }
30  
31      public static boolean setParserProperty(XMLReader reader,
32              String propertyName, Object value) {
33          try {
34              reader.setProperty(propertyName, value);
35  
36              return true;
37          } catch (SAXNotSupportedException e) {
38              // ignore
39          } catch (SAXNotRecognizedException e) {
40              // ignore
41          }
42  
43          return false;
44      }
45  
46      public static boolean setParserFeature(XMLReader reader,
47              String featureName, boolean value) {
48          try {
49              reader.setFeature(featureName, value);
50  
51              return true;
52          } catch (SAXNotSupportedException e) {
53              // ignore
54          } catch (SAXNotRecognizedException e) {
55              // ignore
56          }
57  
58          return false;
59      }
60  
61      /***
62       * Creats a default XMLReader via the org.xml.sax.driver system property or
63       * JAXP if the system property is not set.
64       * 
65       * @param validating
66       *            DOCUMENT ME!
67       * 
68       * @return DOCUMENT ME!
69       * 
70       * @throws SAXException
71       *             DOCUMENT ME!
72       */
73      public static XMLReader createXMLReader(boolean validating)
74              throws SAXException {
75          XMLReader reader = null;
76  
77          if (reader == null) {
78              reader = createXMLReaderViaJAXP(validating, true);
79          }
80  
81          if (reader == null) {
82              try {
83                  reader = XMLReaderFactory.createXMLReader();
84              } catch (Exception e) {
85                  if (isVerboseErrorReporting()) {
86                      // log all exceptions as warnings and carry
87                      // on as we have a default SAX parser we can use
88                      System.out.println("Warning: Caught exception attempting "
89                              + "to use SAX to load a SAX XMLReader ");
90                      System.out.println("Warning: Exception was: " + e);
91                      System.out
92                              .println("Warning: I will print the stack trace "
93                                      + "then carry on using the default "
94                                      + "SAX parser");
95                      e.printStackTrace();
96                  }
97  
98                  throw new SAXException(e);
99              }
100         }
101 
102         if (reader == null) {
103             throw new SAXException("Couldn't create SAX reader");
104         }
105 
106         return reader;
107     }
108 
109     /***
110      * This method attempts to use JAXP to locate the SAX2 XMLReader
111      * implementation. This method uses reflection to avoid being dependent
112      * directly on the JAXP classes.
113      * 
114      * @param validating
115      *            DOCUMENT ME!
116      * @param namespaceAware
117      *            DOCUMENT ME!
118      * 
119      * @return DOCUMENT ME!
120      */
121     protected static XMLReader createXMLReaderViaJAXP(boolean validating,
122             boolean namespaceAware) {
123         // try use JAXP to load the XMLReader...
124         try {
125             return JAXPHelper.createXMLReader(validating, namespaceAware);
126         } catch (Throwable e) {
127             if (!loggedWarning) {
128                 loggedWarning = true;
129 
130                 if (isVerboseErrorReporting()) {
131                     // log all exceptions as warnings and carry
132                     // on as we have a default SAX parser we can use
133                     System.out.println("Warning: Caught exception attempting "
134                             + "to use JAXP to load a SAX XMLReader");
135                     System.out.println("Warning: Exception was: " + e);
136                     e.printStackTrace();
137                 }
138             }
139         }
140 
141         return null;
142     }
143 
144     protected static boolean isVerboseErrorReporting() {
145         try {
146             String flag = System.getProperty("org.dom4j.verbose");
147 
148             if ((flag != null) && flag.equalsIgnoreCase("true")) {
149                 return true;
150             }
151         } catch (Exception e) {
152             // in case a security exception
153             // happens in an applet or similar JVM
154         }
155 
156         return true;
157     }
158 }
159 
160 /*
161  * Redistribution and use of this software and associated documentation
162  * ("Software"), with or without modification, are permitted provided that the
163  * following conditions are met:
164  * 
165  * 1. Redistributions of source code must retain copyright statements and
166  * notices. Redistributions must also contain a copy of this document.
167  * 
168  * 2. Redistributions in binary form must reproduce the above copyright notice,
169  * this list of conditions and the following disclaimer in the documentation
170  * and/or other materials provided with the distribution.
171  * 
172  * 3. The name "DOM4J" must not be used to endorse or promote products derived
173  * from this Software without prior written permission of MetaStuff, Ltd. For
174  * written permission, please contact dom4j-info@metastuff.com.
175  * 
176  * 4. Products derived from this Software may not be called "DOM4J" nor may
177  * "DOM4J" appear in their names without prior written permission of MetaStuff,
178  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
179  * 
180  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
181  * 
182  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
183  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
184  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
185  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
186  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
187  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
188  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
189  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
190  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
191  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
192  * POSSIBILITY OF SUCH DAMAGE.
193  * 
194  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
195  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/DocumentInputSource.html0000644000175000017500000003240510242117614023042 0ustar ebourgebourg DocumentInputSource xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.io.IOException;
11  import java.io.Reader;
12  import java.io.StringReader;
13  import java.io.StringWriter;
14  
15  import org.dom4j.Document;
16  
17  import org.xml.sax.InputSource;
18  
19  /***
20   * <p>
21   * <code>DocumentInputSource</code> implements a SAX {@link InputSource}for a
22   * {@link Document}.
23   * </p>
24   * 
25   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
26   * @version $Revision: 1.8 $
27   */
28  class DocumentInputSource extends InputSource {
29      /*** The document source */
30      private Document document;
31  
32      public DocumentInputSource() {
33      }
34  
35      public DocumentInputSource(Document document) {
36          this.document = document;
37          setSystemId(document.getName());
38      }
39  
40      // Properties
41      // -------------------------------------------------------------------------
42  
43      /***
44       * DOCUMENT ME!
45       * 
46       * @return the document which is being used as the SAX {@link InputSource}
47       */
48      public Document getDocument() {
49          return document;
50      }
51  
52      /***
53       * Sets the document used as the SAX {@link InputSource}
54       * 
55       * @param document
56       *            DOCUMENT ME!
57       */
58      public void setDocument(Document document) {
59          this.document = document;
60          setSystemId(document.getName());
61      }
62  
63      // Overloaded methods
64      // -------------------------------------------------------------------------
65  
66      /***
67       * This method is not supported as this source is always a {@linkDocument}
68       * instance.
69       * 
70       * @param characterStream
71       *            DOCUMENT ME!
72       * 
73       * @throws UnsupportedOperationException
74       *             as this method is unsupported
75       */
76      public void setCharacterStream(Reader characterStream)
77              throws UnsupportedOperationException {
78          throw new UnsupportedOperationException();
79      }
80  
81      /***
82       * Note this method is quite inefficent, it turns the in memory XML tree
83       * object model into a single block of text which can then be read by other
84       * XML parsers. Should only be used with care.
85       * 
86       * @return DOCUMENT ME!
87       */
88      public Reader getCharacterStream() {
89          try {
90              StringWriter out = new StringWriter();
91              XMLWriter writer = new XMLWriter(out);
92              writer.write(document);
93              writer.flush();
94  
95              return new StringReader(out.toString());
96          } catch (final IOException e) {
97              // this should never really happen
98              // but for completeness we'll return a Reader
99              // with the embedded exception inside it
100             return new Reader() {
101                 public int read(char[] ch, int offset, int length)
102                         throws IOException {
103                     throw e;
104                 }
105 
106                 public void close() throws IOException {
107                 }
108             };
109         }
110     }
111 }
112 
113 /*
114  * Redistribution and use of this software and associated documentation
115  * ("Software"), with or without modification, are permitted provided that the
116  * following conditions are met:
117  * 
118  * 1. Redistributions of source code must retain copyright statements and
119  * notices. Redistributions must also contain a copy of this document.
120  * 
121  * 2. Redistributions in binary form must reproduce the above copyright notice,
122  * this list of conditions and the following disclaimer in the documentation
123  * and/or other materials provided with the distribution.
124  * 
125  * 3. The name "DOM4J" must not be used to endorse or promote products derived
126  * from this Software without prior written permission of MetaStuff, Ltd. For
127  * written permission, please contact dom4j-info@metastuff.com.
128  * 
129  * 4. Products derived from this Software may not be called "DOM4J" nor may
130  * "DOM4J" appear in their names without prior written permission of MetaStuff,
131  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
132  * 
133  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
134  * 
135  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
136  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
137  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
138  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
139  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
140  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
141  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
142  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
143  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
144  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
145  * POSSIBILITY OF SUCH DAMAGE.
146  * 
147  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
148  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/DOMReader.html0000644000175000017500000006437710242117635020645 0ustar ebourgebourg DOMReader xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.util.ArrayList;
11  import java.util.List;
12  
13  import org.dom4j.Branch;
14  import org.dom4j.Document;
15  import org.dom4j.DocumentFactory;
16  import org.dom4j.Element;
17  import org.dom4j.Namespace;
18  import org.dom4j.QName;
19  import org.dom4j.tree.NamespaceStack;
20  
21  /***
22   * <p>
23   * <code>DOMReader</code> navigates a W3C DOM tree and creates a DOM4J tree
24   * from it.
25   * </p>
26   * 
27   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
28   * @version $Revision: 1.17 $
29   */
30  public class DOMReader {
31      /*** <code>DocumentFactory</code> used to create new document objects */
32      private DocumentFactory factory;
33  
34      /*** stack of <code>Namespace</code> and <code>QName</code> objects */
35      private NamespaceStack namespaceStack;
36  
37      public DOMReader() {
38          this.factory = DocumentFactory.getInstance();
39          this.namespaceStack = new NamespaceStack(factory);
40      }
41  
42      public DOMReader(DocumentFactory factory) {
43          this.factory = factory;
44          this.namespaceStack = new NamespaceStack(factory);
45      }
46  
47      /***
48       * DOCUMENT ME!
49       * 
50       * @return the <code>DocumentFactory</code> used to create document
51       *         objects
52       */
53      public DocumentFactory getDocumentFactory() {
54          return factory;
55      }
56  
57      /***
58       * <p>
59       * This sets the <code>DocumentFactory</code> used to create new
60       * documents. This method allows the building of custom DOM4J tree objects
61       * to be implemented easily using a custom derivation of
62       * {@link DocumentFactory}
63       * </p>
64       * 
65       * @param docFactory
66       *            <code>DocumentFactory</code> used to create DOM4J objects
67       */
68      public void setDocumentFactory(DocumentFactory docFactory) {
69          this.factory = docFactory;
70          this.namespaceStack.setDocumentFactory(factory);
71      }
72  
73      public Document read(org.w3c.dom.Document domDocument) {
74          if (domDocument instanceof Document) {
75              return (Document) domDocument;
76          }
77  
78          Document document = createDocument();
79  
80          clearNamespaceStack();
81  
82          org.w3c.dom.NodeList nodeList = domDocument.getChildNodes();
83  
84          for (int i = 0, size = nodeList.getLength(); i < size; i++) {
85              readTree(nodeList.item(i), document);
86          }
87  
88          return document;
89      }
90  
91      // Implementation methods
92      protected void readTree(org.w3c.dom.Node node, Branch current) {
93          Element element = null;
94          Document document = null;
95  
96          if (current instanceof Element) {
97              element = (Element) current;
98          } else {
99              document = (Document) current;
100         }
101 
102         switch (node.getNodeType()) {
103             case org.w3c.dom.Node.ELEMENT_NODE:
104                 readElement(node, current);
105 
106                 break;
107 
108             case org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE:
109 
110                 if (current instanceof Element) {
111                     Element currentEl = (Element) current;
112                     currentEl.addProcessingInstruction(node.getNodeName(), node
113                             .getNodeValue());
114                 } else {
115                     Document currentDoc = (Document) current;
116                     currentDoc.addProcessingInstruction(node.getNodeName(),
117                             node.getNodeValue());
118                 }
119 
120                 break;
121 
122             case org.w3c.dom.Node.COMMENT_NODE:
123 
124                 if (current instanceof Element) {
125                     ((Element) current).addComment(node.getNodeValue());
126                 } else {
127                     ((Document) current).addComment(node.getNodeValue());
128                 }
129 
130                 break;
131 
132             case org.w3c.dom.Node.DOCUMENT_TYPE_NODE:
133 
134                 org.w3c.dom.DocumentType domDocType 
135                         = (org.w3c.dom.DocumentType) node;
136                 document.addDocType(domDocType.getName(), domDocType
137                         .getPublicId(), domDocType.getSystemId());
138 
139                 break;
140 
141             case org.w3c.dom.Node.TEXT_NODE:
142                 element.addText(node.getNodeValue());
143 
144                 break;
145 
146             case org.w3c.dom.Node.CDATA_SECTION_NODE:
147                 element.addCDATA(node.getNodeValue());
148 
149                 break;
150 
151             case org.w3c.dom.Node.ENTITY_REFERENCE_NODE:
152 
153                 // is there a better way to get the value of an entity?
154                 org.w3c.dom.Node firstChild = node.getFirstChild();
155 
156                 if (firstChild != null) {
157                     element.addEntity(node.getNodeName(), firstChild
158                             .getNodeValue());
159                 } else {
160                     element.addEntity(node.getNodeName(), "");
161                 }
162 
163                 break;
164 
165             case org.w3c.dom.Node.ENTITY_NODE:
166                 element.addEntity(node.getNodeName(), node.getNodeValue());
167 
168                 break;
169 
170             default:
171                 System.out.println("WARNING: Unknown DOM node type: "
172                         + node.getNodeType());
173         }
174     }
175 
176     protected void readElement(org.w3c.dom.Node node, Branch current) {
177         int previouslyDeclaredNamespaces = namespaceStack.size();
178 
179         String namespaceUri = node.getNamespaceURI();
180         String elementPrefix = node.getPrefix();
181 
182         if (elementPrefix == null) {
183             elementPrefix = "";
184         }
185 
186         org.w3c.dom.NamedNodeMap attributeList = node.getAttributes();
187 
188         if ((attributeList != null) && (namespaceUri == null)) {
189             // test if we have an "xmlns" attribute
190             org.w3c.dom.Node attribute = attributeList.getNamedItem("xmlns");
191 
192             if (attribute != null) {
193                 namespaceUri = attribute.getNodeValue();
194                 elementPrefix = "";
195             }
196         }
197 
198         QName qName = namespaceStack.getQName(namespaceUri,
199                 node.getLocalName(), node.getNodeName());
200         Element element = current.addElement(qName);
201 
202         if (attributeList != null) {
203             int size = attributeList.getLength();
204             List attributes = new ArrayList(size);
205 
206             for (int i = 0; i < size; i++) {
207                 org.w3c.dom.Node attribute = attributeList.item(i);
208 
209                 // Define all namespaces first then process attributes later
210                 String name = attribute.getNodeName();
211 
212                 if (name.startsWith("xmlns")) {
213                     String prefix = getPrefix(name);
214                     String uri = attribute.getNodeValue();
215 
216                     Namespace namespace = namespaceStack.addNamespace(prefix,
217                             uri);
218                     element.add(namespace);
219                 } else {
220                     attributes.add(attribute);
221                 }
222             }
223 
224             // now add the attributes, the namespaces should be available
225             size = attributes.size();
226 
227             for (int i = 0; i < size; i++) {
228                 org.w3c.dom.Node attribute = (org.w3c.dom.Node) attributes
229                         .get(i);
230                 QName attributeQName = namespaceStack.getQName(attribute
231                         .getNamespaceURI(), attribute.getLocalName(), attribute
232                         .getNodeName());
233                 element.addAttribute(attributeQName, attribute.getNodeValue());
234             }
235         }
236 
237         // Recurse on child nodes
238         org.w3c.dom.NodeList children = node.getChildNodes();
239 
240         for (int i = 0, size = children.getLength(); i < size; i++) {
241             org.w3c.dom.Node child = children.item(i);
242             readTree(child, element);
243         }
244 
245         // pop namespaces from the stack
246         while (namespaceStack.size() > previouslyDeclaredNamespaces) {
247             namespaceStack.pop();
248         }
249     }
250 
251     protected Namespace getNamespace(String prefix, String uri) {
252         return getDocumentFactory().createNamespace(prefix, uri);
253     }
254 
255     protected Document createDocument() {
256         return getDocumentFactory().createDocument();
257     }
258 
259     protected void clearNamespaceStack() {
260         namespaceStack.clear();
261 
262         if (!namespaceStack.contains(Namespace.XML_NAMESPACE)) {
263             namespaceStack.push(Namespace.XML_NAMESPACE);
264         }
265     }
266 
267     private String getPrefix(String xmlnsDecl) {
268         int index = xmlnsDecl.indexOf(':', 5);
269 
270         if (index != -1) {
271             return xmlnsDecl.substring(index + 1);
272         } else {
273             return "";
274         }
275     }
276 }
277 
278 /*
279  * Redistribution and use of this software and associated documentation
280  * ("Software"), with or without modification, are permitted provided that the
281  * following conditions are met:
282  * 
283  * 1. Redistributions of source code must retain copyright statements and
284  * notices. Redistributions must also contain a copy of this document.
285  * 
286  * 2. Redistributions in binary form must reproduce the above copyright notice,
287  * this list of conditions and the following disclaimer in the documentation
288  * and/or other materials provided with the distribution.
289  * 
290  * 3. The name "DOM4J" must not be used to endorse or promote products derived
291  * from this Software without prior written permission of MetaStuff, Ltd. For
292  * written permission, please contact dom4j-info@metastuff.com.
293  * 
294  * 4. Products derived from this Software may not be called "DOM4J" nor may
295  * "DOM4J" appear in their names without prior written permission of MetaStuff,
296  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
297  * 
298  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
299  * 
300  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
301  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
302  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
303  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
304  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
305  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
306  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
307  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
308  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
309  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
310  * POSSIBILITY OF SUCH DAMAGE.
311  * 
312  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
313  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/package-frame.html0000644000175000017500000001013310242117615021541 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.io

org.dom4j.io

Classes

  • DOMReader
  • DOMWriter
  • DispatchHandler
  • DocumentInputSource
  • DocumentResult
  • DocumentSource
  • ElementModifier
  • ElementStack
  • HTMLWriter
  • JAXPHelper
  • OutputFormat
  • PruningDispatchHandler
  • PruningElementStack
  • SAXContentHandler
  • SAXEventRecorder
  • SAXHelper
  • SAXModifier
  • SAXModifyContentHandler
  • SAXModifyElementHandler
  • SAXModifyException
  • SAXModifyReader
  • SAXReader
  • SAXValidator
  • SAXWriter
  • STAXEventReader
  • STAXEventWriter
  • XMLResult
  • XMLWriter
  • XPP3Reader
  • XPPReader
dom4j-1.6.1/docs/xref/org/dom4j/io/DocumentSource.html0000644000175000017500000003755410242117713022034 0ustar ebourgebourg DocumentSource xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import javax.xml.transform.sax.SAXSource;
11  
12  import org.dom4j.Document;
13  import org.dom4j.Node;
14  
15  import org.xml.sax.InputSource;
16  import org.xml.sax.XMLFilter;
17  import org.xml.sax.XMLReader;
18  
19  /***
20   * <p>
21   * <code>DocumentSource</code> implements a JAXP {@link SAXSource}for a
22   * {@linkDocument}.
23   * </p>
24   * 
25   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
26   * @version $Revision: 1.10 $
27   */
28  public class DocumentSource extends SAXSource {
29      /***
30       * If {@link javax.xml.transform.TransformerFactory#getFeature}returns
31       * <code>true</code> when passed this value as an argument then the
32       * Transformer natively supports <i>dom4j </i>.
33       */
34      public static final String DOM4J_FEATURE 
35              = "http://org.dom4j.io.DoucmentSource/feature";
36  
37      /*** The XMLReader to use */
38      private XMLReader xmlReader = new SAXWriter();
39  
40      /***
41       * Creates a JAXP {@link SAXSource}for the given {@link Node}.
42       * 
43       * @param node
44       *            DOCUMENT ME!
45       */
46      public DocumentSource(Node node) {
47          setDocument(node.getDocument());
48      }
49  
50      /***
51       * Creates a JAXP {@link SAXSource}for the given {@link Document}.
52       * 
53       * @param document
54       *            DOCUMENT ME!
55       */
56      public DocumentSource(Document document) {
57          setDocument(document);
58      }
59  
60      // Properties
61      // -------------------------------------------------------------------------
62  
63      /***
64       * DOCUMENT ME!
65       * 
66       * @return the document which is being used as the JAXP {@link SAXSource}
67       */
68      public Document getDocument() {
69          DocumentInputSource source = (DocumentInputSource) getInputSource();
70          return source.getDocument();
71      }
72  
73      /***
74       * Sets the document used as the JAXP {@link SAXSource}
75       * 
76       * @param document
77       *            DOCUMENT ME!
78       */
79      public void setDocument(Document document) {
80          super.setInputSource(new DocumentInputSource(document));
81      }
82  
83      // Overloaded methods
84      // -------------------------------------------------------------------------
85  
86      /***
87       * DOCUMENT ME!
88       * 
89       * @return the XMLReader to be used for the JAXP {@link SAXSource}.
90       */
91      public XMLReader getXMLReader() {
92          return xmlReader;
93      }
94  
95      /***
96       * This method is not supported as this source is always a {@linkDocument}
97       * instance.
98       * 
99       * @param inputSource
100      *            DOCUMENT ME!
101      * 
102      * @throws UnsupportedOperationException
103      *             as this method is unsupported
104      */
105     public void setInputSource(InputSource inputSource)
106             throws UnsupportedOperationException {
107         if (inputSource instanceof DocumentInputSource) {
108             super.setInputSource((DocumentInputSource) inputSource);
109         } else {
110             throw new UnsupportedOperationException();
111         }
112     }
113 
114     /***
115      * Sets the XMLReader used for the JAXP {@link SAXSource}.
116      * 
117      * @param reader
118      *            DOCUMENT ME!
119      * 
120      * @throws UnsupportedOperationException
121      *             DOCUMENT ME!
122      */
123     public void setXMLReader(XMLReader reader)
124             throws UnsupportedOperationException {
125         if (reader instanceof SAXWriter) {
126             this.xmlReader = (SAXWriter) reader;
127         } else if (reader instanceof XMLFilter) {
128             XMLFilter filter = (XMLFilter) reader;
129 
130             while (true) {
131                 XMLReader parent = filter.getParent();
132 
133                 if (parent instanceof XMLFilter) {
134                     filter = (XMLFilter) parent;
135                 } else {
136                     break;
137                 }
138             }
139 
140             // install filter in SAXWriter....
141             filter.setParent(xmlReader);
142             xmlReader = filter;
143         } else {
144             throw new UnsupportedOperationException();
145         }
146     }
147 }
148 
149 /*
150  * Redistribution and use of this software and associated documentation
151  * ("Software"), with or without modification, are permitted provided that the
152  * following conditions are met:
153  * 
154  * 1. Redistributions of source code must retain copyright statements and
155  * notices. Redistributions must also contain a copy of this document.
156  * 
157  * 2. Redistributions in binary form must reproduce the above copyright notice,
158  * this list of conditions and the following disclaimer in the documentation
159  * and/or other materials provided with the distribution.
160  * 
161  * 3. The name "DOM4J" must not be used to endorse or promote products derived
162  * from this Software without prior written permission of MetaStuff, Ltd. For
163  * written permission, please contact dom4j-info@metastuff.com.
164  * 
165  * 4. Products derived from this Software may not be called "DOM4J" nor may
166  * "DOM4J" appear in their names without prior written permission of MetaStuff,
167  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
168  * 
169  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
170  * 
171  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
172  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
173  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
174  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
175  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
176  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
177  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
178  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
179  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
180  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
181  * POSSIBILITY OF SUCH DAMAGE.
182  * 
183  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
184  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/SAXModifyException.html0000644000175000017500000001531310242117701022541 0ustar ebourgebourg SAXModifyException xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  /***
11   * Exception internally thrown by the SAX Modification classes. This is a
12   * RuntimeException since the {@link org.dom4j.ElementHandler}methods do not
13   * throw Exceptions.
14   * 
15   * @author Wonne Keysers (Realsoftware.be)
16   */
17  class SAXModifyException extends RuntimeException {
18      /***
19       * DOCUMENT ME!
20       * 
21       * @param cause
22       *            The causing {@link java.lang.Throwable}
23       */
24      protected SAXModifyException(Throwable cause) {
25          super(cause);
26      }
27  }
28  
29  /*
30   * Redistribution and use of this software and associated documentation
31   * ("Software"), with or without modification, are permitted provided that the
32   * following conditions are met:
33   * 
34   * 1. Redistributions of source code must retain copyright statements and
35   * notices. Redistributions must also contain a copy of this document.
36   * 
37   * 2. Redistributions in binary form must reproduce the above copyright notice,
38   * this list of conditions and the following disclaimer in the documentation
39   * and/or other materials provided with the distribution.
40   * 
41   * 3. The name "DOM4J" must not be used to endorse or promote products derived
42   * from this Software without prior written permission of MetaStuff, Ltd. For
43   * written permission, please contact dom4j-info@metastuff.com.
44   * 
45   * 4. Products derived from this Software may not be called "DOM4J" nor may
46   * "DOM4J" appear in their names without prior written permission of MetaStuff,
47   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
48   * 
49   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
50   * 
51   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
52   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
53   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
54   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
55   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
56   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
57   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
58   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
59   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
60   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
61   * POSSIBILITY OF SUCH DAMAGE.
62   * 
63   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
64   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/SAXEventRecorder.html0000644000175000017500000013767310242117650022223 0ustar ebourgebourg SAXEventRecorder xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.io.Externalizable;
11  import java.io.IOException;
12  import java.io.ObjectInput;
13  import java.io.ObjectOutput;
14  import java.util.ArrayList;
15  import java.util.HashMap;
16  import java.util.Iterator;
17  import java.util.List;
18  import java.util.Map;
19  
20  import org.dom4j.Namespace;
21  import org.dom4j.QName;
22  import org.xml.sax.Attributes;
23  import org.xml.sax.ContentHandler;
24  import org.xml.sax.DTDHandler;
25  import org.xml.sax.SAXException;
26  import org.xml.sax.ext.DeclHandler;
27  import org.xml.sax.ext.LexicalHandler;
28  import org.xml.sax.helpers.AttributesImpl;
29  import org.xml.sax.helpers.DefaultHandler;
30  
31  /***
32   * <p>
33   * Records SAX events such that they may be "replayed" at a later time. Provides
34   * an alternative serialization approach when externalizing a DOM4J document.
35   * Rather than serializing a document as text and re-parsing, the sax events may
36   * be serialized instead.
37   * </p>
38   * Example usage:
39   * 
40   * <pre>
41   * 
42   *  
43   *  
44   *         SAXEventRecorder recorder = new SAXEventRecorder();
45   *         SAXWriter saxWriter = new SAXWriter(recorder, recorder);
46   *         saxWriter.write(document);
47   *         out.writeObject(recorder);
48   *         ...
49   *         SAXEventRecorder recorder = (SAXEventRecorder)in.readObject();
50   *         SAXContentHandler saxContentHandler = new SAXContentHandler();
51   *         recorder.replay(saxContentHandler);
52   *         Document document = saxContentHandler.getDocument();
53   *  
54   *   
55   *  
56   * </pre>
57   * 
58   * @author Todd Wolff (Bluestem Software)
59   */
60  public class SAXEventRecorder extends DefaultHandler implements LexicalHandler,
61          DeclHandler, DTDHandler, Externalizable {
62      public static final long serialVersionUID = 1;
63  
64      private static final byte STRING = 0;
65  
66      private static final byte OBJECT = 1;
67  
68      private static final byte NULL = 2;
69  
70      private List events = new ArrayList();
71  
72      private Map prefixMappings = new HashMap();
73  
74      private static final String XMLNS = "xmlns";
75  
76      private static final String EMPTY_STRING = "";
77  
78      public SAXEventRecorder() {
79      }
80  
81      public void replay(ContentHandler handler) throws SAXException {
82          SAXEvent saxEvent;
83          Iterator itr = events.iterator();
84  
85          while (itr.hasNext()) {
86              saxEvent = (SAXEvent) itr.next();
87  
88              switch (saxEvent.event) {
89                  // replay to ContentHandler
90                  case SAXEvent.PROCESSING_INSTRUCTION:
91                      handler.processingInstruction((String) saxEvent.getParm(0),
92                              (String) saxEvent.getParm(1));
93  
94                      break;
95  
96                  case SAXEvent.START_PREFIX_MAPPING:
97                      handler.startPrefixMapping((String) saxEvent.getParm(0),
98                              (String) saxEvent.getParm(1));
99  
100                     break;
101 
102                 case SAXEvent.END_PREFIX_MAPPING:
103                     handler.endPrefixMapping((String) saxEvent.getParm(0));
104 
105                     break;
106 
107                 case SAXEvent.START_DOCUMENT:
108                     handler.startDocument();
109 
110                     break;
111 
112                 case SAXEvent.END_DOCUMENT:
113                     handler.endDocument();
114 
115                     break;
116 
117                 case SAXEvent.START_ELEMENT:
118 
119                     AttributesImpl attributes = new AttributesImpl();
120                     List attParmList = (List) saxEvent.getParm(3);
121 
122                     if (attParmList != null) {
123                         Iterator attsItr = attParmList.iterator();
124 
125                         while (attsItr.hasNext()) {
126                             String[] attParms = (String[]) attsItr.next();
127                             attributes.addAttribute(attParms[0], attParms[1],
128                                     attParms[2], attParms[3], attParms[4]);
129                         }
130                     }
131 
132                     handler.startElement((String) saxEvent.getParm(0),
133                             (String) saxEvent.getParm(1), (String) saxEvent
134                                     .getParm(2), attributes);
135 
136                     break;
137 
138                 case SAXEvent.END_ELEMENT:
139                     handler.endElement((String) saxEvent.getParm(0),
140                             (String) saxEvent.getParm(1), (String) saxEvent
141                                     .getParm(2));
142 
143                     break;
144 
145                 case SAXEvent.CHARACTERS:
146 
147                     char[] chars = (char[]) saxEvent.getParm(0);
148                     int start = ((Integer) saxEvent.getParm(1)).intValue();
149                     int end = ((Integer) saxEvent.getParm(2)).intValue();
150                     handler.characters(chars, start, end);
151 
152                     break;
153 
154                 // replay to LexicalHandler
155                 case SAXEvent.START_DTD:
156                     ((LexicalHandler) handler).startDTD((String) saxEvent
157                             .getParm(0), (String) saxEvent.getParm(1),
158                             (String) saxEvent.getParm(2));
159 
160                     break;
161 
162                 case SAXEvent.END_DTD:
163                     ((LexicalHandler) handler).endDTD();
164 
165                     break;
166 
167                 case SAXEvent.START_ENTITY:
168                     ((LexicalHandler) handler).startEntity((String) saxEvent
169                             .getParm(0));
170 
171                     break;
172 
173                 case SAXEvent.END_ENTITY:
174                     ((LexicalHandler) handler).endEntity((String) saxEvent
175                             .getParm(0));
176 
177                     break;
178 
179                 case SAXEvent.START_CDATA:
180                     ((LexicalHandler) handler).startCDATA();
181 
182                     break;
183 
184                 case SAXEvent.END_CDATA:
185                     ((LexicalHandler) handler).endCDATA();
186 
187                     break;
188 
189                 case SAXEvent.COMMENT:
190 
191                     char[] cchars = (char[]) saxEvent.getParm(0);
192                     int cstart = ((Integer) saxEvent.getParm(1)).intValue();
193                     int cend = ((Integer) saxEvent.getParm(2)).intValue();
194                     ((LexicalHandler) handler).comment(cchars, cstart, cend);
195 
196                     break;
197 
198                 // replay to DeclHandler
199                 case SAXEvent.ELEMENT_DECL:
200                     ((DeclHandler) handler).elementDecl((String) saxEvent
201                             .getParm(0), (String) saxEvent.getParm(1));
202 
203                     break;
204 
205                 case SAXEvent.ATTRIBUTE_DECL:
206                     ((DeclHandler) handler).attributeDecl((String) saxEvent
207                             .getParm(0), (String) saxEvent.getParm(1),
208                             (String) saxEvent.getParm(2), (String) saxEvent
209                                     .getParm(3), (String) saxEvent.getParm(4));
210 
211                     break;
212 
213                 case SAXEvent.INTERNAL_ENTITY_DECL:
214                     ((DeclHandler) handler).internalEntityDecl(
215                             (String) saxEvent.getParm(0), (String) saxEvent
216                                     .getParm(1));
217 
218                     break;
219 
220                 case SAXEvent.EXTERNAL_ENTITY_DECL:
221                     ((DeclHandler) handler).externalEntityDecl(
222                             (String) saxEvent.getParm(0), (String) saxEvent
223                                     .getParm(1), (String) saxEvent.getParm(2));
224 
225                     break;
226 
227                 default:
228                     throw new SAXException("Unrecognized event: "
229                             + saxEvent.event);
230             }
231         }
232     }
233 
234     // ContentHandler interface
235     // -------------------------------------------------------------------------
236     public void processingInstruction(String target, String data)
237             throws SAXException {
238         SAXEvent saxEvent = new SAXEvent(SAXEvent.PROCESSING_INSTRUCTION);
239         saxEvent.addParm(target);
240         saxEvent.addParm(data);
241         events.add(saxEvent);
242     }
243 
244     public void startPrefixMapping(String prefix, String uri)
245             throws SAXException {
246         SAXEvent saxEvent = new SAXEvent(SAXEvent.START_PREFIX_MAPPING);
247         saxEvent.addParm(prefix);
248         saxEvent.addParm(uri);
249         events.add(saxEvent);
250     }
251 
252     public void endPrefixMapping(String prefix) throws SAXException {
253         SAXEvent saxEvent = new SAXEvent(SAXEvent.END_PREFIX_MAPPING);
254         saxEvent.addParm(prefix);
255         events.add(saxEvent);
256     }
257 
258     public void startDocument() throws SAXException {
259         SAXEvent saxEvent = new SAXEvent(SAXEvent.START_DOCUMENT);
260         events.add(saxEvent);
261     }
262 
263     public void endDocument() throws SAXException {
264         SAXEvent saxEvent = new SAXEvent(SAXEvent.END_DOCUMENT);
265         events.add(saxEvent);
266     }
267 
268     public void startElement(String namespaceURI, String localName,
269             String qualifiedName, Attributes attributes) throws SAXException {
270         SAXEvent saxEvent = new SAXEvent(SAXEvent.START_ELEMENT);
271         saxEvent.addParm(namespaceURI);
272         saxEvent.addParm(localName);
273         saxEvent.addParm(qualifiedName);
274 
275         QName qName = null;
276         if (namespaceURI != null) {
277             qName = new QName(localName, Namespace.get(namespaceURI));
278         } else {
279             qName = new QName(localName);
280         }
281 
282         if ((attributes != null) && (attributes.getLength() > 0)) {
283             List attParmList = new ArrayList(attributes.getLength());
284             String[] attParms = null;
285 
286             for (int i = 0; i < attributes.getLength(); i++) {
287 
288                 String attLocalName = attributes.getLocalName(i);
289 
290                 if (attLocalName.startsWith(XMLNS)) {
291 
292                     // if SAXWriter is writing a DOMDocument, namespace
293                     // decls are treated as attributes. record a start
294                     // prefix mapping event
295                     String prefix = null;
296                     if (attLocalName.length() > 5) {
297                         prefix = attLocalName.substring(6);
298                     } else {
299                         prefix = EMPTY_STRING;
300                     }
301 
302                     SAXEvent prefixEvent = new SAXEvent(
303                             SAXEvent.START_PREFIX_MAPPING);
304                     prefixEvent.addParm(prefix);
305                     prefixEvent.addParm(attributes.getValue(i));
306                     events.add(prefixEvent);
307 
308                     // 'register' the prefix so that we can generate
309                     // an end prefix mapping event within endElement
310                     List prefixes = (List) prefixMappings.get(qName);
311                     if (prefixes == null) {
312                         prefixes = new ArrayList();
313                         prefixMappings.put(qName, prefixes);
314                     }
315                     prefixes.add(prefix);
316 
317                 } else {
318 
319                     attParms = new String[5];
320                     attParms[0] = attributes.getURI(i);
321                     attParms[1] = attLocalName;
322                     attParms[2] = attributes.getQName(i);
323                     attParms[3] = attributes.getType(i);
324                     attParms[4] = attributes.getValue(i);
325                     attParmList.add(attParms);
326 
327                 }
328 
329             }
330 
331             saxEvent.addParm(attParmList);
332         }
333 
334         events.add(saxEvent);
335     }
336 
337     public void endElement(String namespaceURI, String localName, String qName)
338             throws SAXException {
339 
340         SAXEvent saxEvent = new SAXEvent(SAXEvent.END_ELEMENT);
341         saxEvent.addParm(namespaceURI);
342         saxEvent.addParm(localName);
343         saxEvent.addParm(qName);
344         events.add(saxEvent);
345 
346         // check to see if a we issued a start prefix mapping event
347         // for DOMDocument namespace decls
348 
349         QName elementName = null;
350         if (namespaceURI != null) {
351             elementName = new QName(localName, Namespace.get(namespaceURI));
352         } else {
353             elementName = new QName(localName);
354         }
355 
356         List prefixes = (List) prefixMappings.get(elementName);
357         if (prefixes != null) {
358             Iterator itr = prefixes.iterator();
359             while (itr.hasNext()) {
360                 SAXEvent prefixEvent = 
361                         new SAXEvent(SAXEvent.END_PREFIX_MAPPING);
362                 prefixEvent.addParm(itr.next());
363                 events.add(prefixEvent);
364             }
365         }
366 
367     }
368 
369     public void characters(char[] ch, int start, int end) throws SAXException {
370         SAXEvent saxEvent = new SAXEvent(SAXEvent.CHARACTERS);
371         saxEvent.addParm(ch);
372         saxEvent.addParm(new Integer(start));
373         saxEvent.addParm(new Integer(end));
374         events.add(saxEvent);
375     }
376 
377     // LexicalHandler interface
378     // -------------------------------------------------------------------------
379     public void startDTD(String name, String publicId, String systemId)
380             throws SAXException {
381         SAXEvent saxEvent = new SAXEvent(SAXEvent.START_DTD);
382         saxEvent.addParm(name);
383         saxEvent.addParm(publicId);
384         saxEvent.addParm(systemId);
385         events.add(saxEvent);
386     }
387 
388     public void endDTD() throws SAXException {
389         SAXEvent saxEvent = new SAXEvent(SAXEvent.END_DTD);
390         events.add(saxEvent);
391     }
392 
393     public void startEntity(String name) throws SAXException {
394         SAXEvent saxEvent = new SAXEvent(SAXEvent.START_ENTITY);
395         saxEvent.addParm(name);
396         events.add(saxEvent);
397     }
398 
399     public void endEntity(String name) throws SAXException {
400         SAXEvent saxEvent = new SAXEvent(SAXEvent.END_ENTITY);
401         saxEvent.addParm(name);
402         events.add(saxEvent);
403     }
404 
405     public void startCDATA() throws SAXException {
406         SAXEvent saxEvent = new SAXEvent(SAXEvent.START_CDATA);
407         events.add(saxEvent);
408     }
409 
410     public void endCDATA() throws SAXException {
411         SAXEvent saxEvent = new SAXEvent(SAXEvent.END_CDATA);
412         events.add(saxEvent);
413     }
414 
415     public void comment(char[] ch, int start, int end) throws SAXException {
416         SAXEvent saxEvent = new SAXEvent(SAXEvent.COMMENT);
417         saxEvent.addParm(ch);
418         saxEvent.addParm(new Integer(start));
419         saxEvent.addParm(new Integer(end));
420         events.add(saxEvent);
421     }
422 
423     // DeclHandler interface
424     // -------------------------------------------------------------------------
425     public void elementDecl(String name, String model) throws SAXException {
426         SAXEvent saxEvent = new SAXEvent(SAXEvent.ELEMENT_DECL);
427         saxEvent.addParm(name);
428         saxEvent.addParm(model);
429         events.add(saxEvent);
430     }
431 
432     public void attributeDecl(String eName, String aName, String type,
433             String valueDefault, String value) throws SAXException {
434         SAXEvent saxEvent = new SAXEvent(SAXEvent.ATTRIBUTE_DECL);
435         saxEvent.addParm(eName);
436         saxEvent.addParm(aName);
437         saxEvent.addParm(type);
438         saxEvent.addParm(valueDefault);
439         saxEvent.addParm(value);
440         events.add(saxEvent);
441     }
442 
443     public void internalEntityDecl(String name, String value)
444             throws SAXException {
445         SAXEvent saxEvent = new SAXEvent(SAXEvent.INTERNAL_ENTITY_DECL);
446         saxEvent.addParm(name);
447         saxEvent.addParm(value);
448         events.add(saxEvent);
449     }
450 
451     public void externalEntityDecl(String name, String publicId, String sysId)
452             throws SAXException {
453         SAXEvent saxEvent = new SAXEvent(SAXEvent.EXTERNAL_ENTITY_DECL);
454         saxEvent.addParm(name);
455         saxEvent.addParm(publicId);
456         saxEvent.addParm(sysId);
457         events.add(saxEvent);
458     }
459 
460     public void writeExternal(ObjectOutput out) throws IOException {
461         if (events == null) {
462             out.writeByte(NULL);
463         } else {
464             out.writeByte(OBJECT);
465             out.writeObject(events);
466         }
467     }
468 
469     public void readExternal(ObjectInput in) throws ClassNotFoundException,
470             IOException {
471         if (in.readByte() != NULL) {
472             events = (List) in.readObject();
473         }
474     }
475 
476     // SAXEvent inner class
477     // -------------------------------------------------------------------------
478     static class SAXEvent implements Externalizable {
479         public static final long serialVersionUID = 1;
480 
481         static final byte PROCESSING_INSTRUCTION = 1;
482 
483         static final byte START_PREFIX_MAPPING = 2;
484 
485         static final byte END_PREFIX_MAPPING = 3;
486 
487         static final byte START_DOCUMENT = 4;
488 
489         static final byte END_DOCUMENT = 5;
490 
491         static final byte START_ELEMENT = 6;
492 
493         static final byte END_ELEMENT = 7;
494 
495         static final byte CHARACTERS = 8;
496 
497         static final byte START_DTD = 9;
498 
499         static final byte END_DTD = 10;
500 
501         static final byte START_ENTITY = 11;
502 
503         static final byte END_ENTITY = 12;
504 
505         static final byte START_CDATA = 13;
506 
507         static final byte END_CDATA = 14;
508 
509         static final byte COMMENT = 15;
510 
511         static final byte ELEMENT_DECL = 16;
512 
513         static final byte ATTRIBUTE_DECL = 17;
514 
515         static final byte INTERNAL_ENTITY_DECL = 18;
516 
517         static final byte EXTERNAL_ENTITY_DECL = 19;
518 
519         protected byte event;
520 
521         protected List parms;
522 
523         public SAXEvent() {
524         }
525 
526         SAXEvent(byte event) {
527             this.event = event;
528         }
529 
530         void addParm(Object parm) {
531             if (parms == null) {
532                 parms = new ArrayList(3);
533             }
534 
535             parms.add(parm);
536         }
537 
538         Object getParm(int index) {
539             if ((parms != null) && (index < parms.size())) {
540                 return parms.get(index);
541             } else {
542                 return null;
543             }
544         }
545 
546         public void writeExternal(ObjectOutput out) throws IOException {
547             out.writeByte(event);
548 
549             if (parms == null) {
550                 out.writeByte(NULL);
551             } else {
552                 out.writeByte(OBJECT);
553                 out.writeObject(parms);
554             }
555         }
556 
557         public void readExternal(ObjectInput in) throws ClassNotFoundException,
558                 IOException {
559             event = in.readByte();
560 
561             if (in.readByte() != NULL) {
562                 parms = (List) in.readObject();
563             }
564         }
565     }
566 }
567 
568 /*
569  * Redistribution and use of this software and associated documentation
570  * ("Software"), with or without modification, are permitted provided that the
571  * following conditions are met:
572  * 
573  * 1. Redistributions of source code must retain copyright statements and
574  * notices. Redistributions must also contain a copy of this document.
575  * 
576  * 2. Redistributions in binary form must reproduce the above copyright notice,
577  * this list of conditions and the following disclaimer in the documentation
578  * and/or other materials provided with the distribution.
579  * 
580  * 3. The name "DOM4J" must not be used to endorse or promote products derived
581  * from this Software without prior written permission of MetaStuff, Ltd. For
582  * written permission, please contact dom4j-info@metastuff.com.
583  * 
584  * 4. Products derived from this Software may not be called "DOM4J" nor may
585  * "DOM4J" appear in their names without prior written permission of MetaStuff,
586  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
587  * 
588  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
589  * 
590  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
591  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
592  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
593  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
594  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
595  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
596  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
597  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
598  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
599  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
600  * POSSIBILITY OF SUCH DAMAGE.
601  * 
602  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
603  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/SAXReader.html0000644000175000017500000024704610242117671020655 0ustar ebourgebourg SAXReader xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.io.File;
11  import java.io.FileInputStream;
12  import java.io.FileNotFoundException;
13  import java.io.InputStream;
14  import java.io.Reader;
15  import java.io.Serializable;
16  import java.net.URL;
17  
18  import org.dom4j.Document;
19  import org.dom4j.DocumentException;
20  import org.dom4j.DocumentFactory;
21  import org.dom4j.ElementHandler;
22  
23  import org.xml.sax.EntityResolver;
24  import org.xml.sax.ErrorHandler;
25  import org.xml.sax.InputSource;
26  import org.xml.sax.SAXException;
27  import org.xml.sax.SAXParseException;
28  import org.xml.sax.XMLFilter;
29  import org.xml.sax.XMLReader;
30  import org.xml.sax.helpers.DefaultHandler;
31  import org.xml.sax.helpers.XMLReaderFactory;
32  
33  /***
34   * <p>
35   * <code>SAXReader</code> creates a DOM4J tree from SAX parsing events.
36   * </p>
37   * 
38   * <p>
39   * The actual SAX parser that is used by this class is configurable so you can
40   * use your favourite SAX parser if you wish. DOM4J comes configured with its
41   * own SAX parser so you do not need to worry about configuring the SAX parser.
42   * </p>
43   * 
44   * <p>
45   * To explicitly configure the SAX parser that is used via Java code you can use
46   * a constructor or use the {@link #setXMLReader(XMLReader)}or {@link
47   * #setXMLReaderClassName(String)} methods.
48   * </p>
49   * 
50   * <p>
51   * If the parser is not specified explicitly then the standard SAX policy of
52   * using the <code>org.xml.sax.driver</code> system property is used to
53   * determine the implementation class of {@link XMLReader}.
54   * </p>
55   * 
56   * <p>
57   * If the <code>org.xml.sax.driver</code> system property is not defined then
58   * JAXP is used via reflection (so that DOM4J is not explicitly dependent on the
59   * JAXP classes) to load the JAXP configured SAXParser. If there is any error
60   * creating a JAXP SAXParser an informational message is output and then the
61   * default (Aelfred) SAX parser is used instead.
62   * </p>
63   * 
64   * <p>
65   * If you are trying to use JAXP to explicitly set your SAX parser and are
66   * experiencing problems, you can turn on verbose error reporting by defining
67   * the system property <code>org.dom4j.verbose</code> to be "true" which will
68   * output a more detailed description of why JAXP could not find a SAX parser
69   * </p>
70   * 
71   * <p>
72   * For more information on JAXP please go to <a
73   * href="http://java.sun.com/xml/">Sun's Java &amp; XML site </a>
74   * </p>
75   * 
76   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
77   * @version $Revision: 1.58 $
78   */
79  public class SAXReader {
80      private static final String SAX_STRING_INTERNING = 
81              "http://xml.org/sax/features/string-interning";
82      private static final String SAX_NAMESPACE_PREFIXES = 
83              "http://xml.org/sax/features/namespace-prefixes";
84      private static final String SAX_NAMESPACES = 
85              "http://xml.org/sax/features/namespaces";
86      private static final String SAX_DECL_HANDLER = 
87              "http://xml.org/sax/properties/declaration-handler";
88      private static final String SAX_LEXICAL_HANDLER = 
89              "http://xml.org/sax/properties/lexical-handler";
90      private static final String SAX_LEXICALHANDLER = 
91              "http://xml.org/sax/handlers/LexicalHandler";
92  
93      /*** <code>DocumentFactory</code> used to create new document objects */
94      private DocumentFactory factory;
95  
96      /*** <code>XMLReader</code> used to parse the SAX events */
97      private XMLReader xmlReader;
98  
99      /*** Whether validation should occur */
100     private boolean validating;
101 
102     /*** DispatchHandler to call when each <code>Element</code> is encountered */
103     private DispatchHandler dispatchHandler;
104 
105     /*** ErrorHandler class to use */
106     private ErrorHandler errorHandler;
107 
108     /*** The entity resolver */
109     private EntityResolver entityResolver;
110 
111     /*** Should element & attribute names and namespace URIs be interned? */
112     private boolean stringInternEnabled = true;
113 
114     /*** Should internal DTD declarations be expanded into a List in the DTD */
115     private boolean includeInternalDTDDeclarations = false;
116 
117     /*** Should external DTD declarations be expanded into a List in the DTD */
118     private boolean includeExternalDTDDeclarations = false;
119 
120     /*** Whether adjacent text nodes should be merged */
121     private boolean mergeAdjacentText = false;
122 
123     /*** Holds value of property stripWhitespaceText. */
124     private boolean stripWhitespaceText = false;
125 
126     /*** Should we ignore comments */
127     private boolean ignoreComments = false;
128 
129     /*** Encoding of InputSource - null means system default encoding */
130     private String encoding = null;
131 
132     // private boolean includeExternalGeneralEntities = false;
133     // private boolean includeExternalParameterEntities = false;
134 
135     /*** The SAX filter used to filter SAX events */
136     private XMLFilter xmlFilter;
137 
138     public SAXReader() {
139     }
140 
141     public SAXReader(boolean validating) {
142         this.validating = validating;
143     }
144 
145     public SAXReader(DocumentFactory factory) {
146         this.factory = factory;
147     }
148 
149     public SAXReader(DocumentFactory factory, boolean validating) {
150         this.factory = factory;
151         this.validating = validating;
152     }
153 
154     public SAXReader(XMLReader xmlReader) {
155         this.xmlReader = xmlReader;
156     }
157 
158     public SAXReader(XMLReader xmlReader, boolean validating) {
159         this.xmlReader = xmlReader;
160         this.validating = validating;
161     }
162 
163     public SAXReader(String xmlReaderClassName) throws SAXException {
164         if (xmlReaderClassName != null) {
165             this.xmlReader = XMLReaderFactory
166                     .createXMLReader(xmlReaderClassName);
167         }
168     }
169 
170     public SAXReader(String xmlReaderClassName, boolean validating)
171             throws SAXException {
172         if (xmlReaderClassName != null) {
173             this.xmlReader = XMLReaderFactory
174                     .createXMLReader(xmlReaderClassName);
175         }
176 
177         this.validating = validating;
178     }
179 
180     /***
181      * Allows a SAX property to be set on the underlying SAX parser. This can be
182      * useful to set parser-specific properties such as the location of schema
183      * or DTD resources. Though use this method with caution as it has the
184      * possibility of breaking the standard behaviour. An alternative to calling
185      * this method is to correctly configure an XMLReader object instance and
186      * call the {@link #setXMLReader(XMLReader)}method
187      * 
188      * @param name
189      *            is the SAX property name
190      * @param value
191      *            is the value of the SAX property
192      * 
193      * @throws SAXException
194      *             if the XMLReader could not be created or the property could
195      *             not be changed.
196      */
197     public void setProperty(String name, Object value) throws SAXException {
198         getXMLReader().setProperty(name, value);
199     }
200 
201     /***
202      * Sets a SAX feature on the underlying SAX parser. This can be useful to
203      * set parser-specific features. Though use this method with caution as it
204      * has the possibility of breaking the standard behaviour. An alternative to
205      * calling this method is to correctly configure an XMLReader object
206      * instance and call the {@link #setXMLReader(XMLReader)}method
207      * 
208      * @param name
209      *            is the SAX feature name
210      * @param value
211      *            is the value of the SAX feature
212      * 
213      * @throws SAXException
214      *             if the XMLReader could not be created or the feature could
215      *             not be changed.
216      */
217     public void setFeature(String name, boolean value) throws SAXException {
218         getXMLReader().setFeature(name, value);
219     }
220 
221     /***
222      * <p>
223      * Reads a Document from the given <code>File</code>
224      * </p>
225      * 
226      * @param file
227      *            is the <code>File</code> to read from.
228      * 
229      * @return the newly created Document instance
230      * 
231      * @throws DocumentException
232      *             if an error occurs during parsing.
233      */
234     public Document read(File file) throws DocumentException {
235         try {
236             /*
237              * We cannot convert the file to an URL because if the filename
238              * contains '#' characters, there will be problems with the URL in
239              * the InputSource (because a URL like
240              * http://myhost.com/index#anchor is treated the same as
241              * http://myhost.com/index) Thanks to Christian Oetterli
242              */
243             InputSource source = new InputSource(new FileInputStream(file));
244             if (this.encoding != null) {
245                 source.setEncoding(this.encoding);
246             }
247             String path = file.getAbsolutePath();
248 
249             if (path != null) {
250                 // Code taken from Ant FileUtils
251                 StringBuffer sb = new StringBuffer("file://");
252 
253                 // add an extra slash for filesystems with drive-specifiers
254                 if (!path.startsWith(File.separator)) {
255                     sb.append("/");
256                 }
257 
258                 path = path.replace('//', '/');
259                 sb.append(path);
260 
261                 source.setSystemId(sb.toString());
262             }
263 
264             return read(source);
265         } catch (FileNotFoundException e) {
266             throw new DocumentException(e.getMessage(), e);
267         }
268     }
269 
270     /***
271      * <p>
272      * Reads a Document from the given <code>URL</code> using SAX
273      * </p>
274      * 
275      * @param url
276      *            <code>URL</code> to read from.
277      * 
278      * @return the newly created Document instance
279      * 
280      * @throws DocumentException
281      *             if an error occurs during parsing.
282      */
283     public Document read(URL url) throws DocumentException {
284         String systemID = url.toExternalForm();
285 
286         InputSource source = new InputSource(systemID);
287         if (this.encoding != null) {
288             source.setEncoding(this.encoding);
289         }
290 
291         return read(source);
292     }
293 
294     /***
295      * <p>
296      * Reads a Document from the given URL or filename using SAX.
297      * </p>
298      * 
299      * <p>
300      * If the systemId contains a <code>':'</code> character then it is
301      * assumed to be a URL otherwise its assumed to be a file name. If you want
302      * finer grained control over this mechansim then please explicitly pass in
303      * either a {@link URL}or a {@link File}instance instead of a {@link
304      * String} to denote the source of the document.
305      * </p>
306      * 
307      * @param systemId
308      *            is a URL for a document or a file name.
309      * 
310      * @return the newly created Document instance
311      * 
312      * @throws DocumentException
313      *             if an error occurs during parsing.
314      */
315     public Document read(String systemId) throws DocumentException {
316         InputSource source = new InputSource(systemId);
317         if (this.encoding != null) {
318             source.setEncoding(this.encoding);
319         }
320 
321         return read(source);
322     }
323 
324     /***
325      * <p>
326      * Reads a Document from the given stream using SAX
327      * </p>
328      * 
329      * @param in
330      *            <code>InputStream</code> to read from.
331      * 
332      * @return the newly created Document instance
333      * 
334      * @throws DocumentException
335      *             if an error occurs during parsing.
336      */
337     public Document read(InputStream in) throws DocumentException {
338         InputSource source = new InputSource(in);
339         if (this.encoding != null) {
340             source.setEncoding(this.encoding);
341         }
342 
343         return read(source);
344     }
345 
346     /***
347      * <p>
348      * Reads a Document from the given <code>Reader</code> using SAX
349      * </p>
350      * 
351      * @param reader
352      *            is the reader for the input
353      * 
354      * @return the newly created Document instance
355      * 
356      * @throws DocumentException
357      *             if an error occurs during parsing.
358      */
359     public Document read(Reader reader) throws DocumentException {
360         InputSource source = new InputSource(reader);
361         if (this.encoding != null) {
362             source.setEncoding(this.encoding);
363         }
364 
365         return read(source);
366     }
367 
368     /***
369      * <p>
370      * Reads a Document from the given stream using SAX
371      * </p>
372      * 
373      * @param in
374      *            <code>InputStream</code> to read from.
375      * @param systemId
376      *            is the URI for the input
377      * 
378      * @return the newly created Document instance
379      * 
380      * @throws DocumentException
381      *             if an error occurs during parsing.
382      */
383     public Document read(InputStream in, String systemId)
384             throws DocumentException {
385         InputSource source = new InputSource(in);
386         source.setSystemId(systemId);
387         if (this.encoding != null) {
388             source.setEncoding(this.encoding);
389         }
390 
391         return read(source);
392     }
393 
394     /***
395      * <p>
396      * Reads a Document from the given <code>Reader</code> using SAX
397      * </p>
398      * 
399      * @param reader
400      *            is the reader for the input
401      * @param systemId
402      *            is the URI for the input
403      * 
404      * @return the newly created Document instance
405      * 
406      * @throws DocumentException
407      *             if an error occurs during parsing.
408      */
409     public Document read(Reader reader, String systemId)
410             throws DocumentException {
411         InputSource source = new InputSource(reader);
412         source.setSystemId(systemId);
413         if (this.encoding != null) {
414             source.setEncoding(this.encoding);
415         }
416 
417         return read(source);
418     }
419 
420     /***
421      * <p>
422      * Reads a Document from the given <code>InputSource</code> using SAX
423      * </p>
424      * 
425      * @param in
426      *            <code>InputSource</code> to read from.
427      * 
428      * @return the newly created Document instance
429      * 
430      * @throws DocumentException
431      *             if an error occurs during parsing.
432      */
433     public Document read(InputSource in) throws DocumentException {
434         try {
435             XMLReader reader = getXMLReader();
436 
437             reader = installXMLFilter(reader);
438 
439             EntityResolver thatEntityResolver = this.entityResolver;
440 
441             if (thatEntityResolver == null) {
442                 thatEntityResolver = createDefaultEntityResolver(in
443                         .getSystemId());
444                 this.entityResolver = thatEntityResolver;
445             }
446 
447             reader.setEntityResolver(thatEntityResolver);
448 
449             SAXContentHandler contentHandler = createContentHandler(reader);
450             contentHandler.setEntityResolver(thatEntityResolver);
451             contentHandler.setInputSource(in);
452 
453             boolean internal = isIncludeInternalDTDDeclarations();
454             boolean external = isIncludeExternalDTDDeclarations();
455 
456             contentHandler.setIncludeInternalDTDDeclarations(internal);
457             contentHandler.setIncludeExternalDTDDeclarations(external);
458             contentHandler.setMergeAdjacentText(isMergeAdjacentText());
459             contentHandler.setStripWhitespaceText(isStripWhitespaceText());
460             contentHandler.setIgnoreComments(isIgnoreComments());
461             reader.setContentHandler(contentHandler);
462 
463             configureReader(reader, contentHandler);
464 
465             reader.parse(in);
466 
467             return contentHandler.getDocument();
468         } catch (Exception e) {
469             if (e instanceof SAXParseException) {
470                 // e.printStackTrace();
471                 SAXParseException parseException = (SAXParseException) e;
472                 String systemId = parseException.getSystemId();
473 
474                 if (systemId == null) {
475                     systemId = "";
476                 }
477 
478                 String message = "Error on line "
479                         + parseException.getLineNumber() + " of document "
480                         + systemId + " : " + parseException.getMessage();
481 
482                 throw new DocumentException(message, e);
483             } else {
484                 throw new DocumentException(e.getMessage(), e);
485             }
486         }
487     }
488 
489     // Properties
490     // -------------------------------------------------------------------------
491 
492     /***
493      * DOCUMENT ME!
494      * 
495      * @return the validation mode, true if validating will be done otherwise
496      *         false.
497      */
498     public boolean isValidating() {
499         return validating;
500     }
501 
502     /***
503      * Sets the validation mode.
504      * 
505      * @param validation
506      *            indicates whether or not validation should occur.
507      */
508     public void setValidation(boolean validation) {
509         this.validating = validation;
510     }
511 
512     /***
513      * DOCUMENT ME!
514      * 
515      * @return whether internal DTD declarations should be expanded into the
516      *         DocumentType object or not.
517      */
518     public boolean isIncludeInternalDTDDeclarations() {
519         return includeInternalDTDDeclarations;
520     }
521 
522     /***
523      * Sets whether internal DTD declarations should be expanded into the
524      * DocumentType object or not.
525      * 
526      * @param include
527      *            whether or not DTD declarations should be expanded and
528      *            included into the DocumentType object.
529      */
530     public void setIncludeInternalDTDDeclarations(boolean include) {
531         this.includeInternalDTDDeclarations = include;
532     }
533 
534     /***
535      * DOCUMENT ME!
536      * 
537      * @return whether external DTD declarations should be expanded into the
538      *         DocumentType object or not.
539      */
540     public boolean isIncludeExternalDTDDeclarations() {
541         return includeExternalDTDDeclarations;
542     }
543 
544     /***
545      * Sets whether DTD external declarations should be expanded into the
546      * DocumentType object or not.
547      * 
548      * @param include
549      *            whether or not DTD declarations should be expanded and
550      *            included into the DocumentType object.
551      */
552     public void setIncludeExternalDTDDeclarations(boolean include) {
553         this.includeExternalDTDDeclarations = include;
554     }
555 
556     /***
557      * Sets whether String interning is enabled or disabled for element &
558      * attribute names and namespace URIs. This proprety is enabled by default.
559      * 
560      * @return DOCUMENT ME!
561      */
562     public boolean isStringInternEnabled() {
563         return stringInternEnabled;
564     }
565 
566     /***
567      * Sets whether String interning is enabled or disabled for element &
568      * attribute names and namespace URIs
569      * 
570      * @param stringInternEnabled
571      *            DOCUMENT ME!
572      */
573     public void setStringInternEnabled(boolean stringInternEnabled) {
574         this.stringInternEnabled = stringInternEnabled;
575     }
576 
577     /***
578      * Returns whether adjacent text nodes should be merged together.
579      * 
580      * @return Value of property mergeAdjacentText.
581      */
582     public boolean isMergeAdjacentText() {
583         return mergeAdjacentText;
584     }
585 
586     /***
587      * Sets whether or not adjacent text nodes should be merged together when
588      * parsing.
589      * 
590      * @param mergeAdjacentText
591      *            New value of property mergeAdjacentText.
592      */
593     public void setMergeAdjacentText(boolean mergeAdjacentText) {
594         this.mergeAdjacentText = mergeAdjacentText;
595     }
596 
597     /***
598      * Sets whether whitespace between element start and end tags should be
599      * ignored
600      * 
601      * @return Value of property stripWhitespaceText.
602      */
603     public boolean isStripWhitespaceText() {
604         return stripWhitespaceText;
605     }
606 
607     /***
608      * Sets whether whitespace between element start and end tags should be
609      * ignored.
610      * 
611      * @param stripWhitespaceText
612      *            New value of property stripWhitespaceText.
613      */
614     public void setStripWhitespaceText(boolean stripWhitespaceText) {
615         this.stripWhitespaceText = stripWhitespaceText;
616     }
617 
618     /***
619      * Returns whether we should ignore comments or not.
620      * 
621      * @return boolean
622      */
623     public boolean isIgnoreComments() {
624         return ignoreComments;
625     }
626 
627     /***
628      * Sets whether we should ignore comments or not.
629      * 
630      * @param ignoreComments
631      *            whether we should ignore comments or not.
632      */
633     public void setIgnoreComments(boolean ignoreComments) {
634         this.ignoreComments = ignoreComments;
635     }
636 
637     /***
638      * DOCUMENT ME!
639      * 
640      * @return the <code>DocumentFactory</code> used to create document
641      *         objects
642      */
643     public DocumentFactory getDocumentFactory() {
644         if (factory == null) {
645             factory = DocumentFactory.getInstance();
646         }
647 
648         return factory;
649     }
650 
651     /***
652      * <p>
653      * This sets the <code>DocumentFactory</code> used to create new
654      * documents. This method allows the building of custom DOM4J tree objects
655      * to be implemented easily using a custom derivation of
656      * {@link DocumentFactory}
657      * </p>
658      * 
659      * @param documentFactory
660      *            <code>DocumentFactory</code> used to create DOM4J objects
661      */
662     public void setDocumentFactory(DocumentFactory documentFactory) {
663         this.factory = documentFactory;
664     }
665 
666     /***
667      * DOCUMENT ME!
668      * 
669      * @return the <code>ErrorHandler</code> used by SAX
670      */
671     public ErrorHandler getErrorHandler() {
672         return errorHandler;
673     }
674 
675     /***
676      * Sets the <code>ErrorHandler</code> used by the SAX
677      * <code>XMLReader</code>.
678      * 
679      * @param errorHandler
680      *            is the <code>ErrorHandler</code> used by SAX
681      */
682     public void setErrorHandler(ErrorHandler errorHandler) {
683         this.errorHandler = errorHandler;
684     }
685 
686     /***
687      * Returns the current entity resolver used to resolve entities
688      * 
689      * @return DOCUMENT ME!
690      */
691     public EntityResolver getEntityResolver() {
692         return entityResolver;
693     }
694 
695     /***
696      * Sets the entity resolver used to resolve entities.
697      * 
698      * @param entityResolver
699      *            DOCUMENT ME!
700      */
701     public void setEntityResolver(EntityResolver entityResolver) {
702         this.entityResolver = entityResolver;
703     }
704 
705     /***
706      * DOCUMENT ME!
707      * 
708      * @return the <code>XMLReader</code> used to parse SAX events
709      * 
710      * @throws SAXException
711      *             DOCUMENT ME!
712      */
713     public XMLReader getXMLReader() throws SAXException {
714         if (xmlReader == null) {
715             xmlReader = createXMLReader();
716         }
717 
718         return xmlReader;
719     }
720 
721     /***
722      * Sets the <code>XMLReader</code> used to parse SAX events
723      * 
724      * @param reader
725      *            is the <code>XMLReader</code> to parse SAX events
726      */
727     public void setXMLReader(XMLReader reader) {
728         this.xmlReader = reader;
729     }
730 
731     /***
732      * Returns encoding used for InputSource (null means system default
733      * encoding)
734      * 
735      * @return encoding used for InputSource
736      * 
737      */
738     public String getEncoding() {
739         return encoding;
740     }
741 
742     /***
743      * Sets encoding used for InputSource (null means system default encoding)
744      * 
745      * @param encoding
746      *            is encoding used for InputSource
747      */
748     public void setEncoding(String encoding) {
749         this.encoding = encoding;
750     }
751 
752     /***
753      * Sets the class name of the <code>XMLReader</code> to be used to parse
754      * SAX events.
755      * 
756      * @param xmlReaderClassName
757      *            is the class name of the <code>XMLReader</code> to parse SAX
758      *            events
759      * 
760      * @throws SAXException
761      *             DOCUMENT ME!
762      */
763     public void setXMLReaderClassName(String xmlReaderClassName)
764             throws SAXException {
765         setXMLReader(XMLReaderFactory.createXMLReader(xmlReaderClassName));
766     }
767 
768     /***
769      * Adds the <code>ElementHandler</code> to be called when the specified
770      * path is encounted.
771      * 
772      * @param path
773      *            is the path to be handled
774      * @param handler
775      *            is the <code>ElementHandler</code> to be called by the event
776      *            based processor.
777      */
778     public void addHandler(String path, ElementHandler handler) {
779         getDispatchHandler().addHandler(path, handler);
780     }
781 
782     /***
783      * Removes the <code>ElementHandler</code> from the event based processor,
784      * for the specified path.
785      * 
786      * @param path
787      *            is the path to remove the <code>ElementHandler</code> for.
788      */
789     public void removeHandler(String path) {
790         getDispatchHandler().removeHandler(path);
791     }
792 
793     /***
794      * When multiple <code>ElementHandler</code> instances have been
795      * registered, this will set a default <code>ElementHandler</code> to be
796      * called for any path which does <b>NOT </b> have a handler registered.
797      * 
798      * @param handler
799      *            is the <code>ElementHandler</code> to be called by the event
800      *            based processor.
801      */
802     public void setDefaultHandler(ElementHandler handler) {
803         getDispatchHandler().setDefaultHandler(handler);
804     }
805 
806     /***
807      * This method clears out all the existing handlers and default handler
808      * setting things back as if no handler existed. Useful when reusing an
809      * object instance.
810      */
811     public void resetHandlers() {
812         getDispatchHandler().resetHandlers();
813     }
814 
815     /***
816      * Returns the SAX filter being used to filter SAX events.
817      * 
818      * @return the SAX filter being used or null if no SAX filter is installed
819      */
820     public XMLFilter getXMLFilter() {
821         return xmlFilter;
822     }
823 
824     /***
825      * Sets the SAX filter to be used when filtering SAX events
826      * 
827      * @param filter
828      *            is the SAX filter to use or null to disable filtering
829      */
830     public void setXMLFilter(XMLFilter filter) {
831         this.xmlFilter = filter;
832     }
833 
834     // Implementation methods
835     // -------------------------------------------------------------------------
836 
837     /***
838      * Installs any XMLFilter objects required to allow the SAX event stream to
839      * be filtered and preprocessed before it gets to dom4j.
840      * 
841      * @param reader
842      *            DOCUMENT ME!
843      * 
844      * @return the new XMLFilter if applicable or the original XMLReader if no
845      *         filter is being used.
846      */
847     protected XMLReader installXMLFilter(XMLReader reader) {
848         XMLFilter filter = getXMLFilter();
849 
850         if (filter != null) {
851             // find the root XMLFilter
852             XMLFilter root = filter;
853 
854             while (true) {
855                 XMLReader parent = root.getParent();
856 
857                 if (parent instanceof XMLFilter) {
858                     root = (XMLFilter) parent;
859                 } else {
860                     break;
861                 }
862             }
863 
864             root.setParent(reader);
865 
866             return filter;
867         }
868 
869         return reader;
870     }
871 
872     protected DispatchHandler getDispatchHandler() {
873         if (dispatchHandler == null) {
874             dispatchHandler = new DispatchHandler();
875         }
876 
877         return dispatchHandler;
878     }
879 
880     protected void setDispatchHandler(DispatchHandler dispatchHandler) {
881         this.dispatchHandler = dispatchHandler;
882     }
883 
884     /***
885      * Factory Method to allow alternate methods of creating and configuring
886      * XMLReader objects
887      * 
888      * @return DOCUMENT ME!
889      * 
890      * @throws SAXException
891      *             DOCUMENT ME!
892      */
893     protected XMLReader createXMLReader() throws SAXException {
894         return SAXHelper.createXMLReader(isValidating());
895     }
896 
897     /***
898      * Configures the XMLReader before use
899      * 
900      * @param reader
901      *            DOCUMENT ME!
902      * @param handler
903      *            DOCUMENT ME!
904      * 
905      * @throws DocumentException
906      *             DOCUMENT ME!
907      */
908     protected void configureReader(XMLReader reader, DefaultHandler handler)
909             throws DocumentException {
910         // configure lexical handling
911         SAXHelper.setParserProperty(reader, SAX_LEXICALHANDLER, handler);
912 
913         // try alternate property just in case
914         SAXHelper.setParserProperty(reader, SAX_LEXICAL_HANDLER, handler);
915 
916         // register the DeclHandler
917         if (includeInternalDTDDeclarations || includeExternalDTDDeclarations) {
918             SAXHelper.setParserProperty(reader, SAX_DECL_HANDLER, handler);
919         }
920 
921         // configure namespace support
922         SAXHelper.setParserFeature(reader, SAX_NAMESPACES, true);
923 
924         SAXHelper.setParserFeature(reader, SAX_NAMESPACE_PREFIXES, false);
925 
926         // string interning
927         SAXHelper.setParserFeature(reader, SAX_STRING_INTERNING,
928                 isStringInternEnabled());
929 
930         // external entites
931         /*
932          * SAXHelper.setParserFeature( reader,
933          * "http://xml.org/sax/properties/external-general-entities",
934          * includeExternalGeneralEntities ); SAXHelper.setParserFeature( reader,
935          * "http://xml.org/sax/properties/external-parameter-entities",
936          * includeExternalParameterEntities );
937          */
938         // use Locator2 if possible
939         SAXHelper.setParserFeature(reader,
940                 "http://xml.org/sax/features/use-locator2", true);
941 
942         try {
943             // configure validation support
944             reader.setFeature("http://xml.org/sax/features/validation",
945                     isValidating());
946 
947             if (errorHandler != null) {
948                 reader.setErrorHandler(errorHandler);
949             } else {
950                 reader.setErrorHandler(handler);
951             }
952         } catch (Exception e) {
953             if (isValidating()) {
954                 throw new DocumentException("Validation not supported for"
955                         + " XMLReader: " + reader, e);
956             }
957         }
958     }
959 
960     /***
961      * Factory Method to allow user derived SAXContentHandler objects to be used
962      * 
963      * @param reader
964      *            DOCUMENT ME!
965      * 
966      * @return DOCUMENT ME!
967      */
968     protected SAXContentHandler createContentHandler(XMLReader reader) {
969         return new SAXContentHandler(getDocumentFactory(), dispatchHandler);
970     }
971 
972     protected EntityResolver createDefaultEntityResolver(String systemId) {
973         String prefix = null;
974 
975         if ((systemId != null) && (systemId.length() > 0)) {
976             int idx = systemId.lastIndexOf('/');
977 
978             if (idx > 0) {
979                 prefix = systemId.substring(0, idx + 1);
980             }
981         }
982 
983         return new SAXEntityResolver(prefix);
984     }
985 
986     protected static class SAXEntityResolver implements EntityResolver,
987             Serializable {
988         protected String uriPrefix;
989 
990         public SAXEntityResolver(String uriPrefix) {
991             this.uriPrefix = uriPrefix;
992         }
993 
994         public InputSource resolveEntity(String publicId, String systemId) {
995             // try create a relative URI reader...
996             if ((systemId != null) && (systemId.length() > 0)) {
997                 if ((uriPrefix != null) && (systemId.indexOf(':') <= 0)) {
998                     systemId = uriPrefix + systemId;
999                 }
1000             }
1001 
1002             return new InputSource(systemId);
1003         }
1004     }
1005 }
1006 
1007 /*
1008  * Redistribution and use of this software and associated documentation
1009  * ("Software"), with or without modification, are permitted provided that the
1010  * following conditions are met:
1011  * 
1012  * 1. Redistributions of source code must retain copyright statements and
1013  * notices. Redistributions must also contain a copy of this document.
1014  * 
1015  * 2. Redistributions in binary form must reproduce the above copyright notice,
1016  * this list of conditions and the following disclaimer in the documentation
1017  * and/or other materials provided with the distribution.
1018  * 
1019  * 3. The name "DOM4J" must not be used to endorse or promote products derived
1020  * from this Software without prior written permission of MetaStuff, Ltd. For
1021  * written permission, please contact dom4j-info@metastuff.com.
1022  * 
1023  * 4. Products derived from this Software may not be called "DOM4J" nor may
1024  * "DOM4J" appear in their names without prior written permission of MetaStuff,
1025  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
1026  * 
1027  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
1028  * 
1029  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
1030  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1031  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1032  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
1033  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
1034  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
1035  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
1036  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
1037  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
1038  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
1039  * POSSIBILITY OF SUCH DAMAGE.
1040  * 
1041  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
1042  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/SAXModifyContentHandler.html0000644000175000017500000006013110242117610023510 0ustar ebourgebourg SAXModifyContentHandler xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.io.IOException;
11  
12  import org.dom4j.DocumentFactory;
13  import org.dom4j.Element;
14  import org.dom4j.ElementHandler;
15  
16  import org.xml.sax.Attributes;
17  import org.xml.sax.Locator;
18  import org.xml.sax.SAXException;
19  
20  /***
21   * This extension of the SAXContentHandler writes SAX events immediately to the
22   * provided XMLWriter, unless some {@link org.dom4.ElementHandler}is still
23   * handling the current Element.
24   * 
25   * @author Wonne Keysers (Realsoftware.be)
26   * 
27   * @see org.dom4j.io.SAXContentHandler
28   */
29  class SAXModifyContentHandler extends SAXContentHandler {
30      private XMLWriter xmlWriter;
31  
32      public SAXModifyContentHandler() {
33      }
34  
35      public SAXModifyContentHandler(DocumentFactory documentFactory) {
36          super(documentFactory);
37      }
38  
39      public SAXModifyContentHandler(DocumentFactory documentFactory,
40              ElementHandler elementHandler) {
41          super(documentFactory, elementHandler);
42      }
43  
44      public SAXModifyContentHandler(DocumentFactory documentFactory,
45              ElementHandler elementHandler, ElementStack elementStack) {
46          super(documentFactory, elementHandler, elementStack);
47      }
48  
49      public void setXMLWriter(XMLWriter writer) {
50          this.xmlWriter = writer;
51      }
52  
53      public void startCDATA() throws SAXException {
54          super.startCDATA();
55  
56          if (!activeHandlers() && (xmlWriter != null)) {
57              xmlWriter.startCDATA();
58          }
59      }
60  
61      public void startDTD(String name, String publicId, String systemId)
62              throws SAXException {
63          super.startDTD(name, publicId, systemId);
64  
65          if (xmlWriter != null) {
66              xmlWriter.startDTD(name, publicId, systemId);
67          }
68      }
69  
70      public void endDTD() throws org.xml.sax.SAXException {
71          super.endDTD();
72  
73          if (xmlWriter != null) {
74              xmlWriter.endDTD();
75          }
76      }
77  
78      public void comment(char[] characters, int parm2, int parm3)
79              throws SAXException {
80          super.comment(characters, parm2, parm3);
81  
82          if (!activeHandlers() && (xmlWriter != null)) {
83              xmlWriter.comment(characters, parm2, parm3);
84          }
85      }
86  
87      public void startEntity(String name) throws SAXException {
88          super.startEntity(name);
89  
90          if (xmlWriter != null) {
91              xmlWriter.startEntity(name);
92          }
93      }
94  
95      public void endCDATA() throws org.xml.sax.SAXException {
96          super.endCDATA();
97  
98          if (!activeHandlers() && (xmlWriter != null)) {
99              xmlWriter.endCDATA();
100         }
101     }
102 
103     public void endEntity(String name) throws SAXException {
104         super.endEntity(name);
105 
106         if (xmlWriter != null) {
107             xmlWriter.endEntity(name);
108         }
109     }
110 
111     public void unparsedEntityDecl(String name, String publicId,
112             String systemId, String notation) throws SAXException {
113         super.unparsedEntityDecl(name, publicId, systemId, notation);
114 
115         if (!activeHandlers() && (xmlWriter != null)) {
116             xmlWriter.unparsedEntityDecl(name, publicId, systemId, notation);
117         }
118     }
119 
120     public void notationDecl(String name, String publicId, String systemId)
121             throws SAXException {
122         super.notationDecl(name, publicId, systemId);
123 
124         if (xmlWriter != null) {
125             xmlWriter.notationDecl(name, publicId, systemId);
126         }
127     }
128 
129     public void startElement(String uri, String localName, String qName,
130             Attributes atts) throws SAXException {
131         super.startElement(uri, localName, qName, atts);
132 
133         if (!activeHandlers() && (xmlWriter != null)) {
134             xmlWriter.startElement(uri, localName, qName, atts);
135         }
136     }
137 
138     public void startDocument() throws SAXException {
139         super.startDocument();
140 
141         if (xmlWriter != null) {
142             xmlWriter.startDocument();
143         }
144     }
145 
146     public void ignorableWhitespace(char[] parm1, int parm2, int parm3)
147             throws SAXException {
148         super.ignorableWhitespace(parm1, parm2, parm3);
149 
150         if (!activeHandlers() && (xmlWriter != null)) {
151             xmlWriter.ignorableWhitespace(parm1, parm2, parm3);
152         }
153     }
154 
155     public void processingInstruction(String target, String data)
156             throws SAXException {
157         super.processingInstruction(target, data);
158 
159         if (!activeHandlers() && (xmlWriter != null)) {
160             xmlWriter.processingInstruction(target, data);
161         }
162     }
163 
164     public void setDocumentLocator(Locator locator) {
165         super.setDocumentLocator(locator);
166 
167         if (xmlWriter != null) {
168             xmlWriter.setDocumentLocator(locator);
169         }
170     }
171 
172     public void skippedEntity(String name) throws SAXException {
173         super.skippedEntity(name);
174 
175         if (!activeHandlers() && (xmlWriter != null)) {
176             xmlWriter.skippedEntity(name);
177         }
178     }
179 
180     public void endDocument() throws SAXException {
181         super.endDocument();
182 
183         if (xmlWriter != null) {
184             xmlWriter.endDocument();
185         }
186     }
187 
188     public void startPrefixMapping(String prefix, String uri)
189             throws SAXException {
190         super.startPrefixMapping(prefix, uri);
191 
192         if (xmlWriter != null) {
193             xmlWriter.startPrefixMapping(prefix, uri);
194         }
195     }
196 
197     public void endElement(String uri, String localName, String qName)
198             throws SAXException {
199         ElementHandler currentHandler = getElementStack().getDispatchHandler()
200                 .getHandler(getElementStack().getPath());
201 
202         super.endElement(uri, localName, qName);
203 
204         if (!activeHandlers()) {
205             if (xmlWriter != null) {
206                 if (currentHandler == null) {
207                     xmlWriter.endElement(uri, localName, qName);
208                 } else if (currentHandler instanceof SAXModifyElementHandler) {
209                     SAXModifyElementHandler modifyHandler 
210                             = (SAXModifyElementHandler) currentHandler;
211                     Element modifiedElement = modifyHandler
212                             .getModifiedElement();
213 
214                     try {
215                         xmlWriter.write(modifiedElement);
216                     } catch (IOException ex) {
217                         throw new SAXModifyException(ex);
218                     }
219                 }
220             }
221         }
222     }
223 
224     public void endPrefixMapping(String prefix) throws SAXException {
225         super.endPrefixMapping(prefix);
226 
227         if (xmlWriter != null) {
228             xmlWriter.endPrefixMapping(prefix);
229         }
230     }
231 
232     public void characters(char[] parm1, int parm2, int parm3)
233             throws SAXException {
234         super.characters(parm1, parm2, parm3);
235 
236         if (!activeHandlers() && (xmlWriter != null)) {
237             xmlWriter.characters(parm1, parm2, parm3);
238         }
239     }
240 
241     protected XMLWriter getXMLWriter() {
242         return this.xmlWriter;
243     }
244 
245     private boolean activeHandlers() {
246         DispatchHandler handler = getElementStack().getDispatchHandler();
247 
248         return handler.getActiveHandlerCount() > 0;
249     }
250 }
251 
252 /*
253  * Redistribution and use of this software and associated documentation
254  * ("Software"), with or without modification, are permitted provided that the
255  * following conditions are met:
256  * 
257  * 1. Redistributions of source code must retain copyright statements and
258  * notices. Redistributions must also contain a copy of this document.
259  * 
260  * 2. Redistributions in binary form must reproduce the above copyright notice,
261  * this list of conditions and the following disclaimer in the documentation
262  * and/or other materials provided with the distribution.
263  * 
264  * 3. The name "DOM4J" must not be used to endorse or promote products derived
265  * from this Software without prior written permission of MetaStuff, Ltd. For
266  * written permission, please contact dom4j-info@metastuff.com.
267  * 
268  * 4. Products derived from this Software may not be called "DOM4J" nor may
269  * "DOM4J" appear in their names without prior written permission of MetaStuff,
270  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
271  * 
272  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
273  * 
274  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
275  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
276  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
277  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
278  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
279  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
280  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
281  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
282  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
283  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
284  * POSSIBILITY OF SUCH DAMAGE.
285  * 
286  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
287  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/PruningDispatchHandler.html0000644000175000017500000001541010242117715023462 0ustar ebourgebourg PruningDispatchHandler xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import org.dom4j.ElementPath;
11  
12  /***
13   * This extension on the {@link DispatchHandler}prunes the current {@link
14   * org.dom4j.Element} when there are no {@link ElementHandler}objects active
15   * the element.
16   * 
17   * @author Wonne keysers (Realsoftware)
18   */
19  class PruningDispatchHandler extends DispatchHandler {
20      public void onEnd(ElementPath elementPath) {
21          super.onEnd(elementPath);
22  
23          if (getActiveHandlerCount() == 0) {
24              elementPath.getCurrent().detach();
25          }
26      }
27  }
28  
29  /*
30   * Redistribution and use of this software and associated documentation
31   * ("Software"), with or without modification, are permitted provided that the
32   * following conditions are met:
33   * 
34   * 1. Redistributions of source code must retain copyright statements and
35   * notices. Redistributions must also contain a copy of this document.
36   * 
37   * 2. Redistributions in binary form must reproduce the above copyright notice,
38   * this list of conditions and the following disclaimer in the documentation
39   * and/or other materials provided with the distribution.
40   * 
41   * 3. The name "DOM4J" must not be used to endorse or promote products derived
42   * from this Software without prior written permission of MetaStuff, Ltd. For
43   * written permission, please contact dom4j-info@metastuff.com.
44   * 
45   * 4. Products derived from this Software may not be called "DOM4J" nor may
46   * "DOM4J" appear in their names without prior written permission of MetaStuff,
47   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
48   * 
49   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
50   * 
51   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
52   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
53   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
54   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
55   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
56   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
57   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
58   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
59   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
60   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
61   * POSSIBILITY OF SUCH DAMAGE.
62   * 
63   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
64   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/ElementStack.html0000644000175000017500000004426610242117705021453 0ustar ebourgebourg ElementStack xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import org.dom4j.Element;
11  import org.dom4j.ElementHandler;
12  import org.dom4j.ElementPath;
13  
14  /***
15   * <p>
16   * <code>ElementStack</code> is used internally inside the {@link
17   * SAXContentHandler} to maintain a stack of {@link Element}instances. It opens
18   * an integration possibility allowing derivations to prune the tree when a node
19   * is complete.
20   * </p>
21   * 
22   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
23   * @version $Revision: 1.14 $
24   */
25  class ElementStack implements ElementPath {
26      /*** stack of <code>Element</code> objects */
27      protected Element[] stack;
28  
29      /*** index of the item at the top of the stack or -1 if the stack is empty */
30      protected int lastElementIndex = -1;
31  
32      private DispatchHandler handler = null;
33  
34      public ElementStack() {
35          this(50);
36      }
37  
38      public ElementStack(int defaultCapacity) {
39          stack = new Element[defaultCapacity];
40      }
41  
42      public void setDispatchHandler(DispatchHandler dispatchHandler) {
43          this.handler = dispatchHandler;
44      }
45  
46      public DispatchHandler getDispatchHandler() {
47          return this.handler;
48      }
49  
50      /***
51       * Peeks at the top element on the stack without changing the contents of
52       * the stack.
53       */
54      public void clear() {
55          lastElementIndex = -1;
56      }
57  
58      /***
59       * Peeks at the top element on the stack without changing the contents of
60       * the stack.
61       * 
62       * @return the current element on the stack
63       */
64      public Element peekElement() {
65          if (lastElementIndex < 0) {
66              return null;
67          }
68  
69          return stack[lastElementIndex];
70      }
71  
72      /***
73       * Pops the element off the stack
74       * 
75       * @return the element that has just been popped off the stack
76       */
77      public Element popElement() {
78          if (lastElementIndex < 0) {
79              return null;
80          }
81  
82          return stack[lastElementIndex--];
83      }
84  
85      /***
86       * Pushes a new element onto the stack
87       * 
88       * @param element
89       *            DOCUMENT ME!
90       */
91      public void pushElement(Element element) {
92          int length = stack.length;
93  
94          if (++lastElementIndex >= length) {
95              reallocate(length * 2);
96          }
97  
98          stack[lastElementIndex] = element;
99      }
100 
101     /***
102      * Reallocates the stack to the given size
103      * 
104      * @param size
105      *            DOCUMENT ME!
106      */
107     protected void reallocate(int size) {
108         Element[] oldStack = stack;
109         stack = new Element[size];
110         System.arraycopy(oldStack, 0, stack, 0, oldStack.length);
111     }
112 
113     // The ElementPath Interface
114     //
115     public int size() {
116         return lastElementIndex + 1;
117     }
118 
119     public Element getElement(int depth) {
120         Element element;
121 
122         try {
123             element = (Element) stack[depth];
124         } catch (ArrayIndexOutOfBoundsException e) {
125             element = null;
126         }
127 
128         return element;
129     }
130 
131     public String getPath() {
132         if (handler == null) {
133             setDispatchHandler(new DispatchHandler());
134         }
135 
136         return handler.getPath();
137     }
138 
139     public Element getCurrent() {
140         return peekElement();
141     }
142 
143     public void addHandler(String path, ElementHandler elementHandler) {
144         this.handler.addHandler(getHandlerPath(path), elementHandler);
145     }
146 
147     public void removeHandler(String path) {
148         this.handler.removeHandler(getHandlerPath(path));
149     }
150 
151     /***
152      * DOCUMENT ME!
153      * 
154      * @param path
155      *            DOCUMENT ME!
156      * 
157      * @return true when an <code>ElementHandler</code> is registered for the
158      *         specified path.
159      */
160     public boolean containsHandler(String path) {
161         return this.handler.containsHandler(path);
162     }
163 
164     private String getHandlerPath(String path) {
165         String handlerPath;
166 
167         if (this.handler == null) {
168             setDispatchHandler(new DispatchHandler());
169         }
170 
171         if (path.startsWith("/")) {
172             handlerPath = path;
173         } else if (getPath().equals("/")) {
174             handlerPath = getPath() + path;
175         } else {
176             handlerPath = getPath() + "/" + path;
177         }
178 
179         return handlerPath;
180     }
181 }
182 
183 /*
184  * Redistribution and use of this software and associated documentation
185  * ("Software"), with or without modification, are permitted provided that the
186  * following conditions are met:
187  * 
188  * 1. Redistributions of source code must retain copyright statements and
189  * notices. Redistributions must also contain a copy of this document.
190  * 
191  * 2. Redistributions in binary form must reproduce the above copyright notice,
192  * this list of conditions and the following disclaimer in the documentation
193  * and/or other materials provided with the distribution.
194  * 
195  * 3. The name "DOM4J" must not be used to endorse or promote products derived
196  * from this Software without prior written permission of MetaStuff, Ltd. For
197  * written permission, please contact dom4j-info@metastuff.com.
198  * 
199  * 4. Products derived from this Software may not be called "DOM4J" nor may
200  * "DOM4J" appear in their names without prior written permission of MetaStuff,
201  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
202  * 
203  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
204  * 
205  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
206  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
207  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
208  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
209  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
210  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
211  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
212  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
213  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
214  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
215  * POSSIBILITY OF SUCH DAMAGE.
216  * 
217  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
218  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/SAXWriter.html0000644000175000017500000022367310242117744020730 0ustar ebourgebourg SAXWriter xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.io.IOException;
11  import java.util.HashMap;
12  import java.util.Iterator;
13  import java.util.List;
14  import java.util.Map;
15  
16  import org.dom4j.Attribute;
17  import org.dom4j.Branch;
18  import org.dom4j.CDATA;
19  import org.dom4j.CharacterData;
20  import org.dom4j.Comment;
21  import org.dom4j.Document;
22  import org.dom4j.DocumentType;
23  import org.dom4j.Element;
24  import org.dom4j.Entity;
25  import org.dom4j.Namespace;
26  import org.dom4j.Node;
27  import org.dom4j.ProcessingInstruction;
28  import org.dom4j.Text;
29  import org.dom4j.tree.NamespaceStack;
30  
31  import org.xml.sax.Attributes;
32  import org.xml.sax.ContentHandler;
33  import org.xml.sax.DTDHandler;
34  import org.xml.sax.EntityResolver;
35  import org.xml.sax.ErrorHandler;
36  import org.xml.sax.InputSource;
37  import org.xml.sax.SAXException;
38  import org.xml.sax.SAXNotRecognizedException;
39  import org.xml.sax.SAXNotSupportedException;
40  import org.xml.sax.XMLReader;
41  import org.xml.sax.ext.LexicalHandler;
42  import org.xml.sax.helpers.AttributesImpl;
43  import org.xml.sax.helpers.LocatorImpl;
44  
45  /***
46   * <p>
47   * <code>SAXWriter</code> writes a DOM4J tree to a SAX ContentHandler.
48   * </p>
49   * 
50   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
51   * @version $Revision: 1.24 $
52   */
53  public class SAXWriter implements XMLReader {
54      protected static final String[] LEXICAL_HANDLER_NAMES = {
55              "http://xml.org/sax/properties/lexical-handler",
56              "http://xml.org/sax/handlers/LexicalHandler" };
57  
58      protected static final String FEATURE_NAMESPACE_PREFIXES 
59              = "http://xml.org/sax/features/namespace-prefixes";
60  
61      protected static final String FEATURE_NAMESPACES 
62              = "http://xml.org/sax/features/namespaces";
63  
64      /*** <code>ContentHandler</code> to which SAX events are raised */
65      private ContentHandler contentHandler;
66  
67      /*** <code>DTDHandler</code> fired when a document has a DTD */
68      private DTDHandler dtdHandler;
69  
70      /*** <code>EntityResolver</code> fired when a document has a DTD */
71      private EntityResolver entityResolver;
72  
73      private ErrorHandler errorHandler;
74  
75      /*** <code>LexicalHandler</code> fired on Entity and CDATA sections */
76      private LexicalHandler lexicalHandler;
77  
78      /*** <code>AttributesImpl</code> used when generating the Attributes */
79      private AttributesImpl attributes = new AttributesImpl();
80  
81      /*** Stores the features */
82      private Map features = new HashMap();
83  
84      /*** Stores the properties */
85      private Map properties = new HashMap();
86  
87      /*** Whether namespace declarations are exported as attributes or not */
88      private boolean declareNamespaceAttributes;
89  
90      public SAXWriter() {
91          properties.put(FEATURE_NAMESPACE_PREFIXES, Boolean.FALSE);
92          properties.put(FEATURE_NAMESPACE_PREFIXES, Boolean.TRUE);
93      }
94  
95      public SAXWriter(ContentHandler contentHandler) {
96          this();
97          this.contentHandler = contentHandler;
98      }
99  
100     public SAXWriter(ContentHandler contentHandler,
101             LexicalHandler lexicalHandler) {
102         this();
103         this.contentHandler = contentHandler;
104         this.lexicalHandler = lexicalHandler;
105     }
106 
107     public SAXWriter(ContentHandler contentHandler,
108             LexicalHandler lexicalHandler, EntityResolver entityResolver) {
109         this();
110         this.contentHandler = contentHandler;
111         this.lexicalHandler = lexicalHandler;
112         this.entityResolver = entityResolver;
113     }
114 
115     /***
116      * A polymorphic method to write any Node to this SAX stream
117      * 
118      * @param node
119      *            DOCUMENT ME!
120      * 
121      * @throws SAXException
122      *             DOCUMENT ME!
123      */
124     public void write(Node node) throws SAXException {
125         int nodeType = node.getNodeType();
126 
127         switch (nodeType) {
128             case Node.ELEMENT_NODE:
129                 write((Element) node);
130 
131                 break;
132 
133             case Node.ATTRIBUTE_NODE:
134                 write((Attribute) node);
135 
136                 break;
137 
138             case Node.TEXT_NODE:
139                 write(node.getText());
140 
141                 break;
142 
143             case Node.CDATA_SECTION_NODE:
144                 write((CDATA) node);
145 
146                 break;
147 
148             case Node.ENTITY_REFERENCE_NODE:
149                 write((Entity) node);
150 
151                 break;
152 
153             case Node.PROCESSING_INSTRUCTION_NODE:
154                 write((ProcessingInstruction) node);
155 
156                 break;
157 
158             case Node.COMMENT_NODE:
159                 write((Comment) node);
160 
161                 break;
162 
163             case Node.DOCUMENT_NODE:
164                 write((Document) node);
165 
166                 break;
167 
168             case Node.DOCUMENT_TYPE_NODE:
169                 write((DocumentType) node);
170 
171                 break;
172 
173             case Node.NAMESPACE_NODE:
174 
175                 // Will be output with attributes
176                 // write((Namespace) node);
177                 break;
178 
179             default:
180                 throw new SAXException("Invalid node type: " + node);
181         }
182     }
183 
184     /***
185      * Generates SAX events for the given Document and all its content
186      * 
187      * @param document
188      *            is the Document to parse
189      * 
190      * @throws SAXException
191      *             if there is a SAX error processing the events
192      */
193     public void write(Document document) throws SAXException {
194         if (document != null) {
195             checkForNullHandlers();
196 
197             documentLocator(document);
198             startDocument();
199             entityResolver(document);
200             dtdHandler(document);
201 
202             writeContent(document, new NamespaceStack());
203             endDocument();
204         }
205     }
206 
207     /***
208      * Generates SAX events for the given Element and all its content
209      * 
210      * @param element
211      *            is the Element to parse
212      * 
213      * @throws SAXException
214      *             if there is a SAX error processing the events
215      */
216     public void write(Element element) throws SAXException {
217         write(element, new NamespaceStack());
218     }
219 
220     /***
221      * <p>
222      * Writes the opening tag of an {@link Element}, including its {@link
223      * Attribute}s but without its content.
224      * </p>
225      * 
226      * @param element
227      *            <code>Element</code> to output.
228      * 
229      * @throws SAXException
230      *             DOCUMENT ME!
231      */
232     public void writeOpen(Element element) throws SAXException {
233         startElement(element, null);
234     }
235 
236     /***
237      * <p>
238      * Writes the closing tag of an {@link Element}
239      * </p>
240      * 
241      * @param element
242      *            <code>Element</code> to output.
243      * 
244      * @throws SAXException
245      *             DOCUMENT ME!
246      */
247     public void writeClose(Element element) throws SAXException {
248         endElement(element);
249     }
250 
251     /***
252      * Generates SAX events for the given text
253      * 
254      * @param text
255      *            is the text to send to the SAX ContentHandler
256      * 
257      * @throws SAXException
258      *             if there is a SAX error processing the events
259      */
260     public void write(String text) throws SAXException {
261         if (text != null) {
262             char[] chars = text.toCharArray();
263             contentHandler.characters(chars, 0, chars.length);
264         }
265     }
266 
267     /***
268      * Generates SAX events for the given CDATA
269      * 
270      * @param cdata
271      *            is the CDATA to parse
272      * 
273      * @throws SAXException
274      *             if there is a SAX error processing the events
275      */
276     public void write(CDATA cdata) throws SAXException {
277         String text = cdata.getText();
278 
279         if (lexicalHandler != null) {
280             lexicalHandler.startCDATA();
281             write(text);
282             lexicalHandler.endCDATA();
283         } else {
284             write(text);
285         }
286     }
287 
288     /***
289      * Generates SAX events for the given Comment
290      * 
291      * @param comment
292      *            is the Comment to parse
293      * 
294      * @throws SAXException
295      *             if there is a SAX error processing the events
296      */
297     public void write(Comment comment) throws SAXException {
298         if (lexicalHandler != null) {
299             String text = comment.getText();
300             char[] chars = text.toCharArray();
301             lexicalHandler.comment(chars, 0, chars.length);
302         }
303     }
304 
305     /***
306      * Generates SAX events for the given Entity
307      * 
308      * @param entity
309      *            is the Entity to parse
310      * 
311      * @throws SAXException
312      *             if there is a SAX error processing the events
313      */
314     public void write(Entity entity) throws SAXException {
315         String text = entity.getText();
316 
317         if (lexicalHandler != null) {
318             String name = entity.getName();
319             lexicalHandler.startEntity(name);
320             write(text);
321             lexicalHandler.endEntity(name);
322         } else {
323             write(text);
324         }
325     }
326 
327     /***
328      * Generates SAX events for the given ProcessingInstruction
329      * 
330      * @param pi
331      *            is the ProcessingInstruction to parse
332      * 
333      * @throws SAXException
334      *             if there is a SAX error processing the events
335      */
336     public void write(ProcessingInstruction pi) throws SAXException {
337         String target = pi.getTarget();
338         String text = pi.getText();
339         contentHandler.processingInstruction(target, text);
340     }
341 
342     /***
343      * Should namespace declarations be converted to "xmlns" attributes. This
344      * property defaults to <code>false</code> as per the SAX specification.
345      * This property is set via the SAX feature
346      * "http://xml.org/sax/features/namespace-prefixes"
347      * 
348      * @return DOCUMENT ME!
349      */
350     public boolean isDeclareNamespaceAttributes() {
351         return declareNamespaceAttributes;
352     }
353 
354     /***
355      * Sets whether namespace declarations should be exported as "xmlns"
356      * attributes or not. This property is set from the SAX feature
357      * "http://xml.org/sax/features/namespace-prefixes"
358      * 
359      * @param declareNamespaceAttrs
360      *            DOCUMENT ME!
361      */
362     public void setDeclareNamespaceAttributes(boolean declareNamespaceAttrs) {
363         this.declareNamespaceAttributes = declareNamespaceAttrs;
364     }
365 
366     // XMLReader methods
367     // -------------------------------------------------------------------------
368 
369     /***
370      * DOCUMENT ME!
371      * 
372      * @return the <code>ContentHandler</code> called when SAX events are
373      *         raised
374      */
375     public ContentHandler getContentHandler() {
376         return contentHandler;
377     }
378 
379     /***
380      * Sets the <code>ContentHandler</code> called when SAX events are raised
381      * 
382      * @param contentHandler
383      *            is the <code>ContentHandler</code> called when SAX events
384      *            are raised
385      */
386     public void setContentHandler(ContentHandler contentHandler) {
387         this.contentHandler = contentHandler;
388     }
389 
390     /***
391      * DOCUMENT ME!
392      * 
393      * @return the <code>DTDHandler</code>
394      */
395     public DTDHandler getDTDHandler() {
396         return dtdHandler;
397     }
398 
399     /***
400      * Sets the <code>DTDHandler</code>.
401      * 
402      * @param handler
403      *            DOCUMENT ME!
404      */
405     public void setDTDHandler(DTDHandler handler) {
406         this.dtdHandler = handler;
407     }
408 
409     /***
410      * DOCUMENT ME!
411      * 
412      * @return the <code>ErrorHandler</code>
413      */
414     public ErrorHandler getErrorHandler() {
415         return errorHandler;
416     }
417 
418     /***
419      * Sets the <code>ErrorHandler</code>.
420      * 
421      * @param errorHandler
422      *            DOCUMENT ME!
423      */
424     public void setErrorHandler(ErrorHandler errorHandler) {
425         this.errorHandler = errorHandler;
426     }
427 
428     /***
429      * DOCUMENT ME!
430      * 
431      * @return the <code>EntityResolver</code> used when a Document contains a
432      *         DTD
433      */
434     public EntityResolver getEntityResolver() {
435         return entityResolver;
436     }
437 
438     /***
439      * Sets the <code>EntityResolver</code>.
440      * 
441      * @param entityResolver
442      *            is the <code>EntityResolver</code>
443      */
444     public void setEntityResolver(EntityResolver entityResolver) {
445         this.entityResolver = entityResolver;
446     }
447 
448     /***
449      * DOCUMENT ME!
450      * 
451      * @return the <code>LexicalHandler</code> used when a Document contains a
452      *         DTD
453      */
454     public LexicalHandler getLexicalHandler() {
455         return lexicalHandler;
456     }
457 
458     /***
459      * Sets the <code>LexicalHandler</code>.
460      * 
461      * @param lexicalHandler
462      *            is the <code>LexicalHandler</code>
463      */
464     public void setLexicalHandler(LexicalHandler lexicalHandler) {
465         this.lexicalHandler = lexicalHandler;
466     }
467 
468     /***
469      * Sets the <code>XMLReader</code> used to write SAX events to
470      * 
471      * @param xmlReader
472      *            is the <code>XMLReader</code>
473      */
474     public void setXMLReader(XMLReader xmlReader) {
475         setContentHandler(xmlReader.getContentHandler());
476         setDTDHandler(xmlReader.getDTDHandler());
477         setEntityResolver(xmlReader.getEntityResolver());
478         setErrorHandler(xmlReader.getErrorHandler());
479     }
480 
481     /***
482      * Looks up the value of a feature.
483      * 
484      * @param name
485      *            DOCUMENT ME!
486      * 
487      * @return DOCUMENT ME!
488      * 
489      * @throws SAXNotRecognizedException
490      *             DOCUMENT ME!
491      * @throws SAXNotSupportedException
492      *             DOCUMENT ME!
493      */
494     public boolean getFeature(String name) throws SAXNotRecognizedException,
495             SAXNotSupportedException {
496         Boolean answer = (Boolean) features.get(name);
497 
498         return (answer != null) && answer.booleanValue();
499     }
500 
501     /***
502      * This implementation does actually use any features but just stores them
503      * for later retrieval
504      * 
505      * @param name
506      *            DOCUMENT ME!
507      * @param value
508      *            DOCUMENT ME!
509      * 
510      * @throws SAXNotRecognizedException
511      *             DOCUMENT ME!
512      * @throws SAXNotSupportedException
513      *             DOCUMENT ME!
514      */
515     public void setFeature(String name, boolean value)
516             throws SAXNotRecognizedException, SAXNotSupportedException {
517         if (FEATURE_NAMESPACE_PREFIXES.equals(name)) {
518             setDeclareNamespaceAttributes(value);
519         } else if (FEATURE_NAMESPACE_PREFIXES.equals(name)) {
520             if (!value) {
521                 String msg = "Namespace feature is always supported in dom4j";
522                 throw new SAXNotSupportedException(msg);
523             }
524         }
525 
526         features.put(name, (value) ? Boolean.TRUE : Boolean.FALSE);
527     }
528 
529     /***
530      * Sets the given SAX property
531      * 
532      * @param name
533      *            DOCUMENT ME!
534      * @param value
535      *            DOCUMENT ME!
536      */
537     public void setProperty(String name, Object value) {
538         for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
539             if (LEXICAL_HANDLER_NAMES[i].equals(name)) {
540                 setLexicalHandler((LexicalHandler) value);
541 
542                 return;
543             }
544         }
545 
546         properties.put(name, value);
547     }
548 
549     /***
550      * Gets the given SAX property
551      * 
552      * @param name
553      *            DOCUMENT ME!
554      * 
555      * @return DOCUMENT ME!
556      * 
557      * @throws SAXNotRecognizedException
558      *             DOCUMENT ME!
559      * @throws SAXNotSupportedException
560      *             DOCUMENT ME!
561      */
562     public Object getProperty(String name) throws SAXNotRecognizedException,
563             SAXNotSupportedException {
564         for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
565             if (LEXICAL_HANDLER_NAMES[i].equals(name)) {
566                 return getLexicalHandler();
567             }
568         }
569 
570         return properties.get(name);
571     }
572 
573     /***
574      * This method is not supported.
575      * 
576      * @param systemId
577      *            DOCUMENT ME!
578      * 
579      * @throws SAXNotSupportedException
580      *             DOCUMENT ME!
581      */
582     public void parse(String systemId) throws SAXNotSupportedException {
583         throw new SAXNotSupportedException("This XMLReader can only accept"
584                 + " <dom4j> InputSource objects");
585     }
586 
587     /***
588      * Parses an XML document. This method can only accept DocumentInputSource
589      * inputs otherwise a {@link SAXNotSupportedException}exception is thrown.
590      * 
591      * @param input
592      *            DOCUMENT ME!
593      * 
594      * @throws SAXException
595      *             DOCUMENT ME!
596      * @throws SAXNotSupportedException
597      *             if the input source is not wrapping a dom4j document
598      */
599     public void parse(InputSource input) throws SAXException {
600         if (input instanceof DocumentInputSource) {
601             DocumentInputSource documentInput = (DocumentInputSource) input;
602             Document document = documentInput.getDocument();
603             write(document);
604         } else {
605             throw new SAXNotSupportedException(
606                     "This XMLReader can only accept "
607                             + "<dom4j> InputSource objects");
608         }
609     }
610 
611     // Implementation methods
612     // -------------------------------------------------------------------------
613     protected void writeContent(Branch branch, NamespaceStack namespaceStack)
614             throws SAXException {
615         for (Iterator iter = branch.nodeIterator(); iter.hasNext();) {
616             Object object = iter.next();
617 
618             if (object instanceof Element) {
619                 write((Element) object, namespaceStack);
620             } else if (object instanceof CharacterData) {
621                 if (object instanceof Text) {
622                     Text text = (Text) object;
623                     write(text.getText());
624                 } else if (object instanceof CDATA) {
625                     write((CDATA) object);
626                 } else if (object instanceof Comment) {
627                     write((Comment) object);
628                 } else {
629                     throw new SAXException("Invalid Node in DOM4J content: "
630                             + object + " of type: " + object.getClass());
631                 }
632             } else if (object instanceof String) {
633                 write((String) object);
634             } else if (object instanceof Entity) {
635                 write((Entity) object);
636             } else if (object instanceof ProcessingInstruction) {
637                 write((ProcessingInstruction) object);
638             } else if (object instanceof Namespace) {
639                 write((Namespace) object);
640             } else {
641                 throw new SAXException("Invalid Node in DOM4J content: "
642                         + object);
643             }
644         }
645     }
646 
647     /***
648      * The {@link org.xml.sax.Locator}is only really useful when parsing a
649      * textual document as its main purpose is to identify the line and column
650      * number. Since we are processing an in memory tree which will probably
651      * have its line number information removed, we'll just use -1 for the line
652      * and column numbers.
653      * 
654      * @param document
655      *            DOCUMENT ME!
656      * 
657      * @throws SAXException
658      *             DOCUMENT ME!
659      */
660     protected void documentLocator(Document document) throws SAXException {
661         LocatorImpl locator = new LocatorImpl();
662 
663         String publicID = null;
664         String systemID = null;
665         DocumentType docType = document.getDocType();
666 
667         if (docType != null) {
668             publicID = docType.getPublicID();
669             systemID = docType.getSystemID();
670         }
671 
672         if (publicID != null) {
673             locator.setPublicId(publicID);
674         }
675 
676         if (systemID != null) {
677             locator.setSystemId(systemID);
678         }
679 
680         locator.setLineNumber(-1);
681         locator.setColumnNumber(-1);
682 
683         contentHandler.setDocumentLocator(locator);
684     }
685 
686     protected void entityResolver(Document document) throws SAXException {
687         if (entityResolver != null) {
688             DocumentType docType = document.getDocType();
689 
690             if (docType != null) {
691                 String publicID = docType.getPublicID();
692                 String systemID = docType.getSystemID();
693 
694                 if ((publicID != null) || (systemID != null)) {
695                     try {
696                         entityResolver.resolveEntity(publicID, systemID);
697                     } catch (IOException e) {
698                         throw new SAXException("Could not resolve publicID: "
699                                 + publicID + " systemID: " + systemID, e);
700                     }
701                 }
702             }
703         }
704     }
705 
706     /***
707      * We do not yet support DTD or XML Schemas so this method does nothing
708      * right now.
709      * 
710      * @param document
711      *            DOCUMENT ME!
712      * 
713      * @throws SAXException
714      *             DOCUMENT ME!
715      */
716     protected void dtdHandler(Document document) throws SAXException {
717     }
718 
719     protected void startDocument() throws SAXException {
720         contentHandler.startDocument();
721     }
722 
723     protected void endDocument() throws SAXException {
724         contentHandler.endDocument();
725     }
726 
727     protected void write(Element element, NamespaceStack namespaceStack)
728             throws SAXException {
729         int stackSize = namespaceStack.size();
730         AttributesImpl namespaceAttributes = startPrefixMapping(element,
731                 namespaceStack);
732         startElement(element, namespaceAttributes);
733         writeContent(element, namespaceStack);
734         endElement(element);
735         endPrefixMapping(namespaceStack, stackSize);
736     }
737 
738     /***
739      * Fires a SAX startPrefixMapping event for all the namespaceStack which
740      * have just come into scope
741      * 
742      * @param element
743      *            DOCUMENT ME!
744      * @param namespaceStack
745      *            DOCUMENT ME!
746      * 
747      * @return DOCUMENT ME!
748      * 
749      * @throws SAXException
750      *             DOCUMENT ME!
751      */
752     protected AttributesImpl startPrefixMapping(Element element,
753             NamespaceStack namespaceStack) throws SAXException {
754         AttributesImpl namespaceAttributes = null;
755 
756         // start with the namespace of the element
757         Namespace elementNamespace = element.getNamespace();
758 
759         if ((elementNamespace != null)
760                 && !isIgnoreableNamespace(elementNamespace, namespaceStack)) {
761             namespaceStack.push(elementNamespace);
762             contentHandler.startPrefixMapping(elementNamespace.getPrefix(),
763                     elementNamespace.getURI());
764             namespaceAttributes = addNamespaceAttribute(namespaceAttributes,
765                     elementNamespace);
766         }
767 
768         List declaredNamespaces = element.declaredNamespaces();
769 
770         for (int i = 0, size = declaredNamespaces.size(); i < size; i++) {
771             Namespace namespace = (Namespace) declaredNamespaces.get(i);
772 
773             if (!isIgnoreableNamespace(namespace, namespaceStack)) {
774                 namespaceStack.push(namespace);
775                 contentHandler.startPrefixMapping(namespace.getPrefix(),
776                         namespace.getURI());
777                 namespaceAttributes = addNamespaceAttribute(
778                         namespaceAttributes, namespace);
779             }
780         }
781 
782         return namespaceAttributes;
783     }
784 
785     /***
786      * Fires a SAX endPrefixMapping event for all the namespaceStack which have
787      * gone out of scope
788      * 
789      * @param stack
790      *            DOCUMENT ME!
791      * @param stackSize
792      *            DOCUMENT ME!
793      * 
794      * @throws SAXException
795      *             DOCUMENT ME!
796      */
797     protected void endPrefixMapping(NamespaceStack stack, int stackSize)
798             throws SAXException {
799         while (stack.size() > stackSize) {
800             Namespace namespace = stack.pop();
801 
802             if (namespace != null) {
803                 contentHandler.endPrefixMapping(namespace.getPrefix());
804             }
805         }
806     }
807 
808     protected void startElement(Element element,
809             AttributesImpl namespaceAttributes) throws SAXException {
810         contentHandler.startElement(element.getNamespaceURI(), element
811                 .getName(), element.getQualifiedName(), createAttributes(
812                 element, namespaceAttributes));
813     }
814 
815     protected void endElement(Element element) throws SAXException {
816         contentHandler.endElement(element.getNamespaceURI(), element.getName(),
817                 element.getQualifiedName());
818     }
819 
820     protected Attributes createAttributes(Element element,
821             Attributes namespaceAttributes) throws SAXException {
822         attributes.clear();
823 
824         if (namespaceAttributes != null) {
825             attributes.setAttributes(namespaceAttributes);
826         }
827 
828         for (Iterator iter = element.attributeIterator(); iter.hasNext();) {
829             Attribute attribute = (Attribute) iter.next();
830             attributes.addAttribute(attribute.getNamespaceURI(), attribute
831                     .getName(), attribute.getQualifiedName(), "CDATA",
832                     attribute.getValue());
833         }
834 
835         return attributes;
836     }
837 
838     /***
839      * If isDelcareNamespaceAttributes() is enabled then this method will add
840      * the given namespace declaration to the supplied attributes object,
841      * creating one if it does not exist.
842      * 
843      * @param attrs
844      *            DOCUMENT ME!
845      * @param namespace
846      *            DOCUMENT ME!
847      * 
848      * @return DOCUMENT ME!
849      */
850     protected AttributesImpl addNamespaceAttribute(AttributesImpl attrs,
851             Namespace namespace) {
852         if (declareNamespaceAttributes) {
853             if (attrs == null) {
854                 attrs = new AttributesImpl();
855             }
856 
857             String prefix = namespace.getPrefix();
858             String qualifiedName = "xmlns";
859 
860             if ((prefix != null) && (prefix.length() > 0)) {
861                 qualifiedName = "xmlns:" + prefix;
862             }
863 
864             String uri = "";
865             String localName = prefix;
866             String type = "CDATA";
867             String value = namespace.getURI();
868 
869             attrs.addAttribute(uri, localName, qualifiedName, type, value);
870         }
871 
872         return attrs;
873     }
874 
875     /***
876      * DOCUMENT ME!
877      * 
878      * @param namespace
879      *            DOCUMENT ME!
880      * @param namespaceStack
881      *            DOCUMENT ME!
882      * 
883      * @return true if the given namespace is an ignorable namespace (such as
884      *         Namespace.NO_NAMESPACE or Namespace.XML_NAMESPACE) or if the
885      *         namespace has already been declared in the current scope
886      */
887     protected boolean isIgnoreableNamespace(Namespace namespace,
888             NamespaceStack namespaceStack) {
889         if (namespace.equals(Namespace.NO_NAMESPACE)
890                 || namespace.equals(Namespace.XML_NAMESPACE)) {
891             return true;
892         }
893 
894         String uri = namespace.getURI();
895 
896         if ((uri == null) || (uri.length() <= 0)) {
897             return true;
898         }
899 
900         return namespaceStack.contains(namespace);
901     }
902 
903     /***
904      * Ensures non-null content handlers?
905      */
906     protected void checkForNullHandlers() {
907     }
908 }
909 
910 /*
911  * Redistribution and use of this software and associated documentation
912  * ("Software"), with or without modification, are permitted provided that the
913  * following conditions are met:
914  * 
915  * 1. Redistributions of source code must retain copyright statements and
916  * notices. Redistributions must also contain a copy of this document.
917  * 
918  * 2. Redistributions in binary form must reproduce the above copyright notice,
919  * this list of conditions and the following disclaimer in the documentation
920  * and/or other materials provided with the distribution.
921  * 
922  * 3. The name "DOM4J" must not be used to endorse or promote products derived
923  * from this Software without prior written permission of MetaStuff, Ltd. For
924  * written permission, please contact dom4j-info@metastuff.com.
925  * 
926  * 4. Products derived from this Software may not be called "DOM4J" nor may
927  * "DOM4J" appear in their names without prior written permission of MetaStuff,
928  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
929  * 
930  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
931  * 
932  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
933  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
934  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
935  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
936  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
937  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
938  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
939  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
940  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
941  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
942  * POSSIBILITY OF SUCH DAMAGE.
943  * 
944  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
945  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/XPP3Reader.html0000644000175000017500000012774310242117752020755 0ustar ebourgebourg XPP3Reader xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.io.BufferedReader;
11  import java.io.CharArrayReader;
12  import java.io.File;
13  import java.io.FileReader;
14  import java.io.IOException;
15  import java.io.InputStream;
16  import java.io.InputStreamReader;
17  import java.io.Reader;
18  import java.net.URL;
19  
20  import org.dom4j.Document;
21  import org.dom4j.DocumentException;
22  import org.dom4j.DocumentFactory;
23  import org.dom4j.Element;
24  import org.dom4j.ElementHandler;
25  import org.dom4j.QName;
26  
27  import org.xmlpull.v1.XmlPullParser;
28  import org.xmlpull.v1.XmlPullParserException;
29  import org.xmlpull.v1.XmlPullParserFactory;
30  
31  /***
32   * <p>
33   * <code>XPP3Reader</code> is a Reader of DOM4J documents that uses the fast
34   * <a href="http://www.extreme.indiana.edu/soap/xpp/">XML Pull Parser 3.x </a>.
35   * It is very fast for use in SOAP style environments.
36   * </p>
37   * 
38   * @author <a href="mailto:pelle@neubia.com">Pelle Braendgaard </a>
39   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
40   * @version $Revision: 1.3 $
41   */
42  public class XPP3Reader {
43      /*** <code>DocumentFactory</code> used to create new document objects */
44      private DocumentFactory factory;
45  
46      /*** <code>XmlPullParser</code> used to parse XML */
47      private XmlPullParser xppParser;
48  
49      /*** <code>XmlPullParser</code> used to parse XML */
50      private XmlPullParserFactory xppFactory;
51  
52      /*** DispatchHandler to call when each <code>Element</code> is encountered */
53      private DispatchHandler dispatchHandler;
54  
55      public XPP3Reader() {
56      }
57  
58      public XPP3Reader(DocumentFactory factory) {
59          this.factory = factory;
60      }
61  
62      /***
63       * <p>
64       * Reads a Document from the given <code>File</code>
65       * </p>
66       * 
67       * @param file
68       *            is the <code>File</code> to read from.
69       * 
70       * @return the newly created Document instance
71       * 
72       * @throws DocumentException
73       *             if an error occurs during parsing.
74       * @throws IOException
75       *             if a URL could not be made for the given File
76       * @throws XmlPullParserException
77       *             DOCUMENT ME!
78       */
79      public Document read(File file) throws DocumentException, IOException,
80              XmlPullParserException {
81          String systemID = file.getAbsolutePath();
82  
83          return read(new BufferedReader(new FileReader(file)), systemID);
84      }
85  
86      /***
87       * <p>
88       * Reads a Document from the given <code>URL</code>
89       * </p>
90       * 
91       * @param url
92       *            <code>URL</code> to read from.
93       * 
94       * @return the newly created Document instance
95       * 
96       * @throws DocumentException
97       *             if an error occurs during parsing.
98       * @throws IOException
99       *             DOCUMENT ME!
100      * @throws XmlPullParserException
101      *             DOCUMENT ME!
102      */
103     public Document read(URL url) throws DocumentException, IOException,
104             XmlPullParserException {
105         String systemID = url.toExternalForm();
106 
107         return read(createReader(url.openStream()), systemID);
108     }
109 
110     /***
111      * <p>
112      * Reads a Document from the given URL or filename.
113      * </p>
114      * 
115      * <p>
116      * If the systemID contains a <code>':'</code> character then it is
117      * assumed to be a URL otherwise its assumed to be a file name. If you want
118      * finer grained control over this mechansim then please explicitly pass in
119      * either a {@link URL}or a {@link File}instance instead of a {@link
120      * String} to denote the source of the document.
121      * </p>
122      * 
123      * @param systemID
124      *            is a URL for a document or a file name.
125      * 
126      * @return the newly created Document instance
127      * 
128      * @throws DocumentException
129      *             if an error occurs during parsing.
130      * @throws IOException
131      *             if a URL could not be made for the given File
132      * @throws XmlPullParserException
133      *             DOCUMENT ME!
134      */
135     public Document read(String systemID) throws DocumentException,
136             IOException, XmlPullParserException {
137         if (systemID.indexOf(':') >= 0) {
138             // lets assume its a URL
139             return read(new URL(systemID));
140         } else {
141             // lets assume that we are given a file name
142             return read(new File(systemID));
143         }
144     }
145 
146     /***
147      * <p>
148      * Reads a Document from the given stream
149      * </p>
150      * 
151      * @param in
152      *            <code>InputStream</code> to read from.
153      * 
154      * @return the newly created Document instance
155      * 
156      * @throws DocumentException
157      *             if an error occurs during parsing.
158      * @throws IOException
159      *             DOCUMENT ME!
160      * @throws XmlPullParserException
161      *             DOCUMENT ME!
162      */
163     public Document read(InputStream in) throws DocumentException, IOException,
164             XmlPullParserException {
165         return read(createReader(in));
166     }
167 
168     /***
169      * <p>
170      * Reads a Document from the given <code>Reader</code>
171      * </p>
172      * 
173      * @param reader
174      *            is the reader for the input
175      * 
176      * @return the newly created Document instance
177      * 
178      * @throws DocumentException
179      *             if an error occurs during parsing.
180      * @throws IOException
181      *             DOCUMENT ME!
182      * @throws XmlPullParserException
183      *             DOCUMENT ME!
184      */
185     public Document read(Reader reader) throws DocumentException, IOException,
186             XmlPullParserException {
187         getXPPParser().setInput(reader);
188 
189         return parseDocument();
190     }
191 
192     /***
193      * <p>
194      * Reads a Document from the given array of characters
195      * </p>
196      * 
197      * @param text
198      *            is the text to parse
199      * 
200      * @return the newly created Document instance
201      * 
202      * @throws DocumentException
203      *             if an error occurs during parsing.
204      * @throws IOException
205      *             DOCUMENT ME!
206      * @throws XmlPullParserException
207      *             DOCUMENT ME!
208      */
209     public Document read(char[] text) throws DocumentException, IOException,
210             XmlPullParserException {
211         getXPPParser().setInput(new CharArrayReader(text));
212 
213         return parseDocument();
214     }
215 
216     /***
217      * <p>
218      * Reads a Document from the given stream
219      * </p>
220      * 
221      * @param in
222      *            <code>InputStream</code> to read from.
223      * @param systemID
224      *            is the URI for the input
225      * 
226      * @return the newly created Document instance
227      * 
228      * @throws DocumentException
229      *             if an error occurs during parsing.
230      * @throws IOException
231      *             DOCUMENT ME!
232      * @throws XmlPullParserException
233      *             DOCUMENT ME!
234      */
235     public Document read(InputStream in, String systemID)
236             throws DocumentException, IOException, XmlPullParserException {
237         return read(createReader(in), systemID);
238     }
239 
240     /***
241      * <p>
242      * Reads a Document from the given <code>Reader</code>
243      * </p>
244      * 
245      * @param reader
246      *            is the reader for the input
247      * @param systemID
248      *            is the URI for the input
249      * 
250      * @return the newly created Document instance
251      * 
252      * @throws DocumentException
253      *             if an error occurs during parsing.
254      * @throws IOException
255      *             DOCUMENT ME!
256      * @throws XmlPullParserException
257      *             DOCUMENT ME!
258      */
259     public Document read(Reader reader, String systemID)
260             throws DocumentException, IOException, XmlPullParserException {
261         Document document = read(reader);
262         document.setName(systemID);
263 
264         return document;
265     }
266 
267     // Properties
268     // -------------------------------------------------------------------------
269     public XmlPullParser getXPPParser() throws XmlPullParserException {
270         if (xppParser == null) {
271             xppParser = getXPPFactory().newPullParser();
272         }
273 
274         return xppParser;
275     }
276 
277     public XmlPullParserFactory getXPPFactory() throws XmlPullParserException {
278         if (xppFactory == null) {
279             xppFactory = XmlPullParserFactory.newInstance();
280         }
281 
282         xppFactory.setNamespaceAware(true);
283 
284         return xppFactory;
285     }
286 
287     public void setXPPFactory(XmlPullParserFactory xPPfactory) {
288         this.xppFactory = xPPfactory;
289     }
290 
291     /***
292      * DOCUMENT ME!
293      * 
294      * @return the <code>DocumentFactory</code> used to create document
295      *         objects
296      */
297     public DocumentFactory getDocumentFactory() {
298         if (factory == null) {
299             factory = DocumentFactory.getInstance();
300         }
301 
302         return factory;
303     }
304 
305     /***
306      * <p>
307      * This sets the <code>DocumentFactory</code> used to create new
308      * documents. This method allows the building of custom DOM4J tree objects
309      * to be implemented easily using a custom derivation of
310      * {@link DocumentFactory}
311      * </p>
312      * 
313      * @param documentFactory
314      *            <code>DocumentFactory</code> used to create DOM4J objects
315      */
316     public void setDocumentFactory(DocumentFactory documentFactory) {
317         this.factory = documentFactory;
318     }
319 
320     /***
321      * Adds the <code>ElementHandler</code> to be called when the specified
322      * path is encounted.
323      * 
324      * @param path
325      *            is the path to be handled
326      * @param handler
327      *            is the <code>ElementHandler</code> to be called by the event
328      *            based processor.
329      */
330     public void addHandler(String path, ElementHandler handler) {
331         getDispatchHandler().addHandler(path, handler);
332     }
333 
334     /***
335      * Removes the <code>ElementHandler</code> from the event based processor,
336      * for the specified path.
337      * 
338      * @param path
339      *            is the path to remove the <code>ElementHandler</code> for.
340      */
341     public void removeHandler(String path) {
342         getDispatchHandler().removeHandler(path);
343     }
344 
345     /***
346      * When multiple <code>ElementHandler</code> instances have been
347      * registered, this will set a default <code>ElementHandler</code> to be
348      * called for any path which does <b>NOT </b> have a handler registered.
349      * 
350      * @param handler
351      *            is the <code>ElementHandler</code> to be called by the event
352      *            based processor.
353      */
354     public void setDefaultHandler(ElementHandler handler) {
355         getDispatchHandler().setDefaultHandler(handler);
356     }
357 
358     // Implementation methods
359     // -------------------------------------------------------------------------
360     protected Document parseDocument() throws DocumentException, IOException,
361             XmlPullParserException {
362         DocumentFactory df = getDocumentFactory();
363         Document document = df.createDocument();
364         Element parent = null;
365         XmlPullParser pp = getXPPParser();
366         pp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
367 
368         while (true) {
369             int type = pp.nextToken();
370 
371             switch (type) {
372                 case XmlPullParser.PROCESSING_INSTRUCTION: {
373                     String text = pp.getText();
374                     int loc = text.indexOf(" ");
375 
376                     if (loc >= 0) {
377                         String target = text.substring(0, loc);
378                         String txt = text.substring(loc + 1);
379                         document.addProcessingInstruction(target, txt);
380                     } else {
381                         document.addProcessingInstruction(text, "");
382                     }
383 
384                     break;
385                 }
386 
387                 case XmlPullParser.COMMENT: {
388                     if (parent != null) {
389                         parent.addComment(pp.getText());
390                     } else {
391                         document.addComment(pp.getText());
392                     }
393 
394                     break;
395                 }
396 
397                 case XmlPullParser.CDSECT: {
398                     if (parent != null) {
399                         parent.addCDATA(pp.getText());
400                     } else {
401                         String msg = "Cannot have text content outside of the "
402                                 + "root document";
403                         throw new DocumentException(msg);
404                     }
405 
406                     break;
407                 }
408 
409                 case XmlPullParser.ENTITY_REF:
410                     break;
411 
412                 case XmlPullParser.END_DOCUMENT:
413                     return document;
414 
415                 case XmlPullParser.START_TAG: {
416                     QName qname = (pp.getPrefix() == null) ? df.createQName(pp
417                             .getName(), pp.getNamespace()) : df.createQName(pp
418                             .getName(), pp.getPrefix(), pp.getNamespace());
419                     Element newElement = df.createElement(qname);
420                     int nsStart = pp.getNamespaceCount(pp.getDepth() - 1);
421                     int nsEnd = pp.getNamespaceCount(pp.getDepth());
422 
423                     for (int i = nsStart; i < nsEnd; i++) {
424                         if (pp.getNamespacePrefix(i) != null) {
425                             newElement.addNamespace(pp.getNamespacePrefix(i),
426                                     pp.getNamespaceUri(i));
427                         }
428                     }
429 
430                     for (int i = 0; i < pp.getAttributeCount(); i++) {
431                         QName qa = (pp.getAttributePrefix(i) == null) ? df
432                                 .createQName(pp.getAttributeName(i)) : df
433                                 .createQName(pp.getAttributeName(i), pp
434                                         .getAttributePrefix(i), pp
435                                         .getAttributeNamespace(i));
436                         newElement.addAttribute(qa, pp.getAttributeValue(i));
437                     }
438 
439                     if (parent != null) {
440                         parent.add(newElement);
441                     } else {
442                         document.add(newElement);
443                     }
444 
445                     parent = newElement;
446 
447                     break;
448                 }
449 
450                 case XmlPullParser.END_TAG: {
451                     if (parent != null) {
452                         parent = parent.getParent();
453                     }
454 
455                     break;
456                 }
457 
458                 case XmlPullParser.TEXT: {
459                     String text = pp.getText();
460 
461                     if (parent != null) {
462                         parent.addText(text);
463                     } else {
464                         String msg = "Cannot have text content outside of the "
465                                 + "root document";
466                         throw new DocumentException(msg);
467                     }
468 
469                     break;
470                 }
471 
472                 default:
473                     break;
474             }
475         }
476     }
477 
478     protected DispatchHandler getDispatchHandler() {
479         if (dispatchHandler == null) {
480             dispatchHandler = new DispatchHandler();
481         }
482 
483         return dispatchHandler;
484     }
485 
486     protected void setDispatchHandler(DispatchHandler dispatchHandler) {
487         this.dispatchHandler = dispatchHandler;
488     }
489 
490     /***
491      * Factory method to create a Reader from the given InputStream.
492      * 
493      * @param in
494      *            DOCUMENT ME!
495      * 
496      * @return DOCUMENT ME!
497      * 
498      * @throws IOException
499      *             DOCUMENT ME!
500      */
501     protected Reader createReader(InputStream in) throws IOException {
502         return new BufferedReader(new InputStreamReader(in));
503     }
504 }
505 
506 /*
507  * Redistribution and use of this software and associated documentation
508  * ("Software"), with or without modification, are permitted provided that the
509  * following conditions are met:
510  * 
511  * 1. Redistributions of source code must retain copyright statements and
512  * notices. Redistributions must also contain a copy of this document.
513  * 
514  * 2. Redistributions in binary form must reproduce the above copyright notice,
515  * this list of conditions and the following disclaimer in the documentation
516  * and/or other materials provided with the distribution.
517  * 
518  * 3. The name "DOM4J" must not be used to endorse or promote products derived
519  * from this Software without prior written permission of MetaStuff, Ltd. For
520  * written permission, please contact dom4j-info@metastuff.com.
521  * 
522  * 4. Products derived from this Software may not be called "DOM4J" nor may
523  * "DOM4J" appear in their names without prior written permission of MetaStuff,
524  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
525  * 
526  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
527  * 
528  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
529  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
530  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
531  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
532  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
533  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
534  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
535  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
536  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
537  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
538  * POSSIBILITY OF SUCH DAMAGE.
539  * 
540  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
541  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/SAXModifyElementHandler.html0000644000175000017500000003340110242117761023476 0ustar ebourgebourg SAXModifyElementHandler xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import org.dom4j.Document;
11  import org.dom4j.Element;
12  import org.dom4j.ElementHandler;
13  import org.dom4j.ElementPath;
14  
15  /***
16   * This {@link org.dom4j.ElementHandler}is used to trigger {@link
17   * ElementModifier} objects in order to modify (parts of) the Document on the
18   * fly.
19   * 
20   * <p>
21   * When an element is completely parsed, a copy is handed to the associated (if
22   * any) {@link ElementModifier}that on his turn returns the modified element
23   * that has to come in the tree.
24   * </p>
25   * 
26   * @author Wonne Keysers (Realsoftware.be)
27   */
28  class SAXModifyElementHandler implements ElementHandler {
29      private ElementModifier elemModifier;
30  
31      private Element modifiedElement;
32  
33      public SAXModifyElementHandler(ElementModifier elemModifier) {
34          this.elemModifier = elemModifier;
35      }
36  
37      public void onStart(ElementPath elementPath) {
38          this.modifiedElement = elementPath.getCurrent();
39      }
40  
41      public void onEnd(ElementPath elementPath) {
42          try {
43              Element origElement = elementPath.getCurrent();
44              Element currentParent = origElement.getParent();
45  
46              if (currentParent != null) {
47                  // Clone sets parent + document to null
48                  Element clonedElem = (Element) origElement.clone();
49  
50                  // Ask for modified element
51                  modifiedElement = elemModifier.modifyElement(clonedElem);
52  
53                  if (modifiedElement != null) {
54                      // Restore parent + document
55                      modifiedElement.setParent(origElement.getParent());
56                      modifiedElement.setDocument(origElement.getDocument());
57  
58                      // Replace old with new element in parent
59                      int contentIndex = currentParent.indexOf(origElement);
60                      currentParent.content().set(contentIndex, modifiedElement);
61                  }
62  
63                  // Remove the old element
64                  origElement.detach();
65              } else {
66                  if (origElement.isRootElement()) {
67                      // Clone sets parent + document to null
68                      Element clonedElem = (Element) origElement.clone();
69  
70                      // Ask for modified element
71                      modifiedElement = elemModifier.modifyElement(clonedElem);
72  
73                      if (modifiedElement != null) {
74                          // Restore parent + document
75                          modifiedElement.setDocument(origElement.getDocument());
76  
77                          // Replace old with new element in parent
78                          Document doc = origElement.getDocument();
79                          doc.setRootElement(modifiedElement);
80                      }
81  
82                      // Remove the old element
83                      origElement.detach();
84                  }
85              }
86  
87              // Put the new element on the ElementStack, it might get pruned by
88              // the PruningDispatchHandler
89              if (elementPath instanceof ElementStack) {
90                  ElementStack elementStack = ((ElementStack) elementPath);
91                  elementStack.popElement();
92                  elementStack.pushElement(modifiedElement);
93              }
94          } catch (Exception ex) {
95              throw new SAXModifyException(ex);
96          }
97      }
98  
99      /***
100      * DOCUMENT ME!
101      * 
102      * @return Returns the modified Element.
103      */
104     protected Element getModifiedElement() {
105         return modifiedElement;
106     }
107 }
108 
109 /*
110  * Redistribution and use of this software and associated documentation
111  * ("Software"), with or without modification, are permitted provided that the
112  * following conditions are met:
113  * 
114  * 1. Redistributions of source code must retain copyright statements and
115  * notices. Redistributions must also contain a copy of this document.
116  * 
117  * 2. Redistributions in binary form must reproduce the above copyright notice,
118  * this list of conditions and the following disclaimer in the documentation
119  * and/or other materials provided with the distribution.
120  * 
121  * 3. The name "DOM4J" must not be used to endorse or promote products derived
122  * from this Software without prior written permission of MetaStuff, Ltd. For
123  * written permission, please contact dom4j-info@metastuff.com.
124  * 
125  * 4. Products derived from this Software may not be called "DOM4J" nor may
126  * "DOM4J" appear in their names without prior written permission of MetaStuff,
127  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
128  * 
129  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
130  * 
131  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
132  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
133  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
134  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
135  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
136  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
137  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
138  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
139  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
140  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
141  * POSSIBILITY OF SUCH DAMAGE.
142  * 
143  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
144  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/PruningElementStack.html0000644000175000017500000003432410242117755023015 0ustar ebourgebourg PruningElementStack xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import org.dom4j.Element;
11  import org.dom4j.ElementHandler;
12  
13  /***
14   * <p>
15   * <code>PruningElementStack</code> is a stack of {@link Element}instances
16   * which will prune the tree when a path expression is reached. This is useful
17   * for parsing very large documents where children of the root element can be
18   * processed individually rather than keeping them all in memory at the same
19   * time.
20   * </p>
21   * 
22   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
23   * @version $Revision: 1.11 $
24   */
25  class PruningElementStack extends ElementStack {
26      /*** ElementHandler to call when pruning occurs */
27      private ElementHandler elementHandler;
28  
29      /***
30       * the element name path which denotes the node to remove from its parent
31       * when it is complete (i.e. when it is popped from the stack). The first
32       * entry in the path will be a child of the root node
33       */
34      private String[] path;
35  
36      /***
37       * The level at which a path match can occur. We match when we have popped
38       * the selected node so the and the lastElementIndex points to its parent so
39       * this value should be path.length - 2
40       */
41      private int matchingElementIndex;
42  
43      public PruningElementStack(String[] path, ElementHandler elementHandler) {
44          this.path = path;
45          this.elementHandler = elementHandler;
46          checkPath();
47      }
48  
49      public PruningElementStack(String[] path, ElementHandler elementHandler,
50              int defaultCapacity) {
51          super(defaultCapacity);
52          this.path = path;
53          this.elementHandler = elementHandler;
54          checkPath();
55      }
56  
57      public Element popElement() {
58          Element answer = super.popElement();
59  
60          if ((lastElementIndex == matchingElementIndex)
61                  && (lastElementIndex >= 0)) {
62              // we are popping the correct level in the tree
63              // lets check if the path fits
64              //
65              // NOTE: this is an inefficient way of doing it - we could
66              // maintain a history of which parts matched?
67              if (validElement(answer, lastElementIndex + 1)) {
68                  Element parent = null;
69  
70                  for (int i = 0; i <= lastElementIndex; i++) {
71                      parent = stack[i];
72  
73                      if (!validElement(parent, i)) {
74                          parent = null;
75  
76                          break;
77                      }
78                  }
79  
80                  if (parent != null) {
81                      pathMatches(parent, answer);
82                  }
83              }
84          }
85  
86          return answer;
87      }
88  
89      protected void pathMatches(Element parent, Element selectedNode) {
90          elementHandler.onEnd(this);
91          parent.remove(selectedNode);
92      }
93  
94      protected boolean validElement(Element element, int index) {
95          String requiredName = path[index];
96          String name = element.getName();
97  
98          if (requiredName == name) {
99              return true;
100         }
101 
102         if ((requiredName != null) && (name != null)) {
103             return requiredName.equals(name);
104         }
105 
106         return false;
107     }
108 
109     private void checkPath() {
110         if (path.length < 2) {
111             throw new RuntimeException("Invalid path of length: " + path.length
112                     + " it must be greater than 2");
113         }
114 
115         matchingElementIndex = path.length - 2;
116     }
117 }
118 
119 /*
120  * Redistribution and use of this software and associated documentation
121  * ("Software"), with or without modification, are permitted provided that the
122  * following conditions are met:
123  * 
124  * 1. Redistributions of source code must retain copyright statements and
125  * notices. Redistributions must also contain a copy of this document.
126  * 
127  * 2. Redistributions in binary form must reproduce the above copyright notice,
128  * this list of conditions and the following disclaimer in the documentation
129  * and/or other materials provided with the distribution.
130  * 
131  * 3. The name "DOM4J" must not be used to endorse or promote products derived
132  * from this Software without prior written permission of MetaStuff, Ltd. For
133  * written permission, please contact dom4j-info@metastuff.com.
134  * 
135  * 4. Products derived from this Software may not be called "DOM4J" nor may
136  * "DOM4J" appear in their names without prior written permission of MetaStuff,
137  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
138  * 
139  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
140  * 
141  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
142  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
143  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
144  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
145  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
146  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
147  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
148  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
149  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
150  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
151  * POSSIBILITY OF SUCH DAMAGE.
152  * 
153  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
154  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/SAXModifyReader.html0000644000175000017500000002751110242117700022007 0ustar ebourgebourg SAXModifyReader xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import org.dom4j.DocumentFactory;
11  
12  import org.xml.sax.SAXException;
13  import org.xml.sax.XMLReader;
14  
15  /***
16   * The SAXModifier parses, updates and writes an XML document. <br>
17   * The input that is parsed is directly written to the specified output, unless
18   * the current xml element has an associated ElementHandler. <br>
19   * The {@link org.dom4j.ElementHandler}objects make it possible to update the
20   * document on the fly, without having read tje complete document.
21   * 
22   * @author Wonne Keysers (Realsoftware.be)
23   * 
24   * @see org.dom4j.io.SAXReader
25   * @see org.dom4j.io.XMLWriters
26   */
27  class SAXModifyReader extends SAXReader {
28      private XMLWriter xmlWriter;
29  
30      private boolean pruneElements;
31  
32      public SAXModifyReader() {
33      }
34  
35      public SAXModifyReader(boolean validating) {
36          super(validating);
37      }
38  
39      public SAXModifyReader(DocumentFactory factory) {
40          super(factory);
41      }
42  
43      public SAXModifyReader(DocumentFactory factory, boolean validating) {
44          super(factory, validating);
45      }
46  
47      public SAXModifyReader(XMLReader xmlReader) {
48          super(xmlReader);
49      }
50  
51      public SAXModifyReader(XMLReader xmlReader, boolean validating) {
52          super(xmlReader, validating);
53      }
54  
55      public SAXModifyReader(String xmlReaderClassName) throws SAXException {
56          super(xmlReaderClassName);
57      }
58  
59      public SAXModifyReader(String xmlReaderClassName, boolean validating)
60              throws SAXException {
61          super(xmlReaderClassName, validating);
62      }
63  
64      public void setXMLWriter(XMLWriter writer) {
65          this.xmlWriter = writer;
66      }
67  
68      public boolean isPruneElements() {
69          return pruneElements;
70      }
71  
72      public void setPruneElements(boolean pruneElements) {
73          this.pruneElements = pruneElements;
74      }
75  
76      protected SAXContentHandler createContentHandler(XMLReader reader) {
77          SAXModifyContentHandler handler = new SAXModifyContentHandler(
78                  getDocumentFactory(), getDispatchHandler());
79  
80          handler.setXMLWriter(xmlWriter);
81  
82          return handler;
83      }
84  
85      protected XMLWriter getXMLWriter() {
86          return this.xmlWriter;
87      }
88  }
89  
90  /*
91   * Redistribution and use of this software and associated documentation
92   * ("Software"), with or without modification, are permitted provided that the
93   * following conditions are met:
94   * 
95   * 1. Redistributions of source code must retain copyright statements and
96   * notices. Redistributions must also contain a copy of this document.
97   * 
98   * 2. Redistributions in binary form must reproduce the above copyright notice,
99   * this list of conditions and the following disclaimer in the documentation
100  * and/or other materials provided with the distribution.
101  * 
102  * 3. The name "DOM4J" must not be used to endorse or promote products derived
103  * from this Software without prior written permission of MetaStuff, Ltd. For
104  * written permission, please contact dom4j-info@metastuff.com.
105  * 
106  * 4. Products derived from this Software may not be called "DOM4J" nor may
107  * "DOM4J" appear in their names without prior written permission of MetaStuff,
108  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
109  * 
110  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
111  * 
112  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
113  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
114  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
115  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
116  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
117  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
118  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
119  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
120  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
121  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
122  * POSSIBILITY OF SUCH DAMAGE.
123  * 
124  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
125  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/HTMLWriter.html0000644000175000017500000021307110242117625021026 0ustar ebourgebourg HTMLWriter xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.io.IOException;
11  import java.io.OutputStream;
12  import java.io.StringWriter;
13  import java.io.UnsupportedEncodingException;
14  import java.io.Writer;
15  import java.util.HashSet;
16  import java.util.Iterator;
17  import java.util.Set;
18  import java.util.Stack;
19  
20  import org.dom4j.Document;
21  import org.dom4j.DocumentHelper;
22  import org.dom4j.Element;
23  import org.dom4j.Entity;
24  import org.dom4j.Node;
25  
26  import org.xml.sax.SAXException;
27  
28  /***
29   * <p>
30   * <code>HTMLWriter</code> takes a DOM4J tree and formats it to a stream as
31   * HTML. This formatter is similar to XMLWriter but it outputs the text of CDATA
32   * and Entity sections rather than the serialised format as in XML, it has an
33   * XHTML mode, it retains whitespace in certain elements such as &lt;PRE&gt;,
34   * and it supports certain elements which have no corresponding close tag such
35   * as for &lt;BR&gt; and &lt;P&gt;.
36   * </p>
37   * 
38   * <p>
39   * The OutputFormat passed in to the constructor is checked for isXHTML() and
40   * isExpandEmptyElements(). See {@link OutputFormat OutputFormat}for details.
41   * Here are the rules for <b>this class </b> based on an OutputFormat, "format",
42   * passed in to the constructor: <br/><br/>
43   * 
44   * <ul>
45   * <li>If an element is in {@link #getOmitElementCloseSet()
46   * getOmitElementCloseSet}, then it is treated specially:
47   * 
48   * <ul>
49   * <li>It never expands, since some browsers treat this as two separate
50   * Horizontal Rules: &lt;HR&gt;&lt;/HR&gt;</li>
51   * <li>If {@link org.dom4j.io.OutputFormat#isXHTML() format.isXHTML()}, then
52   * it has a space before the closing single-tag slash, since Netscape 4.x-
53   * treats this: &lt;HR /&gt; as an element named "HR" with an attribute named
54   * "/", but that's better than when it refuses to recognize this: &lt;hr/&gt;
55   * which it thinks is an element named "HR/".</li>
56   * </ul>
57   * 
58   * </li>
59   * <li>If {@link org.dom4j.io.OutputFormat#isXHTML() format.isXHTML()}, all
60   * elements must have either a close element, or be a closed single tag.</li>
61   * <li>If {@link org.dom4j.io.OutputFormat#isExpandEmptyElements()
62   * format.isExpandEmptyElements()}() is true, all elements are expanded except
63   * as above.</li>
64   * </ul>
65   * 
66   * <b>Examples </b>
67   * </p>
68   * 
69   * <p>
70   * </p>
71   * 
72   * <p>
73   * If isXHTML == true, CDATA sections look like this:
74   * 
75   * <PRE>
76   * 
77   * <b>&lt;myelement&gt;&lt;![CDATA[My data]]&gt;&lt;/myelement&gt; </b>
78   * 
79   * </PRE>
80   * 
81   * Otherwise, they look like this:
82   * 
83   * <PRE>
84   * 
85   * <b>&lt;myelement&gt;My data&lt;/myelement&gt; </b>
86   * 
87   * </PRE>
88   * 
89   * </p>
90   * 
91   * <p>
92   * Basically, {@link OutputFormat.isXHTML() OutputFormat.isXHTML()} ==
93   * <code>true</code> will produce valid XML, while {@link
94   * org.dom4j.io.OutputFormat#isExpandEmptyElements()
95   * format.isExpandEmptyElements()} determines whether empty elements are
96   * expanded if isXHTML is true, excepting the special HTML single tags.
97   * </p>
98   * 
99   * <p>
100  * Also, HTMLWriter handles tags whose contents should be preformatted, that is,
101  * whitespace-preserved. By default, this set includes the tags &lt;PRE&gt;,
102  * &lt;SCRIPT&gt;, &lt;STYLE&gt;, and &lt;TEXTAREA&gt;, case insensitively. It
103  * does not include &lt;IFRAME&gt;. Other tags, such as &lt;CODE&gt;,
104  * &lt;KBD&gt;, &lt;TT&gt;, &lt;VAR&gt;, are usually rendered in a different
105  * font in most browsers, but don't preserve whitespace, so they also don't
106  * appear in the default list. HTML Comments are always whitespace-preserved.
107  * However, the parser you use may store comments with linefeed-only text nodes
108  * (\n) even if your platform uses another line.separator character, and
109  * HTMLWriter outputs Comment nodes exactly as the DOM is set up by the parser.
110  * See examples and discussion here: {@link#setPreformattedTags(java.util.Set)
111  * setPreformattedTags}
112  * </p>
113  * 
114  * <p>
115  * <b>Examples </b>
116  * </p>
117  * <blockquote>
118  * <p>
119  * <b>Pretty Printing </b>
120  * </p>
121  * 
122  * <p>
123  * This example shows how to pretty print a string containing a valid HTML
124  * document to a string. You can also just call the static methods of this
125  * class: <br>
126  * {@link #prettyPrintHTML(String) prettyPrintHTML(String)}or <br>
127  * {@link #prettyPrintHTML(String,boolean,boolean,boolean,boolean)
128  * prettyPrintHTML(String,boolean,boolean,boolean,boolean)} or, <br>
129  * {@link #prettyPrintXHTML(String) prettyPrintXHTML(String)}for XHTML (note
130  * the X)
131  * </p>
132  * 
133  * <pre>
134  * String testPrettyPrint(String html) {
135  *     StringWriter sw = new StringWriter();
136  *     OutputFormat format = OutputFormat.createPrettyPrint();
137  *     // These are the default values for createPrettyPrint,
138  *     // so you needn't set them:
139  *     // format.setNewlines(true);
140  *     // format.setTrimText(true);&lt;/font&gt;
141  *     format.setXHTML(true);
142  *     HTMLWriter writer = new HTMLWriter(sw, format);
143  *     Document document = DocumentHelper.parseText(html);
144  *     writer.write(document);
145  *     writer.flush();
146  *     return sw.toString();
147  * }
148  * </pre>
149  * 
150  * <p>
151  * This example shows how to create a "squeezed" document, but one that will
152  * work in browsers even if the browser line length is limited. No newlines are
153  * included, no extra whitespace at all, except where it it required by
154  * {@link #setPreformattedTags(java.util.Set) setPreformattedTags}.
155  * </p>
156  * 
157  * <pre>
158  * String testCrunch(String html) {
159  *     StringWriter sw = new StringWriter();
160  *     OutputFormat format = OutputFormat.createPrettyPrint();
161  *     format.setNewlines(false);
162  *     format.setTrimText(true);
163  *     format.setIndent(&quot;&quot;);
164  *     format.setXHTML(true);
165  *     format.setExpandEmptyElements(false);
166  *     format.setNewLineAfterNTags(20);
167  *     org.dom4j.io.HTMLWriter writer = new HTMLWriter(sw, format);
168  *     org.dom4j.Document document = DocumentHelper.parseText(html);
169  *     writer.write(document);
170  *     writer.flush();
171  *     return sw.toString();
172  * }
173  * </pre>
174  * 
175  * </blockquote>
176  * 
177  * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
178  * @author Laramie Crocker
179  * @version $Revision: 1.21 $
180  */
181 public class HTMLWriter extends XMLWriter {
182     private static String lineSeparator = System.getProperty("line.separator");
183 
184     protected static final HashSet DEFAULT_PREFORMATTED_TAGS;
185 
186     static {
187         // If you change this list, update the javadoc examples, above in the
188         // class javadoc, in writeElement, and in setPreformattedTags().
189         DEFAULT_PREFORMATTED_TAGS = new HashSet();
190         DEFAULT_PREFORMATTED_TAGS.add("PRE");
191         DEFAULT_PREFORMATTED_TAGS.add("SCRIPT");
192         DEFAULT_PREFORMATTED_TAGS.add("STYLE");
193         DEFAULT_PREFORMATTED_TAGS.add("TEXTAREA");
194     }
195 
196     protected static final OutputFormat DEFAULT_HTML_FORMAT;
197 
198     static {
199         DEFAULT_HTML_FORMAT = new OutputFormat("  ", true);
200         DEFAULT_HTML_FORMAT.setTrimText(true);
201         DEFAULT_HTML_FORMAT.setSuppressDeclaration(true);
202     }
203 
204     private Stack formatStack = new Stack();
205 
206     private String lastText = "";
207 
208     private int tagsOuput = 0;
209 
210     // legal values are 0+, but -1 signifies lazy initialization.
211     private int newLineAfterNTags = -1;
212 
213     private HashSet preformattedTags = DEFAULT_PREFORMATTED_TAGS;
214 
215     /***
216      * Used to store the qualified element names which should have no close
217      * element tag
218      */
219     private HashSet omitElementCloseSet;
220 
221     public HTMLWriter(Writer writer) {
222         super(writer, DEFAULT_HTML_FORMAT);
223     }
224 
225     public HTMLWriter(Writer writer, OutputFormat format) {
226         super(writer, format);
227     }
228 
229     public HTMLWriter() throws UnsupportedEncodingException {
230         super(DEFAULT_HTML_FORMAT);
231     }
232 
233     public HTMLWriter(OutputFormat format) throws UnsupportedEncodingException {
234         super(format);
235     }
236 
237     public HTMLWriter(OutputStream out) throws UnsupportedEncodingException {
238         super(out, DEFAULT_HTML_FORMAT);
239     }
240 
241     public HTMLWriter(OutputStream out, OutputFormat format)
242             throws UnsupportedEncodingException {
243         super(out, format);
244     }
245 
246     public void startCDATA() throws SAXException {
247     }
248 
249     public void endCDATA() throws SAXException {
250     }
251 
252     // Overloaded methods
253     // added isXHTML() stuff so you get the CDATA brackets if you desire.
254     protected void writeCDATA(String text) throws IOException {
255         // XXX: Should we escape entities?
256         // writer.write( escapeElementEntities( text ) );
257         if (getOutputFormat().isXHTML()) {
258             super.writeCDATA(text);
259         } else {
260             writer.write(text);
261         }
262 
263         lastOutputNodeType = Node.CDATA_SECTION_NODE;
264     }
265 
266     protected void writeEntity(Entity entity) throws IOException {
267         writer.write(entity.getText());
268         lastOutputNodeType = Node.ENTITY_REFERENCE_NODE;
269     }
270 
271     protected void writeDeclaration() throws IOException {
272     }
273 
274     protected void writeString(String text) throws IOException {
275         /*
276          * DOM stores \n at the end of text nodes that are newlines. This is
277          * significant if we are in a PRE section. However, we only want to
278          * output the system line.separator, not \n. This is a little brittle,
279          * but this function appears to be called with these lineseparators as a
280          * separate TEXT_NODE. If we are in a preformatted section, output the
281          * right line.separator, otherwise ditch. If the single \n character is
282          * not the text, then do the super thing to output the text.
283          * 
284          * Also, we store the last text that was not a \n since it may be used
285          * by writeElement in this class to line up preformatted tags.
286          */
287         if (text.equals("\n")) {
288             if (!formatStack.empty()) {
289                 super.writeString(lineSeparator);
290             }
291 
292             return;
293         }
294 
295         lastText = text;
296 
297         if (formatStack.empty()) {
298             super.writeString(text.trim());
299         } else {
300             super.writeString(text);
301         }
302     }
303 
304     /***
305      * Overriden method to not close certain element names to avoid wierd
306      * behaviour from browsers for versions up to 5.x
307      * 
308      * @param qualifiedName
309      *            DOCUMENT ME!
310      * 
311      * @throws IOException
312      *             DOCUMENT ME!
313      */
314     protected void writeClose(String qualifiedName) throws IOException {
315         if (!omitElementClose(qualifiedName)) {
316             super.writeClose(qualifiedName);
317         }
318     }
319 
320     protected void writeEmptyElementClose(String qualifiedName)
321             throws IOException {
322         if (getOutputFormat().isXHTML()) {
323             // xhtml, always check with format object whether to expand or not.
324             if (omitElementClose(qualifiedName)) {
325                 // it was a special omit tag, do it the XHTML way: "<br/>",
326                 // ignoring the expansion option, since <br></br> is OK XML,
327                 // but produces twice the linefeeds desired in the browser.
328                 // for netscape 4.7, though all are fine with it, write a space
329                 // before the close slash.
330                 writer.write(" />");
331             } else {
332                 super.writeEmptyElementClose(qualifiedName);
333             }
334         } else {
335             // html, not xhtml
336             if (omitElementClose(qualifiedName)) {
337                 // it was a special omit tag, do it the old html way: "<br>".
338                 writer.write(">");
339             } else {
340                 // it was NOT a special omit tag, check with format object
341                 // whether to expand or not.
342                 super.writeEmptyElementClose(qualifiedName);
343             }
344         }
345     }
346 
347     protected boolean omitElementClose(String qualifiedName) {
348         return internalGetOmitElementCloseSet().contains(
349                 qualifiedName.toUpperCase());
350     }
351 
352     private HashSet internalGetOmitElementCloseSet() {
353         if (omitElementCloseSet == null) {
354             omitElementCloseSet = new HashSet();
355             loadOmitElementCloseSet(omitElementCloseSet);
356         }
357 
358         return omitElementCloseSet;
359     }
360 
361     // If you change this, change the javadoc for getOmitElementCloseSet.
362     protected void loadOmitElementCloseSet(Set set) {
363         set.add("AREA");
364         set.add("BASE");
365         set.add("BR");
366         set.add("COL");
367         set.add("HR");
368         set.add("IMG");
369         set.add("INPUT");
370         set.add("LINK");
371         set.add("META");
372         set.add("P");
373         set.add("PARAM");
374     }
375 
376     // let the people see the set, but not modify it.
377 
378     /***
379      * A clone of the Set of elements that can have their close-tags omitted. By
380      * default it should be "AREA", "BASE", "BR", "COL", "HR", "IMG", "INPUT",
381      * "LINK", "META", "P", "PARAM"
382      * 
383      * @return A clone of the Set.
384      */
385     public Set getOmitElementCloseSet() {
386         return (Set) (internalGetOmitElementCloseSet().clone());
387     }
388 
389     /***
390      * To use the empty set, pass an empty Set, or null:
391      * 
392      * <pre>
393      * 
394      * 
395      *       setOmitElementCloseSet(new HashSet());
396      *     or
397      *       setOmitElementCloseSet(null);
398      * 
399      *  
400      * </pre>
401      * 
402      * @param newSet
403      *            DOCUMENT ME!
404      */
405     public void setOmitElementCloseSet(Set newSet) {
406         // resets, and safely empties it out if newSet is null.
407         omitElementCloseSet = new HashSet();
408 
409         if (newSet != null) {
410             omitElementCloseSet = new HashSet();
411 
412             Object aTag;
413             Iterator iter = newSet.iterator();
414 
415             while (iter.hasNext()) {
416                 aTag = iter.next();
417 
418                 if (aTag != null) {
419                     omitElementCloseSet.add(aTag.toString().toUpperCase());
420                 }
421             }
422         }
423     }
424 
425     /***
426      * @see #setPreformattedTags(java.util.Set) setPreformattedTags
427      */
428     public Set getPreformattedTags() {
429         return (Set) (preformattedTags.clone());
430     }
431 
432     /***
433      * <p>
434      * Override the default set, which includes PRE, SCRIPT, STYLE, and
435      * TEXTAREA, case insensitively.
436      * </p>
437      * 
438      * <p>
439      * <b>Setting Preformatted Tags </b>
440      * </p>
441      * 
442      * <p>
443      * Pass in a Set of Strings, one for each tag name that should be treated
444      * like a PRE tag. You may pass in null or an empty Set to assign the empty
445      * set, in which case no tags will be treated as preformatted, except that
446      * HTML Comments will continue to be preformatted. If a tag is included in
447      * the set of preformatted tags, all whitespace within the tag will be
448      * preserved, including whitespace on the same line preceding the close tag.
449      * This will generally make the close tag not line up with the start tag,
450      * but it preserves the intention of the whitespace within the tag.
451      * </p>
452      * 
453      * <p>
454      * The browser considers leading whitespace before the close tag to be
455      * significant, but leading whitespace before the open tag to be
456      * insignificant. For example, if the HTML author doesn't put the close
457      * TEXTAREA tag flush to the left margin, then the TEXTAREA control in the
458      * browser will have spaces on the last line inside the control. This may be
459      * the HTML author's intent. Similarly, in a PRE, the browser treats a
460      * flushed left close PRE tag as different from a close tag with leading
461      * whitespace. Again, this must be left up to the HTML author.
462      * </p>
463      * 
464      * <p>
465      * <b>Examples </b>
466      * </p>
467      * <blockquote>
468      * <p>
469      * Here is an example of how you can set the PreformattedTags list using
470      * setPreformattedTags to include IFRAME, as well as the default set, if you
471      * have an instance of this class named myHTMLWriter:
472      * 
473      * <pre>
474      * Set current = myHTMLWriter.getPreformattedTags();
475      * current.add(&quot;IFRAME&quot;);
476      * myHTMLWriter.setPreformattedTags(current);
477      * 
478      * //The set is now &lt;b&gt;PRE, SCRIPT, STYLE, TEXTAREA, IFRAME&lt;/b&gt;
479      * 
480      * 
481      * </pre>
482      * 
483      * Similarly, you can simply replace it with your own:
484      * 
485      * <pre>
486      * 
487      * 
488      *       HashSet newset = new HashSet();
489      *       newset.add(&quot;PRE&quot;);
490      *       newset.add(&quot;TEXTAREA&quot;);
491      *       myHTMLWriter.setPreformattedTags(newset);
492      * 
493      *       //The set is now &lt;b&gt;{PRE, TEXTAREA}&lt;/b&gt;
494      * 
495      *  
496      * </pre>
497      * 
498      * You can remove all tags from the preformatted tags list, with an empty
499      * set, like this:
500      * 
501      * <pre>
502      * 
503      * 
504      *       myHTMLWriter.setPreformattedTags(new HashSet());
505      * 
506      *       //The set is now &lt;b&gt;{}&lt;/b&gt;
507      * 
508      *  
509      * </pre>
510      * 
511      * or with null, like this:
512      * 
513      * <pre>
514      * 
515      * 
516      *       myHTMLWriter.setPreformattedTags(null);
517      * 
518      *       //The set is now &lt;b&gt;{}&lt;/b&gt;
519      * 
520      *  
521      * </pre>
522      * 
523      * </p>
524      * </blockquote>
525      * 
526      * @param newSet
527      *            DOCUMENT ME!
528      */
529     public void setPreformattedTags(Set newSet) {
530         // no fancy merging, just set it, assuming they did a
531         // getExcludeTrimTags() first if they wanted to preserve the default
532         // set.
533         // resets, and safely empties it out if newSet is null.
534         preformattedTags = new HashSet();
535 
536         if (newSet != null) {
537             Object aTag;
538             Iterator iter = newSet.iterator();
539 
540             while (iter.hasNext()) {
541                 aTag = iter.next();
542 
543                 if (aTag != null) {
544                     preformattedTags.add(aTag.toString().toUpperCase());
545                 }
546             }
547         }
548     }
549 
550     /***
551      * DOCUMENT ME!
552      * 
553      * @param qualifiedName
554      *            DOCUMENT ME!
555      * 
556      * @return true if the qualifiedName passed in matched (case-insensitively)
557      *         a tag in the preformattedTags set, or false if not found or if
558      *         the set is empty or null.
559      * 
560      * @see #setPreformattedTags(java.util.Set) setPreformattedTags
561      */
562     public boolean isPreformattedTag(String qualifiedName) {
563         // A null set implies that the user called setPreformattedTags(null),
564         // which means they want no tags to be preformatted.
565         return (preformattedTags != null)
566                 && (preformattedTags.contains(qualifiedName.toUpperCase()));
567     }
568 
569     /***
570      * This override handles any elements that should not remove whitespace,
571      * such as &lt;PRE&gt;, &lt;SCRIPT&gt;, &lt;STYLE&gt;, and &lt;TEXTAREA&gt;.
572      * Note: the close tags won't line up with the open tag, but we can't alter
573      * that. See javadoc note at setPreformattedTags.
574      * 
575      * @param element
576      *            DOCUMENT ME!
577      * 
578      * @throws IOException
579      *             When the stream could not be written to.
580      * 
581      * @see #setPreformattedTags(java.util.Set) setPreformattedTags
582      */
583     protected void writeElement(Element element) throws IOException {
584         if (newLineAfterNTags == -1) { // lazy initialization check
585             lazyInitNewLinesAfterNTags();
586         }
587 
588         if (newLineAfterNTags > 0) {
589             if ((tagsOuput > 0) && ((tagsOuput % newLineAfterNTags) == 0)) {
590                 super.writer.write(lineSeparator);
591             }
592         }
593 
594         tagsOuput++;
595 
596         String qualifiedName = element.getQualifiedName();
597         String saveLastText = lastText;
598         int size = element.nodeCount();
599 
600         if (isPreformattedTag(qualifiedName)) {
601             OutputFormat currentFormat = getOutputFormat();
602             boolean saveNewlines = currentFormat.isNewlines();
603             boolean saveTrimText = currentFormat.isTrimText();
604             String currentIndent = currentFormat.getIndent();
605 
606             // You could have nested PREs, or SCRIPTS within PRE... etc.,
607             // therefore use push and pop.
608             formatStack.push(new FormatState(saveNewlines, saveTrimText,
609                     currentIndent));
610 
611             try {
612                 // do this manually, since it won't be done while outputting
613                 // the tag.
614                 super.writePrintln();
615 
616                 if ((saveLastText.trim().length() == 0)
617                         && (currentIndent != null)
618                         && (currentIndent.length() > 0)) {
619                     // We are indenting, but we want to line up with the close
620                     // tag. lastText was the indent (whitespace, no \n) before
621                     // the preformatted start tag. So write it out instead of
622                     // the current indent level. This makes it line up with its
623                     // close tag.
624                     super.writer.write(justSpaces(saveLastText));
625                 }
626 
627                 // actually, newlines are handled in this class by writeString,
628                 // depending on if the stack is empty.
629                 currentFormat.setNewlines(false);
630                 currentFormat.setTrimText(false);
631                 currentFormat.setIndent("");
632 
633                 // This line is the recursive one:
634                 super.writeElement(element);
635             } finally {
636                 FormatState state = (FormatState) formatStack.pop();
637                 currentFormat.setNewlines(state.isNewlines());
638                 currentFormat.setTrimText(state.isTrimText());
639                 currentFormat.setIndent(state.getIndent());
640             }
641         } else {
642             super.writeElement(element);
643         }
644     }
645 
646     private String justSpaces(String text) {
647         int size = text.length();
648         StringBuffer res = new StringBuffer(size);
649         char c;
650 
651         for (int i = 0; i < size; i++) {
652             c = text.charAt(i);
653 
654             switch (c) {
655                 case '\r':
656                 case '\n':
657 
658                     continue;
659 
660                 default:
661                     res.append(c);
662             }
663         }
664 
665         return res.toString();
666     }
667 
668     private void lazyInitNewLinesAfterNTags() {
669         if (getOutputFormat().isNewlines()) {
670             // don't bother, newlines are going to happen anyway.
671             newLineAfterNTags = 0;
672         } else {
673             newLineAfterNTags = getOutputFormat().getNewLineAfterNTags();
674         }
675     }
676 
677     // Convenience methods, static, with bunch-o-defaults
678 
679     /***
680      * Convenience method to just get a String result.
681      * 
682      * @param html
683      *            DOCUMENT ME!
684      * 
685      * @return a pretty printed String from the source string, preserving
686      *         whitespace in the defaultPreformattedTags set, and leaving the
687      *         close tags off of the default omitElementCloseSet set. Use one of
688      *         the write methods if you want stream output.
689      * 
690      * @throws java.io.IOException
691      * @throws java.io.UnsupportedEncodingException
692      * @throws org.dom4j.DocumentException
693      */
694     public static String prettyPrintHTML(String html)
695             throws java.io.IOException, java.io.UnsupportedEncodingException,
696             org.dom4j.DocumentException {
697         return prettyPrintHTML(html, true, true, false, true);
698     }
699 
700     /***
701      * Convenience method to just get a String result, but <b>As XHTML </b>.
702      * 
703      * @param html
704      *            DOCUMENT ME!
705      * 
706      * @return a pretty printed String from the source string, preserving
707      *         whitespace in the defaultPreformattedTags set, but conforming to
708      *         XHTML: no close tags are omitted (though if empty, they will be
709      *         converted to XHTML empty tags: &lt;HR/&gt; Use one of the write
710      *         methods if you want stream output.
711      * 
712      * @throws java.io.IOException
713      * @throws java.io.UnsupportedEncodingException
714      * @throws org.dom4j.DocumentException
715      */
716     public static String prettyPrintXHTML(String html)
717             throws java.io.IOException, java.io.UnsupportedEncodingException,
718             org.dom4j.DocumentException {
719         return prettyPrintHTML(html, true, true, true, false);
720     }
721 
722     /***
723      * DOCUMENT ME!
724      * 
725      * @param html
726      *            DOCUMENT ME!
727      * @param newlines
728      *            DOCUMENT ME!
729      * @param trim
730      *            DOCUMENT ME!
731      * @param isXHTML
732      *            DOCUMENT ME!
733      * @param expandEmpty
734      *            DOCUMENT ME!
735      * 
736      * @return a pretty printed String from the source string, preserving
737      *         whitespace in the defaultPreformattedTags set, and leaving the
738      *         close tags off of the default omitElementCloseSet set. This
739      *         override allows you to specify various formatter options. Use one
740      *         of the write methods if you want stream output.
741      * 
742      * @throws java.io.IOException
743      * @throws java.io.UnsupportedEncodingException
744      * @throws org.dom4j.DocumentException
745      */
746     public static String prettyPrintHTML(String html, boolean newlines,
747             boolean trim, boolean isXHTML, boolean expandEmpty)
748             throws java.io.IOException, java.io.UnsupportedEncodingException,
749             org.dom4j.DocumentException {
750         StringWriter sw = new StringWriter();
751         OutputFormat format = OutputFormat.createPrettyPrint();
752         format.setNewlines(newlines);
753         format.setTrimText(trim);
754         format.setXHTML(isXHTML);
755         format.setExpandEmptyElements(expandEmpty);
756 
757         HTMLWriter writer = new HTMLWriter(sw, format);
758         Document document = DocumentHelper.parseText(html);
759         writer.write(document);
760         writer.flush();
761 
762         return sw.toString();
763     }
764 
765     // Allows us to the current state of the format in this struct on the
766     // formatStack.
767     private class FormatState {
768         private boolean newlines = false;
769 
770         private boolean trimText = false;
771 
772         private String indent = "";
773 
774         public FormatState(boolean newLines, boolean trimText, String indent) {
775             this.newlines = newLines;
776             this.trimText = trimText;
777             this.indent = indent;
778         }
779 
780         public boolean isNewlines() {
781             return newlines;
782         }
783 
784         public boolean isTrimText() {
785             return trimText;
786         }
787 
788         public String getIndent() {
789             return indent;
790         }
791     }
792 }
793 
794 /*
795  * <html> <head> <title>My Title </title> <style> .foo { text-align: Right; }
796  * </style> <script> function mojo(){ return "bar"; } </script> <script
797  * language="JavaScript"> <!-- //this is the canonical javascript hiding.
798  * function foo(){ return "foo"; } //--> </script> </head> <!-- this is a
799  * comment --> <body bgcolor="#A4BFDD" mojo="&amp;"> entities: &#160; &amp;
800  * &quot; &lt; &gt; %23 <p></p> <mojo> </mojo> <foo /> <table border="1"> <tr>
801  * <td><pre> line0 <hr /> line1 <b>line2, should line up, indent-wise </b> line
802  * 3 line 4 </pre></td><td></td></tr> </table> <myCDATAElement> <![CDATA[My
803  * data]]> </myCDATAElement> </body> </html>
804  */
805 
806 /*
807  * Redistribution and use of this software and associated documentation
808  * ("Software"), with or without modification, are permitted provided that the
809  * following conditions are met:
810  * 
811  * 1. Redistributions of source code must retain copyright statements and
812  * notices. Redistributions must also contain a copy of this document.
813  * 
814  * 2. Redistributions in binary form must reproduce the above copyright notice,
815  * this list of conditions and the following disclaimer in the documentation
816  * and/or other materials provided with the distribution.
817  * 
818  * 3. The name "DOM4J" must not be used to endorse or promote products derived
819  * from this Software without prior written permission of MetaStuff, Ltd. For
820  * written permission, please contact dom4j-info@metastuff.com.
821  * 
822  * 4. Products derived from this Software may not be called "DOM4J" nor may
823  * "DOM4J" appear in their names without prior written permission of MetaStuff,
824  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
825  * 
826  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
827  * 
828  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
829  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
830  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
831  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
832  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
833  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
834  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
835  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
836  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
837  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
838  * POSSIBILITY OF SUCH DAMAGE.
839  * 
840  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
841  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/XMLResult.html0000644000175000017500000002547210242117573020734 0ustar ebourgebourg XMLResult xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.io.OutputStream;
11  import java.io.UnsupportedEncodingException;
12  import java.io.Writer;
13  
14  import javax.xml.transform.sax.SAXResult;
15  
16  import org.xml.sax.ContentHandler;
17  import org.xml.sax.ext.LexicalHandler;
18  
19  /***
20   * <p>
21   * <code>XMLResult</code> implements a JAXP {@link SAXResult}for an output
22   * stream with support for pretty printing and control over how the XML is
23   * formatted.
24   * </p>
25   * 
26   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
27   * @version $Revision: 1.9 $
28   */
29  public class XMLResult extends SAXResult {
30      private XMLWriter xmlWriter;
31  
32      public XMLResult() {
33          this(new XMLWriter());
34      }
35  
36      public XMLResult(Writer writer) {
37          this(new XMLWriter(writer));
38      }
39  
40      public XMLResult(Writer writer, OutputFormat format) {
41          this(new XMLWriter(writer, format));
42      }
43  
44      public XMLResult(OutputStream out) throws UnsupportedEncodingException {
45          this(new XMLWriter(out));
46      }
47  
48      public XMLResult(OutputStream out, OutputFormat format)
49              throws UnsupportedEncodingException {
50          this(new XMLWriter(out, format));
51      }
52  
53      public XMLResult(XMLWriter xmlWriter) {
54          super(xmlWriter);
55          this.xmlWriter = xmlWriter;
56          setLexicalHandler(xmlWriter);
57      }
58  
59      public XMLWriter getXMLWriter() {
60          return xmlWriter;
61      }
62  
63      public void setXMLWriter(XMLWriter writer) {
64          this.xmlWriter = writer;
65          setHandler(xmlWriter);
66          setLexicalHandler(xmlWriter);
67      }
68  
69      public ContentHandler getHandler() {
70          return xmlWriter;
71      }
72  
73      public LexicalHandler getLexicalHandler() {
74          return xmlWriter;
75      }
76  }
77  
78  /*
79   * Redistribution and use of this software and associated documentation
80   * ("Software"), with or without modification, are permitted provided that the
81   * following conditions are met:
82   * 
83   * 1. Redistributions of source code must retain copyright statements and
84   * notices. Redistributions must also contain a copy of this document.
85   * 
86   * 2. Redistributions in binary form must reproduce the above copyright notice,
87   * this list of conditions and the following disclaimer in the documentation
88   * and/or other materials provided with the distribution.
89   * 
90   * 3. The name "DOM4J" must not be used to endorse or promote products derived
91   * from this Software without prior written permission of MetaStuff, Ltd. For
92   * written permission, please contact dom4j-info@metastuff.com.
93   * 
94   * 4. Products derived from this Software may not be called "DOM4J" nor may
95   * "DOM4J" appear in their names without prior written permission of MetaStuff,
96   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
97   * 
98   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
99   * 
100  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
101  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
102  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
103  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
104  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
105  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
106  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
107  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
108  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
109  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
110  * POSSIBILITY OF SUCH DAMAGE.
111  * 
112  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
113  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/io/DOMWriter.html0000644000175000017500000010614510242117740020702 0ustar ebourgebourg DOMWriter xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.io;
9   
10  import java.util.List;
11  
12  import org.dom4j.Attribute;
13  import org.dom4j.CDATA;
14  import org.dom4j.Comment;
15  import org.dom4j.Document;
16  import org.dom4j.DocumentException;
17  import org.dom4j.Element;
18  import org.dom4j.Entity;
19  import org.dom4j.Namespace;
20  import org.dom4j.ProcessingInstruction;
21  import org.dom4j.Text;
22  import org.dom4j.tree.NamespaceStack;
23  
24  import org.w3c.dom.DOMImplementation;
25  
26  /***
27   * <p>
28   * <code>DOMWriter</code> takes a DOM4J tree and outputs it as a W3C DOM
29   * object
30   * </p>
31   * 
32   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
33   * @version $Revision: 1.17 $
34   */
35  public class DOMWriter {
36      private static boolean loggedWarning = false;
37  
38      private static final String[] DEFAULT_DOM_DOCUMENT_CLASSES = {
39              "org.apache.xerces.dom.DocumentImpl", // Xerces
40              "gnu.xml.dom.DomDocument", // GNU JAXP
41              "org.apache.crimson.tree.XmlDocument", // Crimson
42              "com.sun.xml.tree.XmlDocument", // Sun's Project X
43              "oracle.xml.parser.v2.XMLDocument", // Oracle V2
44              "oracle.xml.parser.XMLDocument", // Oracle V1
45              "org.dom4j.dom.DOMDocument" // Internal DOM implementation
46      };
47  
48      // the Class used to create new DOM Document instances
49      private Class domDocumentClass;
50  
51      /*** stack of <code>Namespace</code> objects */
52      private NamespaceStack namespaceStack = new NamespaceStack();
53  
54      public DOMWriter() {
55      }
56  
57      public DOMWriter(Class domDocumentClass) {
58          this.domDocumentClass = domDocumentClass;
59      }
60  
61      public Class getDomDocumentClass() throws DocumentException {
62          Class result = domDocumentClass;
63  
64          if (result == null) {
65              // lets try and find one in the classpath
66              int size = DEFAULT_DOM_DOCUMENT_CLASSES.length;
67  
68              for (int i = 0; i < size; i++) {
69                  try {
70                      String name = DEFAULT_DOM_DOCUMENT_CLASSES[i];
71                      result = Class.forName(name, true, DOMWriter.class
72                              .getClassLoader());
73  
74                      if (result != null) {
75                          break;
76                      }
77                  } catch (Exception e) {
78                      // could not load class correctly
79                      // lets carry on to the next one
80                  }
81              }
82          }
83  
84          return result;
85      }
86  
87      /***
88       * Sets the DOM {@link org.w3c.dom.Document}implementation class used by
89       * the writer when creating DOM documents.
90       * 
91       * @param domDocumentClass
92       *            is the Class implementing the {@linkorg.w3c.dom.Document}
93       *            interface
94       */
95      public void setDomDocumentClass(Class domDocumentClass) {
96          this.domDocumentClass = domDocumentClass;
97      }
98  
99      /***
100      * Sets the DOM {@link org.w3c.dom.Document}implementation class name used
101      * by the writer when creating DOM documents.
102      * 
103      * @param name
104      *            is the name of the Class implementing the {@link
105      *            org.w3c.dom.Document} interface
106      * 
107      * @throws DocumentException
108      *             if the class could not be loaded
109      */
110     public void setDomDocumentClassName(String name) throws DocumentException {
111         try {
112             this.domDocumentClass = Class.forName(name, true, DOMWriter.class
113                     .getClassLoader());
114         } catch (Exception e) {
115             throw new DocumentException("Could not load the DOM Document "
116                     + "class: " + name, e);
117         }
118     }
119 
120     public org.w3c.dom.Document write(Document document)
121             throws DocumentException {
122         if (document instanceof org.w3c.dom.Document) {
123             return (org.w3c.dom.Document) document;
124         }
125 
126         resetNamespaceStack();
127 
128         org.w3c.dom.Document domDocument = createDomDocument(document);
129         appendDOMTree(domDocument, domDocument, document.content());
130         namespaceStack.clear();
131 
132         return domDocument;
133     }
134 
135     public org.w3c.dom.Document write(Document document,
136             org.w3c.dom.DOMImplementation domImpl) throws DocumentException {
137         if (document instanceof org.w3c.dom.Document) {
138             return (org.w3c.dom.Document) document;
139         }
140 
141         resetNamespaceStack();
142 
143         org.w3c.dom.Document domDocument = createDomDocument(document, domImpl);
144         appendDOMTree(domDocument, domDocument, document.content());
145         namespaceStack.clear();
146 
147         return domDocument;
148     }
149 
150     protected void appendDOMTree(org.w3c.dom.Document domDocument,
151             org.w3c.dom.Node domCurrent, List content) {
152         int size = content.size();
153 
154         for (int i = 0; i < size; i++) {
155             Object object = content.get(i);
156 
157             if (object instanceof Element) {
158                 appendDOMTree(domDocument, domCurrent, (Element) object);
159             } else if (object instanceof String) {
160                 appendDOMTree(domDocument, domCurrent, (String) object);
161             } else if (object instanceof Text) {
162                 Text text = (Text) object;
163                 appendDOMTree(domDocument, domCurrent, text.getText());
164             } else if (object instanceof CDATA) {
165                 appendDOMTree(domDocument, domCurrent, (CDATA) object);
166             } else if (object instanceof Comment) {
167                 appendDOMTree(domDocument, domCurrent, (Comment) object);
168             } else if (object instanceof Entity) {
169                 appendDOMTree(domDocument, domCurrent, (Entity) object);
170             } else if (object instanceof ProcessingInstruction) {
171                 appendDOMTree(domDocument, domCurrent,
172                         (ProcessingInstruction) object);
173             }
174         }
175     }
176 
177     protected void appendDOMTree(org.w3c.dom.Document domDocument,
178             org.w3c.dom.Node domCurrent, Element element) {
179         String elUri = element.getNamespaceURI();
180         String elName = element.getQualifiedName();
181         org.w3c.dom.Element domElement = domDocument.createElementNS(elUri,
182                 elName);
183 
184         int stackSize = namespaceStack.size();
185 
186         // add the namespace of the element first
187         Namespace elementNamespace = element.getNamespace();
188 
189         if (isNamespaceDeclaration(elementNamespace)) {
190             namespaceStack.push(elementNamespace);
191             writeNamespace(domElement, elementNamespace);
192         }
193 
194         // add the additional declared namespaces
195         List declaredNamespaces = element.declaredNamespaces();
196 
197         for (int i = 0, size = declaredNamespaces.size(); i < size; i++) {
198             Namespace namespace = (Namespace) declaredNamespaces.get(i);
199 
200             if (isNamespaceDeclaration(namespace)) {
201                 namespaceStack.push(namespace);
202                 writeNamespace(domElement, namespace);
203             }
204         }
205 
206         // add the attributes
207         for (int i = 0, size = element.attributeCount(); i < size; i++) {
208             Attribute attribute = (Attribute) element.attribute(i);
209             String attUri = attribute.getNamespaceURI();
210             String attName = attribute.getQualifiedName();
211             String value = attribute.getValue();
212             domElement.setAttributeNS(attUri, attName, value);
213         }
214 
215         // add content
216         appendDOMTree(domDocument, domElement, element.content());
217 
218         domCurrent.appendChild(domElement);
219 
220         while (namespaceStack.size() > stackSize) {
221             namespaceStack.pop();
222         }
223     }
224 
225     protected void appendDOMTree(org.w3c.dom.Document domDocument,
226             org.w3c.dom.Node domCurrent, CDATA cdata) {
227         org.w3c.dom.CDATASection domCDATA = domDocument
228                 .createCDATASection(cdata.getText());
229         domCurrent.appendChild(domCDATA);
230     }
231 
232     protected void appendDOMTree(org.w3c.dom.Document domDocument,
233             org.w3c.dom.Node domCurrent, Comment comment) {
234         org.w3c.dom.Comment domComment = domDocument.createComment(comment
235                 .getText());
236         domCurrent.appendChild(domComment);
237     }
238 
239     protected void appendDOMTree(org.w3c.dom.Document domDocument,
240             org.w3c.dom.Node domCurrent, String text) {
241         org.w3c.dom.Text domText = domDocument.createTextNode(text);
242         domCurrent.appendChild(domText);
243     }
244 
245     protected void appendDOMTree(org.w3c.dom.Document domDocument,
246             org.w3c.dom.Node domCurrent, Entity entity) {
247         org.w3c.dom.EntityReference domEntity = domDocument
248                 .createEntityReference(entity.getName());
249         domCurrent.appendChild(domEntity);
250     }
251 
252     protected void appendDOMTree(org.w3c.dom.Document domDoc,
253             org.w3c.dom.Node domCurrent, ProcessingInstruction pi) {
254         org.w3c.dom.ProcessingInstruction domPI = domDoc
255                 .createProcessingInstruction(pi.getTarget(), pi.getText());
256         domCurrent.appendChild(domPI);
257     }
258 
259     protected void writeNamespace(org.w3c.dom.Element domElement,
260             Namespace namespace) {
261         String attributeName = attributeNameForNamespace(namespace);
262 
263         // domElement.setAttributeNS("", attributeName, namespace.getURI());
264         domElement.setAttribute(attributeName, namespace.getURI());
265     }
266 
267     protected String attributeNameForNamespace(Namespace namespace) {
268         String xmlns = "xmlns";
269         String prefix = namespace.getPrefix();
270 
271         if (prefix.length() > 0) {
272             return xmlns + ":" + prefix;
273         }
274 
275         return xmlns;
276     }
277 
278     protected org.w3c.dom.Document createDomDocument(Document document)
279             throws DocumentException {
280         org.w3c.dom.Document result = null;
281 
282         // use the given domDocumentClass (if not null)
283         if (domDocumentClass != null) {
284             try {
285                 result = (org.w3c.dom.Document) domDocumentClass.newInstance();
286             } catch (Exception e) {
287                 throw new DocumentException(
288                         "Could not instantiate an instance "
289                                 + "of DOM Document with class: "
290                                 + domDocumentClass.getName(), e);
291             }
292         } else {
293             // lets try JAXP first before using the hardcoded default parsers
294             result = createDomDocumentViaJAXP();
295 
296             if (result == null) {
297                 Class theClass = getDomDocumentClass();
298 
299                 try {
300                     result = (org.w3c.dom.Document) theClass.newInstance();
301                 } catch (Exception e) {
302                     throw new DocumentException("Could not instantiate an "
303                             + "instance of DOM Document " + "with class: "
304                             + theClass.getName(), e);
305                 }
306             }
307         }
308 
309         return result;
310     }
311 
312     protected org.w3c.dom.Document createDomDocumentViaJAXP()
313             throws DocumentException {
314         try {
315             return JAXPHelper.createDocument(false, true);
316         } catch (Throwable e) {
317             if (!loggedWarning) {
318                 loggedWarning = true;
319 
320                 if (SAXHelper.isVerboseErrorReporting()) {
321                     // log all exceptions as warnings and carry
322                     // on as we have a default SAX parser we can use
323                     System.out.println("Warning: Caught exception attempting "
324                             + "to use JAXP to create a W3C DOM " + "document");
325                     System.out.println("Warning: Exception was: " + e);
326                     e.printStackTrace();
327                 } else {
328                     System.out.println("Warning: Error occurred using JAXP to "
329                             + "create a DOM document.");
330                 }
331             }
332         }
333 
334         return null;
335     }
336 
337     protected org.w3c.dom.Document createDomDocument(Document document,
338             DOMImplementation domImpl) throws DocumentException {
339         String namespaceURI = null;
340         String qualifiedName = null;
341         org.w3c.dom.DocumentType docType = null;
342 
343         return domImpl.createDocument(namespaceURI, qualifiedName, docType);
344     }
345 
346     protected boolean isNamespaceDeclaration(Namespace ns) {
347         if ((ns != null) && (ns != Namespace.NO_NAMESPACE)
348                 && (ns != Namespace.XML_NAMESPACE)) {
349             String uri = ns.getURI();
350 
351             if ((uri != null) && (uri.length() > 0)) {
352                 if (!namespaceStack.contains(ns)) {
353                     return true;
354                 }
355             }
356         }
357 
358         return false;
359     }
360 
361     protected void resetNamespaceStack() {
362         namespaceStack.clear();
363         namespaceStack.push(Namespace.XML_NAMESPACE);
364     }
365 }
366 
367 /*
368  * Redistribution and use of this software and associated documentation
369  * ("Software"), with or without modification, are permitted provided that the
370  * following conditions are met:
371  * 
372  * 1. Redistributions of source code must retain copyright statements and
373  * notices. Redistributions must also contain a copy of this document.
374  * 
375  * 2. Redistributions in binary form must reproduce the above copyright notice,
376  * this list of conditions and the following disclaimer in the documentation
377  * and/or other materials provided with the distribution.
378  * 
379  * 3. The name "DOM4J" must not be used to endorse or promote products derived
380  * from this Software without prior written permission of MetaStuff, Ltd. For
381  * written permission, please contact dom4j-info@metastuff.com.
382  * 
383  * 4. Products derived from this Software may not be called "DOM4J" nor may
384  * "DOM4J" appear in their names without prior written permission of MetaStuff,
385  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
386  * 
387  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
388  * 
389  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
390  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
391  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
392  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
393  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
394  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
395  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
396  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
397  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
398  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
399  * POSSIBILITY OF SUCH DAMAGE.
400  * 
401  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
402  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/Document.html0000644000175000017500000003761010242117631020234 0ustar ebourgebourg Document xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import java.util.Map;
11  
12  import org.xml.sax.EntityResolver;
13  
14  /***
15   * <p>
16   * <code>Document</code> defines an XML Document.
17   * </p>
18   * 
19   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
20   * @version $Revision: 1.14 $
21   */
22  public interface Document extends Branch {
23      /***
24       * Returns the root {@link Element}for this document.
25       * 
26       * @return the root element for this document
27       */
28      Element getRootElement();
29  
30      /***
31       * Sets the root element for this document
32       * 
33       * @param rootElement
34       *            the new root element for this document
35       */
36      void setRootElement(Element rootElement);
37  
38      /***
39       * Adds a new <code>Comment</code> node with the given text to this
40       * branch.
41       * 
42       * @param comment
43       *            is the text for the <code>Comment</code> node.
44       * 
45       * @return this <code>Document</code> instance.
46       */
47      Document addComment(String comment);
48  
49      /***
50       * Adds a processing instruction for the given target
51       * 
52       * @param target
53       *            is the target of the processing instruction
54       * @param text
55       *            is the textual data (key/value pairs) of the processing
56       *            instruction
57       * 
58       * @return this <code>Document</code> instance.
59       */
60      Document addProcessingInstruction(String target, String text);
61  
62      /***
63       * Adds a processing instruction for the given target
64       * 
65       * @param target
66       *            is the target of the processing instruction
67       * @param data
68       *            is a Map of the key / value pairs of the processing
69       *            instruction
70       * 
71       * @return this <code>Document</code> instance.
72       */
73      Document addProcessingInstruction(String target, Map data);
74  
75      /***
76       * Adds a DOCTYPE declaration to this document
77       * 
78       * @param name
79       *            is the name of the root element
80       * @param publicId
81       *            is the PUBLIC URI
82       * @param systemId
83       *            is the SYSTEM URI
84       * 
85       * @return this <code>Document</code> instance.
86       */
87      Document addDocType(String name, String publicId, String systemId);
88  
89      /***
90       * DOCUMENT ME!
91       * 
92       * @return the DocumentType property
93       */
94      DocumentType getDocType();
95  
96      /***
97       * Sets the DocumentType property
98       * 
99       * @param docType
100      *            DOCUMENT ME!
101      */
102     void setDocType(DocumentType docType);
103 
104     /***
105      * DOCUMENT ME!
106      * 
107      * @return the EntityResolver used to find resolve URIs such as for DTDs, or
108      *         XML Schema documents
109      */
110     EntityResolver getEntityResolver();
111 
112     /***
113      * Sets the EntityResolver used to find resolve URIs such as for DTDs, or
114      * XML Schema documents
115      * 
116      * @param entityResolver
117      *            DOCUMENT ME!
118      */
119     void setEntityResolver(EntityResolver entityResolver);
120 
121     /***
122      * Return the encoding of this document, as part of the XML declaration This
123      * is <code>null</code> when unspecified or when it is not known (such as
124      * when the Document was created in memory) or when the implementation does
125      * not support this operation.
126      * 
127      * <p>
128      * The way this encoding is retrieved also depends on the way the XML source
129      * is parsed. For instance, if the SAXReader is used and if the underlying
130      * XMLReader implementation support the
131      * <code>org.xml.sax.ext.Locator2</code> interface, the result returned by
132      * this method is specified by the <code>getEncoding()</code> method of
133      * that interface.
134      * </p>
135      * 
136      * @return The encoding of this document, as stated in the XML declaration,
137      *         or <code>null</code> if unknown.
138      * 
139      * @since 1.5
140      */
141     String getXMLEncoding();
142 
143     /***
144      * Sets the encoding of this document as it will appear in the XML
145      * declaration part of the document.
146      * 
147      * @param encoding the encoding of the document
148      * 
149      * @since 1.6
150      */
151     void setXMLEncoding(String encoding);
152 }
153 
154 /*
155  * Redistribution and use of this software and associated documentation
156  * ("Software"), with or without modification, are permitted provided that the
157  * following conditions are met:
158  * 
159  * 1. Redistributions of source code must retain copyright statements and
160  * notices. Redistributions must also contain a copy of this document.
161  * 
162  * 2. Redistributions in binary form must reproduce the above copyright notice,
163  * this list of conditions and the following disclaimer in the documentation
164  * and/or other materials provided with the distribution.
165  * 
166  * 3. The name "DOM4J" must not be used to endorse or promote products derived
167  * from this Software without prior written permission of MetaStuff, Ltd. For
168  * written permission, please contact dom4j-info@metastuff.com.
169  * 
170  * 4. Products derived from this Software may not be called "DOM4J" nor may
171  * "DOM4J" appear in their names without prior written permission of MetaStuff,
172  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
173  * 
174  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
175  * 
176  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
177  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
178  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
179  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
180  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
181  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
182  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
183  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
184  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
185  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
186  * POSSIBILITY OF SUCH DAMAGE.
187  * 
188  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
189  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/CDATA.html0000644000175000017500000001422410242117740017267 0ustar ebourgebourg CDATA xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  /***
11   * <p>
12   * <code>CDATA</code> defines an XML CDATA section.
13   * </p>
14   * 
15   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
16   * @version $Revision: 1.7 $
17   */
18  public interface CDATA extends CharacterData {
19  }
20  
21  /*
22   * Redistribution and use of this software and associated documentation
23   * ("Software"), with or without modification, are permitted provided that the
24   * following conditions are met:
25   * 
26   * 1. Redistributions of source code must retain copyright statements and
27   * notices. Redistributions must also contain a copy of this document.
28   * 
29   * 2. Redistributions in binary form must reproduce the above copyright notice,
30   * this list of conditions and the following disclaimer in the documentation
31   * and/or other materials provided with the distribution.
32   * 
33   * 3. The name "DOM4J" must not be used to endorse or promote products derived
34   * from this Software without prior written permission of MetaStuff, Ltd. For
35   * written permission, please contact dom4j-info@metastuff.com.
36   * 
37   * 4. Products derived from this Software may not be called "DOM4J" nor may
38   * "DOM4J" appear in their names without prior written permission of MetaStuff,
39   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
40   * 
41   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
42   * 
43   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
44   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
47   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
48   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
49   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
50   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
51   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
52   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
53   * POSSIBILITY OF SUCH DAMAGE.
54   * 
55   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
56   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/Element.html0000644000175000017500000021273310242117730020050 0ustar ebourgebourg Element xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import java.util.Iterator;
11  import java.util.List;
12  import java.util.Map;
13  
14  /***
15   * <p>
16   * <code>Element</code> interface defines an XML element. An element can have
17   * declared namespaces, attributes, child nodes and textual content.
18   * </p>
19   * 
20   * <p>
21   * Some of this interface is optional. Some implementations may be read-only and
22   * not support being modified. Some implementations may not support the parent
23   * relationship and methods such as {@link #getParent}or {@link#getDocument}.
24   * </p>
25   * 
26   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
27   * @version $Revision: 1.47 $
28   */
29  public interface Element extends Branch {
30      // Name and namespace related methods
31      // -------------------------------------------------------------------------
32  
33      /***
34       * <p>
35       * Returns the <code>QName</code> of this element which represents the
36       * local name, the qualified name and the <code>Namespace</code>.
37       * </p>
38       * 
39       * @return the <code>QName</code> associated with this element
40       */
41      QName getQName();
42  
43      /***
44       * <p>
45       * Sets the <code>QName</code> of this element which represents the local
46       * name, the qualified name and the <code>Namespace</code>.
47       * </p>
48       * 
49       * @param qname
50       *            is the <code>QName</code> to be associated with this element
51       */
52      void setQName(QName qname);
53  
54      /***
55       * <p>
56       * Returns the <code>Namespace</code> of this element if one exists
57       * otherwise <code>Namespace.NO_NAMESPACE</code> is returned.
58       * </p>
59       * 
60       * @return the <code>Namespace</code> associated with this element
61       */
62      Namespace getNamespace();
63  
64      /***
65       * <p>
66       * Returns the <code>QName</code> for the given qualified name, using the
67       * namespace URI in scope for the given prefix of the qualified name or the
68       * default namespace if the qualified name has no prefix.
69       * </p>
70       * 
71       * @param qualifiedName
72       *            DOCUMENT ME!
73       * 
74       * @return the <code>QName</code> for the given qualified name
75       */
76      QName getQName(String qualifiedName);
77  
78      /***
79       * <p>
80       * Returns the <code>Namespace</code> which is mapped to the given prefix
81       * or null if it could not be found.
82       * </p>
83       * 
84       * @param prefix
85       *            DOCUMENT ME!
86       * 
87       * @return the <code>Namespace</code> associated with the given prefix
88       */
89      Namespace getNamespaceForPrefix(String prefix);
90  
91      /***
92       * <p>
93       * Returns the <code>Namespace</code> which is mapped to the given URI or
94       * null if it could not be found. If there is more than one
95       * <code>Namespace</code> mapped to the URI, which of them will be
96       * returned is undetermined.
97       * </p>
98       * 
99       * @param uri
100      *            DOCUMENT ME!
101      * 
102      * @return the <code>Namespace</code> associated with the given URI
103      */
104     Namespace getNamespaceForURI(String uri);
105 
106     /***
107      * <p>
108      * Returns the all namespaces which are mapped to the given URI or an empty
109      * list if no such namespaces could be found.
110      * </p>
111      * 
112      * @param uri
113      *            DOCUMENT ME!
114      * 
115      * @return the namespaces associated with the given URI
116      * 
117      * @since 1.5
118      */
119     List getNamespacesForURI(String uri);
120 
121     /***
122      * <p>
123      * Returns the namespace prefix of this element if one exists otherwise an
124      * empty <code>String</code> is returned.
125      * </p>
126      * 
127      * @return the prefix of the <code>Namespace</code> of this element or an
128      *         empty <code>String</code>
129      */
130     String getNamespacePrefix();
131 
132     /***
133      * <p>
134      * Returns the URI mapped to the namespace of this element if one exists
135      * otherwise an empty <code>String</code> is returned.
136      * </p>
137      * 
138      * @return the URI for the <code>Namespace</code> of this element or an
139      *         empty <code>String</code>
140      */
141     String getNamespaceURI();
142 
143     /***
144      * <p>
145      * Returns the fully qualified name of this element. This will be the same
146      * as the value returned from {@link #getName}if this element has no
147      * namespace attached to this element or an expression of the form
148      * 
149      * <pre>
150      * getNamespacePrefix() + &quot;:&quot; + getName()
151      * </pre>
152      * 
153      * will be returned.
154      * </p>
155      * 
156      * @return the fully qualified name of the element.
157      */
158     String getQualifiedName();
159 
160     /***
161      * <p>
162      * Returns any additional namespaces declarations for this element other
163      * than namespace returned via the {@link #getNamespace()}method. If no
164      * additional namespace declarations are present for this element then an
165      * empty list will be returned. The list is backed by the element such that
166      * changes to the list will be reflected in the element though the reverse
167      * is not the case.
168      * </p>
169      * 
170      * @return a list of any additional namespace declarations.
171      */
172     List additionalNamespaces();
173 
174     /***
175      * <p>
176      * Returns all the namespaces declared by this element. If no namespaces are
177      * declared for this element then an empty list will be returned. The list
178      * is backed by the element such that changes to the list will be reflected
179      * in the element though the reverse is not the case.
180      * </p>
181      * 
182      * @return a list of namespaces declared for this element.
183      */
184     List declaredNamespaces();
185 
186     // Builder methods
187     // -------------------------------------------------------------------------
188 
189     /***
190      * <p>
191      * Adds the attribute value of the given local name. If an attribute already
192      * exists for the given name it will be replaced. Attributes with null
193      * values are silently ignored. If the value of the attribute is null then
194      * this method call will remove any attributes with the given name.
195      * </p>
196      * 
197      * @param name
198      *            is the name of the attribute whose value is to be added or
199      *            updated
200      * @param value
201      *            is the attribute's value
202      * 
203      * @return this <code>Element</code> instance.
204      */
205     Element addAttribute(String name, String value);
206 
207     /***
208      * <p>
209      * Adds the attribute value of the given fully qualified name. If an
210      * attribute already exists for the given name it will be replaced.
211      * Attributes with null values are silently ignored. If the value of the
212      * attribute is null then this method call will remove any attributes with
213      * the given name.
214      * </p>
215      * 
216      * @param qName
217      *            is the fully qualified name of the attribute whose value is to
218      *            be added or updated
219      * @param value
220      *            is the attribute's value
221      * 
222      * @return this <code>Element</code> instance.
223      */
224     Element addAttribute(QName qName, String value);
225 
226     /***
227      * Adds a new <code>Comment</code> node with the given text to this
228      * element.
229      * 
230      * @param comment
231      *            is the text for the <code>Comment</code> node.
232      * 
233      * @return this <code>Element</code> instance.
234      */
235     Element addComment(String comment);
236 
237     /***
238      * Adds a new <code>CDATA</code> node with the given text to this element.
239      * 
240      * @param cdata
241      *            is the text for the <code>CDATA</code> node.
242      * 
243      * @return this <code>Element</code> instance.
244      */
245     Element addCDATA(String cdata);
246 
247     /***
248      * Adds a new <code>Entity</code> node with the given name and text to
249      * this element and returns a reference to the new node.
250      * 
251      * @param name
252      *            is the name for the <code>Entity</code> node.
253      * @param text
254      *            is the text for the <code>Entity</code> node.
255      * 
256      * @return this <code>Element</code> instance.
257      */
258     Element addEntity(String name, String text);
259 
260     /***
261      * Adds a namespace to this element for use by its child content
262      * 
263      * @param prefix
264      *            is the prefix to use, which should not be null or blank
265      * @param uri
266      *            is the namespace URI
267      * 
268      * @return this <code>Element</code> instance.
269      */
270     Element addNamespace(String prefix, String uri);
271 
272     /***
273      * Adds a processing instruction for the given target
274      * 
275      * @param target
276      *            is the target of the processing instruction
277      * @param text
278      *            is the textual data (key/value pairs) of the processing
279      *            instruction
280      * 
281      * @return this <code>Element</code> instance.
282      */
283     Element addProcessingInstruction(String target, String text);
284 
285     /***
286      * Adds a processing instruction for the given target
287      * 
288      * @param target
289      *            is the target of the processing instruction
290      * @param data
291      *            is a Map of the key / value pairs of the processing
292      *            instruction
293      * 
294      * @return this <code>Element</code> instance.
295      */
296     Element addProcessingInstruction(String target, Map data);
297 
298     /***
299      * Adds a new <code>Text</code> node with the given text to this element.
300      * 
301      * @param text
302      *            is the text for the <code>Text</code> node.
303      * 
304      * @return this <code>Element</code> instance.
305      */
306     Element addText(String text);
307 
308     // Typesafe modifying methods
309     // -------------------------------------------------------------------------
310 
311     /***
312      * Adds the given <code>Attribute</code> to this element. If the given
313      * node already has a parent defined then an
314      * <code>IllegalAddException</code> will be thrown. Attributes with null
315      * values are silently ignored.
316      * 
317      * <p>
318      * If the value of the attribute is null then this method call will remove
319      * any attributes with the QName of this attribute.
320      * </p>
321      * 
322      * @param attribute
323      *            is the attribute to be added
324      */
325     void add(Attribute attribute);
326 
327     /***
328      * Adds the given <code>CDATA</code> to this element. If the given node
329      * already has a parent defined then an <code>IllegalAddException</code>
330      * will be thrown.
331      * 
332      * @param cdata
333      *            is the CDATA to be added
334      */
335     void add(CDATA cdata);
336 
337     /***
338      * Adds the given <code>Entity</code> to this element. If the given node
339      * already has a parent defined then an <code>IllegalAddException</code>
340      * will be thrown.
341      * 
342      * @param entity
343      *            is the entity to be added
344      */
345     void add(Entity entity);
346 
347     /***
348      * Adds the given <code>Text</code> to this element. If the given node
349      * already has a parent defined then an <code>IllegalAddException</code>
350      * will be thrown.
351      * 
352      * @param text
353      *            is the text to be added
354      */
355     void add(Text text);
356 
357     /***
358      * Adds the given <code>Namespace</code> to this element. If the given
359      * node already has a parent defined then an
360      * <code>IllegalAddException</code> will be thrown.
361      * 
362      * @param namespace
363      *            is the namespace to be added
364      */
365     void add(Namespace namespace);
366 
367     /***
368      * Removes the given <code>Attribute</code> from this element.
369      * 
370      * @param attribute
371      *            is the attribute to be removed
372      * 
373      * @return true if the attribute was removed
374      */
375     boolean remove(Attribute attribute);
376 
377     /***
378      * Removes the given <code>CDATA</code> if the node is an immediate child
379      * of this element. If the given node is not an immediate child of this
380      * element then the {@link Node#detach()}method should be used instead.
381      * 
382      * @param cdata
383      *            is the CDATA to be removed
384      * 
385      * @return true if the cdata was removed
386      */
387     boolean remove(CDATA cdata);
388 
389     /***
390      * Removes the given <code>Entity</code> if the node is an immediate child
391      * of this element. If the given node is not an immediate child of this
392      * element then the {@link Node#detach()}method should be used instead.
393      * 
394      * @param entity
395      *            is the entity to be removed
396      * 
397      * @return true if the entity was removed
398      */
399     boolean remove(Entity entity);
400 
401     /***
402      * Removes the given <code>Namespace</code> if the node is an immediate
403      * child of this element. If the given node is not an immediate child of
404      * this element then the {@link Node#detach()}method should be used
405      * instead.
406      * 
407      * @param namespace
408      *            is the namespace to be removed
409      * 
410      * @return true if the namespace was removed
411      */
412     boolean remove(Namespace namespace);
413 
414     /***
415      * Removes the given <code>Text</code> if the node is an immediate child
416      * of this element. If the given node is not an immediate child of this
417      * element then the {@link Node#detach()}method should be used instead.
418      * 
419      * @param text
420      *            is the text to be removed
421      * 
422      * @return true if the text was removed
423      */
424     boolean remove(Text text);
425 
426     // Text methods
427     // -------------------------------------------------------------------------
428 
429     /***
430      * Returns the text value of this element without recursing through child
431      * elements. This method iterates through all {@link Text},{@link CDATA}
432      * and {@link Entity}nodes that this element contains and appends the text
433      * values together.
434      * 
435      * @return the textual content of this Element. Child elements are not
436      *         navigated. This method does not return null;
437      */
438     String getText();
439 
440     /***
441      * DOCUMENT ME!
442      * 
443      * @return the trimmed text value where whitespace is trimmed and normalised
444      *         into single spaces. This method does not return null.
445      */
446     String getTextTrim();
447 
448     /***
449      * Returns the XPath string-value of this node. The behaviour of this method
450      * is defined in the <a href="http://www.w3.org/TR/xpath">XPath
451      * specification </a>. This method returns the string-value of all the
452      * contained {@link Text},{@link CDATA},{@link Entity}and {@link
453      * Element} nodes all appended together.
454      * 
455      * @return the text from all the child Text and Element nodes appended
456      *         together.
457      */
458     String getStringValue();
459 
460     /***
461      * Accesses the data of this element which may implement data typing
462      * bindings such as XML Schema or Java Bean bindings or will return the same
463      * value as {@link #getText}
464      * 
465      * @return DOCUMENT ME!
466      */
467     Object getData();
468 
469     /***
470      * Sets the data value of this element if this element supports data binding
471      * or calls {@link #setText}if it doesn't
472      * 
473      * @param data
474      *            DOCUMENT ME!
475      */
476     void setData(Object data);
477 
478     // Attribute methods
479     // -------------------------------------------------------------------------
480 
481     /***
482      * <p>
483      * Returns the {@link Attribute}instances this element contains as a backed
484      * {@link List}so that the attributes may be modified directly using the
485      * {@link List}interface. The <code>List</code> is backed by the
486      * <code>Element</code> so that changes to the list are reflected in the
487      * element and vice versa.
488      * </p>
489      * 
490      * @return the attributes that this element contains as a <code>List</code>
491      */
492     List attributes();
493 
494     /***
495      * Sets the attributes that this element contains
496      * 
497      * @param attributes
498      *            DOCUMENT ME!
499      */
500     void setAttributes(List attributes);
501 
502     /***
503      * DOCUMENT ME!
504      * 
505      * @return the number of attributes this element contains
506      */
507     int attributeCount();
508 
509     /***
510      * DOCUMENT ME!
511      * 
512      * @return an iterator over the attributes of this element
513      */
514     Iterator attributeIterator();
515 
516     /***
517      * Returns the attribute at the specified indexGets the
518      * 
519      * @param index
520      *            DOCUMENT ME!
521      * 
522      * @return the attribute at the specified index where index &gt;= 0 and
523      *         index &lt; number of attributes or throws an
524      *         IndexOutOfBoundsException if the index is not within the
525      *         allowable range
526      */
527     Attribute attribute(int index);
528 
529     /***
530      * Returns the attribute with the given name
531      * 
532      * @param name
533      *            DOCUMENT ME!
534      * 
535      * @return the attribute for the given local name in any namespace. If there
536      *         are more than one attributes with the given local name in
537      *         different namespaces then the first one is returned.
538      */
539     Attribute attribute(String name);
540 
541     /***
542      * DOCUMENT ME!
543      * 
544      * @param qName
545      *            is the fully qualified name
546      * 
547      * @return the attribute for the given fully qualified name or null if it
548      *         could not be found.
549      */
550     Attribute attribute(QName qName);
551 
552     /***
553      * <p>
554      * This returns the attribute value for the attribute with the given name
555      * and any namespace or null if there is no such attribute or the empty
556      * string if the attribute value is empty.
557      * </p>
558      * 
559      * @param name
560      *            is the name of the attribute value to be returnd
561      * 
562      * @return the value of the attribute, null if the attribute does not exist
563      *         or the empty string
564      */
565     String attributeValue(String name);
566 
567     /***
568      * <p>
569      * This returns the attribute value for the attribute with the given name
570      * and any namespace or the default value if there is no such attribute
571      * value.
572      * </p>
573      * 
574      * @param name
575      *            is the name of the attribute value to be returnd
576      * @param defaultValue
577      *            is the default value to be returned if the attribute has no
578      *            value defined.
579      * 
580      * @return the value of the attribute or the defaultValue if the attribute
581      *         has no value defined.
582      */
583     String attributeValue(String name, String defaultValue);
584 
585     /***
586      * <p>
587      * This returns the attribute value for the attribute with the given fully
588      * qualified name or null if there is no such attribute or the empty string
589      * if the attribute value is empty.
590      * </p>
591      * 
592      * @param qName
593      *            is the fully qualified name
594      * 
595      * @return the value of the attribute, null if the attribute does not exist
596      *         or the empty string
597      */
598     String attributeValue(QName qName);
599 
600     /***
601      * <p>
602      * This returns the attribute value for the attribute with the given fully
603      * qualified name or the default value if there is no such attribute value.
604      * </p>
605      * 
606      * @param qName
607      *            is the fully qualified name
608      * @param defaultValue
609      *            is the default value to be returned if the attribute has no
610      *            value defined.
611      * 
612      * @return the value of the attribute or the defaultValue if the attribute
613      *         has no value defined.
614      */
615     String attributeValue(QName qName, String defaultValue);
616 
617     /***
618      * <p>
619      * Sets the attribute value of the given local name.
620      * </p>
621      * 
622      * @param name
623      *            is the name of the attribute whose value is to be added or
624      *            updated
625      * @param value
626      *            is the attribute's value
627      * 
628      * @deprecated As of version 0.5. Please use {@link
629      *             #addAttribute(String,String)} instead. WILL BE REMOVED IN
630      *             dom4j-1.6 !!
631      */
632     void setAttributeValue(String name, String value);
633 
634     /***
635      * <p>
636      * Sets the attribute value of the given fully qualified name.
637      * </p>
638      * 
639      * @param qName
640      *            is the fully qualified name of the attribute whose value is to
641      *            be added or updated
642      * @param value
643      *            is the attribute's value
644      * 
645      * @deprecated As of version 0.5. Please use {@link
646      *             #addAttribute(QName,String)} instead. WILL BE REMOVED IN
647      *             dom4j-1.6 !!
648      */
649     void setAttributeValue(QName qName, String value);
650 
651     // Content methods
652     // -------------------------------------------------------------------------
653 
654     /***
655      * Returns the first element for the given local name and any namespace.
656      * 
657      * @param name
658      *            DOCUMENT ME!
659      * 
660      * @return the first element with the given local name
661      */
662     Element element(String name);
663 
664     /***
665      * Returns the first element for the given fully qualified name.
666      * 
667      * @param qName
668      *            is the fully qualified name to search for
669      * 
670      * @return the first element with the given fully qualified name
671      */
672     Element element(QName qName);
673 
674     /***
675      * <p>
676      * Returns the elements contained in this element. If this element does not
677      * contain any elements then this method returns an empty list. The list is
678      * backed by the element such that changes to the list will be reflected in
679      * the element though the reverse is not the case.
680      * </p>
681      * 
682      * @return a list of all the elements in this element.
683      */
684     List elements();
685 
686     /***
687      * <p>
688      * Returns the elements contained in this element with the given local name
689      * and any namespace. If no elements are found then this method returns an
690      * empty list. The list is backed by the element such that changes to the
691      * list will be reflected in the element though the reverse is not the case.
692      * </p>
693      * 
694      * @param name
695      *            DOCUMENT ME!
696      * 
697      * @return a list of all the elements in this element for the given local
698      *         name
699      */
700     List elements(String name);
701 
702     /***
703      * <p>
704      * Returns the elements contained in this element with the given fully
705      * qualified name. If no elements are found then this method returns an
706      * empty list. The list is backed by the element such that changes to the
707      * list will be reflected in the element though the reverse is not the case.
708      * </p>
709      * 
710      * @param qName
711      *            is the fully qualified name to search for
712      * 
713      * @return a list of all the elements in this element for the given fully
714      *         qualified name.
715      */
716     List elements(QName qName);
717 
718     /***
719      * Returns an iterator over all this elements child elements.
720      * 
721      * @return an iterator over the contained elements
722      */
723     Iterator elementIterator();
724 
725     /***
726      * Returns an iterator over the elements contained in this element which
727      * match the given local name and any namespace.
728      * 
729      * @param name
730      *            DOCUMENT ME!
731      * 
732      * @return an iterator over the contained elements matching the given local
733      *         name
734      */
735     Iterator elementIterator(String name);
736 
737     /***
738      * Returns an iterator over the elements contained in this element which
739      * match the given fully qualified name.
740      * 
741      * @param qName
742      *            is the fully qualified name to search for
743      * 
744      * @return an iterator over the contained elements matching the given fully
745      *         qualified name
746      */
747     Iterator elementIterator(QName qName);
748 
749     // Helper methods
750     // -------------------------------------------------------------------------
751 
752     /***
753      * DOCUMENT ME!
754      * 
755      * @return true if this element is the root element of a document and this
756      *         element supports the parent relationship else false.
757      */
758     boolean isRootElement();
759 
760     /***
761      * <p>
762      * Returns true if this <code>Element</code> has mixed content. Mixed
763      * content means that an element contains both textual data and child
764      * elements.
765      * </p>
766      * 
767      * @return true if this element contains mixed content.
768      */
769     boolean hasMixedContent();
770 
771     /***
772      * <p>
773      * Returns true if this <code>Element</code> has text only content.
774      * </p>
775      * 
776      * @return true if this element is empty or only contains text content.
777      */
778     boolean isTextOnly();
779 
780     /***
781      * Appends the attributes of the given element to me. This method behaves
782      * like the {@link java.util.Collection#addAll(java.util.Collection)}
783      * method.
784      * 
785      * @param element
786      *            is the element whose attributes will be added to me.
787      */
788     void appendAttributes(Element element);
789 
790     /***
791      * <p>
792      * Creates a deep copy of this element The new element is detached from its
793      * parent, and getParent() on the clone will return null.
794      * </p>
795      * 
796      * @return a new deep copy Element
797      */
798     Element createCopy();
799 
800     /***
801      * <p>
802      * Creates a deep copy of this element with the given local name The new
803      * element is detached from its parent, and getParent() on the clone will
804      * return null.
805      * </p>
806      * 
807      * @param name
808      *            DOCUMENT ME!
809      * 
810      * @return a new deep copy Element
811      */
812     Element createCopy(String name);
813 
814     /***
815      * <p>
816      * Creates a deep copy of this element with the given fully qualified name.
817      * The new element is detached from its parent, and getParent() on the clone
818      * will return null.
819      * </p>
820      * 
821      * @param qName
822      *            DOCUMENT ME!
823      * 
824      * @return a new deep copy Element
825      */
826     Element createCopy(QName qName);
827 
828     String elementText(String name);
829 
830     String elementText(QName qname);
831 
832     String elementTextTrim(String name);
833 
834     String elementTextTrim(QName qname);
835 
836     /***
837      * Returns a node at the given index suitable for an XPath result set. This
838      * means the resulting Node will either be null or it will support the
839      * parent relationship.
840      * 
841      * @param index
842      *            DOCUMENT ME!
843      * 
844      * @return the Node for the given index which will support the parent
845      *         relationship or null if there is not a node at the given index.
846      */
847     Node getXPathResult(int index);
848 }
849 
850 /*
851  * Redistribution and use of this software and associated documentation
852  * ("Software"), with or without modification, are permitted provided that the
853  * following conditions are met:
854  * 
855  * 1. Redistributions of source code must retain copyright statements and
856  * notices. Redistributions must also contain a copy of this document.
857  * 
858  * 2. Redistributions in binary form must reproduce the above copyright notice,
859  * this list of conditions and the following disclaimer in the documentation
860  * and/or other materials provided with the distribution.
861  * 
862  * 3. The name "DOM4J" must not be used to endorse or promote products derived
863  * from this Software without prior written permission of MetaStuff, Ltd. For
864  * written permission, please contact dom4j-info@metastuff.com.
865  * 
866  * 4. Products derived from this Software may not be called "DOM4J" nor may
867  * "DOM4J" appear in their names without prior written permission of MetaStuff,
868  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
869  * 
870  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
871  * 
872  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
873  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
874  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
875  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
876  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
877  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
878  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
879  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
880  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
881  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
882  * POSSIBILITY OF SUCH DAMAGE.
883  * 
884  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
885  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/DocumentFactory.html0000644000175000017500000011613510242117554021570 0ustar ebourgebourg DocumentFactory xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import java.io.IOException;
11  import java.io.ObjectInputStream;
12  import java.io.Serializable;
13  import java.util.List;
14  import java.util.Map;
15  
16  import org.dom4j.rule.Pattern;
17  import org.dom4j.tree.AbstractDocument;
18  import org.dom4j.tree.DefaultAttribute;
19  import org.dom4j.tree.DefaultCDATA;
20  import org.dom4j.tree.DefaultComment;
21  import org.dom4j.tree.DefaultDocument;
22  import org.dom4j.tree.DefaultDocumentType;
23  import org.dom4j.tree.DefaultElement;
24  import org.dom4j.tree.DefaultEntity;
25  import org.dom4j.tree.DefaultProcessingInstruction;
26  import org.dom4j.tree.DefaultText;
27  import org.dom4j.tree.QNameCache;
28  import org.dom4j.util.SimpleSingleton;
29  import org.dom4j.util.SingletonStrategy;
30  import org.dom4j.xpath.DefaultXPath;
31  import org.dom4j.xpath.XPathPattern;
32  import org.jaxen.VariableContext;
33  
34  /***
35   * <p>
36   * <code>DocumentFactory</code> is a collection of factory methods to allow
37   * easy custom building of DOM4J trees. The default tree that is built uses a
38   * doubly linked tree.
39   * </p>
40   * 
41   * <p>
42   * The tree built allows full XPath expressions from anywhere on the tree.
43   * </p>
44   * 
45   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
46   */
47  public class DocumentFactory implements Serializable {
48      private static SingletonStrategy singleton = null;
49  
50      protected transient QNameCache cache;
51  
52      /*** Default namespace prefix -> URI mappings for XPath expressions to use */
53      private Map xpathNamespaceURIs;
54  
55      private static SingletonStrategy createSingleton() {
56          SingletonStrategy result = null;
57          
58          String documentFactoryClassName;
59          try {
60              documentFactoryClassName = System.getProperty("org.dom4j.factory",
61                      "org.dom4j.DocumentFactory");
62          } catch (Exception e) {
63              documentFactoryClassName = "org.dom4j.DocumentFactory";
64          }
65  
66          try {
67              String singletonClass = System.getProperty(
68                      "org.dom4j.DocumentFactory.singleton.strategy",
69                      "org.dom4j.util.SimpleSingleton");
70              Class clazz = Class.forName(singletonClass);
71              result = (SingletonStrategy) clazz.newInstance();
72          } catch (Exception e) {
73              result = new SimpleSingleton();
74          }
75  
76          result.setSingletonClassName(documentFactoryClassName);
77          
78          return result;
79      }
80  
81      public DocumentFactory() {
82          init();
83      }
84  
85      /***
86       * <p>
87       * Access to singleton implementation of DocumentFactory which is used if no
88       * DocumentFactory is specified when building using the standard builders.
89       * </p>
90       * 
91       * @return the default singleon instance
92       */
93      public static synchronized DocumentFactory getInstance() {
94          if (singleton == null) {
95              singleton = createSingleton();
96          }
97          return (DocumentFactory) singleton.instance();
98      }
99  
100     // Factory methods
101     public Document createDocument() {
102         DefaultDocument answer = new DefaultDocument();
103         answer.setDocumentFactory(this);
104 
105         return answer;
106     }
107 
108     /***
109      * DOCUMENT ME!
110      * 
111      * @param encoding
112      *            DOCUMENT ME!
113      * 
114      * @return DOCUMENT ME!
115      * 
116      * @since 1.5
117      */
118     public Document createDocument(String encoding) {
119         // to keep the DocumentFactory backwards compatible, we have to do this
120         // in this not so nice way, since subclasses only need to extend the
121         // createDocument() method.
122         Document answer = createDocument();
123 
124         if (answer instanceof AbstractDocument) {
125             ((AbstractDocument) answer).setXMLEncoding(encoding);
126         }
127 
128         return answer;
129     }
130 
131     public Document createDocument(Element rootElement) {
132         Document answer = createDocument();
133         answer.setRootElement(rootElement);
134 
135         return answer;
136     }
137 
138     public DocumentType createDocType(String name, String publicId,
139             String systemId) {
140         return new DefaultDocumentType(name, publicId, systemId);
141     }
142 
143     public Element createElement(QName qname) {
144         return new DefaultElement(qname);
145     }
146 
147     public Element createElement(String name) {
148         return createElement(createQName(name));
149     }
150 
151     public Element createElement(String qualifiedName, String namespaceURI) {
152         return createElement(createQName(qualifiedName, namespaceURI));
153     }
154 
155     public Attribute createAttribute(Element owner, QName qname, String value) {
156         return new DefaultAttribute(qname, value);
157     }
158 
159     public Attribute createAttribute(Element owner, String name, String value) {
160         return createAttribute(owner, createQName(name), value);
161     }
162 
163     public CDATA createCDATA(String text) {
164         return new DefaultCDATA(text);
165     }
166 
167     public Comment createComment(String text) {
168         return new DefaultComment(text);
169     }
170 
171     public Text createText(String text) {
172         if (text == null) {
173             String msg = "Adding text to an XML document must not be null";
174             throw new IllegalArgumentException(msg);
175         }
176 
177         return new DefaultText(text);
178     }
179 
180     public Entity createEntity(String name, String text) {
181         return new DefaultEntity(name, text);
182     }
183 
184     public Namespace createNamespace(String prefix, String uri) {
185         return Namespace.get(prefix, uri);
186     }
187 
188     public ProcessingInstruction createProcessingInstruction(String target,
189             String data) {
190         return new DefaultProcessingInstruction(target, data);
191     }
192 
193     public ProcessingInstruction createProcessingInstruction(String target,
194             Map data) {
195         return new DefaultProcessingInstruction(target, data);
196     }
197 
198     public QName createQName(String localName, Namespace namespace) {
199         return cache.get(localName, namespace);
200     }
201 
202     public QName createQName(String localName) {
203         return cache.get(localName);
204     }
205 
206     public QName createQName(String name, String prefix, String uri) {
207         return cache.get(name, Namespace.get(prefix, uri));
208     }
209 
210     public QName createQName(String qualifiedName, String uri) {
211         return cache.get(qualifiedName, uri);
212     }
213 
214     /***
215      * <p>
216      * <code>createXPath</code> parses an XPath expression and creates a new
217      * XPath <code>XPath</code> instance.
218      * </p>
219      * 
220      * @param xpathExpression
221      *            is the XPath expression to create
222      * 
223      * @return a new <code>XPath</code> instance
224      * 
225      * @throws InvalidXPathException
226      *             if the XPath expression is invalid
227      */
228     public XPath createXPath(String xpathExpression)
229             throws InvalidXPathException {
230         DefaultXPath xpath = new DefaultXPath(xpathExpression);
231 
232         if (xpathNamespaceURIs != null) {
233             xpath.setNamespaceURIs(xpathNamespaceURIs);
234         }
235 
236         return xpath;
237     }
238 
239     /***
240      * <p>
241      * <code>createXPath</code> parses an XPath expression and creates a new
242      * XPath <code>XPath</code> instance.
243      * </p>
244      * 
245      * @param xpathExpression
246      *            is the XPath expression to create
247      * @param variableContext
248      *            is the variable context to use when evaluating the XPath
249      * 
250      * @return a new <code>XPath</code> instance
251      */
252     public XPath createXPath(String xpathExpression,
253             VariableContext variableContext) {
254         XPath xpath = createXPath(xpathExpression);
255         xpath.setVariableContext(variableContext);
256 
257         return xpath;
258     }
259 
260     /***
261      * <p>
262      * <code>createXPathFilter</code> parses a NodeFilter from the given XPath
263      * filter expression. XPath filter expressions occur within XPath
264      * expressions such as <code>self::node()[ filterExpression ]</code>
265      * </p>
266      * 
267      * @param xpathFilterExpression
268      *            is the XPath filter expression to create
269      * @param variableContext
270      *            is the variable context to use when evaluating the XPath
271      * 
272      * @return a new <code>NodeFilter</code> instance
273      */
274     public NodeFilter createXPathFilter(String xpathFilterExpression,
275             VariableContext variableContext) {
276         XPath answer = createXPath(xpathFilterExpression);
277 
278         // DefaultXPath answer = new DefaultXPath( xpathFilterExpression );
279         answer.setVariableContext(variableContext);
280 
281         return answer;
282     }
283 
284     /***
285      * <p>
286      * <code>createXPathFilter</code> parses a NodeFilter from the given XPath
287      * filter expression. XPath filter expressions occur within XPath
288      * expressions such as <code>self::node()[ filterExpression ]</code>
289      * </p>
290      * 
291      * @param xpathFilterExpression
292      *            is the XPath filter expression to create
293      * 
294      * @return a new <code>NodeFilter</code> instance
295      */
296     public NodeFilter createXPathFilter(String xpathFilterExpression) {
297         return createXPath(xpathFilterExpression);
298 
299         // return new DefaultXPath( xpathFilterExpression );
300     }
301 
302     /***
303      * <p>
304      * <code>createPattern</code> parses the given XPath expression to create
305      * an XSLT style {@link Pattern}instance which can then be used in an XSLT
306      * processing model.
307      * </p>
308      * 
309      * @param xpathPattern
310      *            is the XPath pattern expression to create
311      * 
312      * @return a new <code>Pattern</code> instance
313      */
314     public Pattern createPattern(String xpathPattern) {
315         return new XPathPattern(xpathPattern);
316     }
317 
318     // Properties
319     // -------------------------------------------------------------------------
320 
321     /***
322      * Returns a list of all the QName instances currently used by this document
323      * factory
324      * 
325      * @return DOCUMENT ME!
326      */
327     public List getQNames() {
328         return cache.getQNames();
329     }
330 
331     /***
332      * DOCUMENT ME!
333      * 
334      * @return the Map of namespace URIs that will be used by by XPath
335      *         expressions to resolve namespace prefixes into namespace URIs.
336      *         The map is keyed by namespace prefix and the value is the
337      *         namespace URI. This value could well be null to indicate no
338      *         namespace URIs are being mapped.
339      */
340     public Map getXPathNamespaceURIs() {
341         return xpathNamespaceURIs;
342     }
343 
344     /***
345      * Sets the namespace URIs to be used by XPath expressions created by this
346      * factory or by nodes associated with this factory. The keys are namespace
347      * prefixes and the values are namespace URIs.
348      * 
349      * @param namespaceURIs
350      *            DOCUMENT ME!
351      */
352     public void setXPathNamespaceURIs(Map namespaceURIs) {
353         this.xpathNamespaceURIs = namespaceURIs;
354     }
355 
356     // Implementation methods
357     // -------------------------------------------------------------------------
358 
359     /***
360      * <p>
361      * <code>createSingleton</code> creates the singleton instance from the
362      * given class name.
363      * </p>
364      * 
365      * @param className
366      *            is the name of the DocumentFactory class to use
367      * 
368      * @return a new singleton instance.
369      */
370     protected static DocumentFactory createSingleton(String className) {
371         // let's try and class load an implementation?
372         try {
373             // I'll use the current class loader
374             // that loaded me to avoid problems in J2EE and web apps
375             Class theClass = Class.forName(className, true,
376                     DocumentFactory.class.getClassLoader());
377 
378             return (DocumentFactory) theClass.newInstance();
379         } catch (Throwable e) {
380             System.out.println("WARNING: Cannot load DocumentFactory: "
381                     + className);
382 
383             return new DocumentFactory();
384         }
385     }
386 
387     /***
388      * DOCUMENT ME!
389      * 
390      * @param qname
391      *            DOCUMENT ME!
392      * 
393      * @return the cached QName instance if there is one or adds the given qname
394      *         to the cache if not
395      */
396     protected QName intern(QName qname) {
397         return cache.intern(qname);
398     }
399 
400     /***
401      * Factory method to create the QNameCache. This method should be overloaded
402      * if you wish to use your own derivation of QName.
403      * 
404      * @return DOCUMENT ME!
405      */
406     protected QNameCache createQNameCache() {
407         return new QNameCache(this);
408     }
409 
410     private void readObject(ObjectInputStream in) throws IOException,
411             ClassNotFoundException {
412         in.defaultReadObject();
413         init();
414     }
415 
416     protected void init() {
417         cache = createQNameCache();
418     }
419 }
420 
421 /*
422  * Redistribution and use of this software and associated documentation
423  * ("Software"), with or without modification, are permitted provided that the
424  * following conditions are met:
425  * 
426  * 1. Redistributions of source code must retain copyright statements and
427  * notices. Redistributions must also contain a copy of this document.
428  * 
429  * 2. Redistributions in binary form must reproduce the above copyright notice,
430  * this list of conditions and the following disclaimer in the documentation
431  * and/or other materials provided with the distribution.
432  * 
433  * 3. The name "DOM4J" must not be used to endorse or promote products derived
434  * from this Software without prior written permission of MetaStuff, Ltd. For
435  * written permission, please contact dom4j-info@metastuff.com.
436  * 
437  * 4. Products derived from this Software may not be called "DOM4J" nor may
438  * "DOM4J" appear in their names without prior written permission of MetaStuff,
439  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
440  * 
441  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
442  * 
443  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
444  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
445  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
446  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
447  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
448  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
449  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
450  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
451  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
452  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
453  * POSSIBILITY OF SUCH DAMAGE.
454  * 
455  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
456  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/Comment.html0000644000175000017500000001425010242117747020063 0ustar ebourgebourg Comment xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  /***
11   * <p>
12   * <code>Comment</code> defines the behavior of an XML comment.
13   * </p>
14   * 
15   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
16   * @version $Revision: 1.7 $
17   */
18  public interface Comment extends CharacterData {
19  }
20  
21  /*
22   * Redistribution and use of this software and associated documentation
23   * ("Software"), with or without modification, are permitted provided that the
24   * following conditions are met:
25   * 
26   * 1. Redistributions of source code must retain copyright statements and
27   * notices. Redistributions must also contain a copy of this document.
28   * 
29   * 2. Redistributions in binary form must reproduce the above copyright notice,
30   * this list of conditions and the following disclaimer in the documentation
31   * and/or other materials provided with the distribution.
32   * 
33   * 3. The name "DOM4J" must not be used to endorse or promote products derived
34   * from this Software without prior written permission of MetaStuff, Ltd. For
35   * written permission, please contact dom4j-info@metastuff.com.
36   * 
37   * 4. Products derived from this Software may not be called "DOM4J" nor may
38   * "DOM4J" appear in their names without prior written permission of MetaStuff,
39   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
40   * 
41   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
42   * 
43   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
44   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
47   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
48   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
49   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
50   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
51   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
52   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
53   * POSSIBILITY OF SUCH DAMAGE.
54   * 
55   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
56   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/util/0000755000175000017500000000000012133227266016545 5ustar ebourgebourgdom4j-1.6.1/docs/xref/org/dom4j/util/UserDataDocumentFactory.html0000644000175000017500000002277410242117724024202 0ustar ebourgebourg UserDataDocumentFactory xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.util;
9   
10  import org.dom4j.Attribute;
11  import org.dom4j.DocumentFactory;
12  import org.dom4j.Element;
13  import org.dom4j.QName;
14  
15  /***
16   * <p>
17   * <code>UserDataDocumentFactory</code> is a factory of XML objects which
18   * support the adornment of a user data object on an Element or Attribute
19   * instance such that the methods <code>getData()</code> and
20   * <code>setData()</code> will get and set the values of a user data object.
21   * This can be useful for developers wishing to create XML trees and adorn the
22   * trees with user defined objects.
23   * </p>
24   * 
25   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
26   * @version $Revision: 1.11 $
27   */
28  public class UserDataDocumentFactory extends DocumentFactory {
29      /*** The Singleton instance */
30      protected static transient UserDataDocumentFactory singleton
31              = new UserDataDocumentFactory();
32  
33      /***
34       * <p>
35       * Access to the singleton instance of this factory.
36       * </p>
37       * 
38       * @return the default singleon instance
39       */
40      public static DocumentFactory getInstance() {
41          return singleton;
42      }
43  
44      // DocumentFactory methods
45      // -------------------------------------------------------------------------
46      public Element createElement(QName qname) {
47          return new UserDataElement(qname);
48      }
49  
50      public Attribute createAttribute(Element owner, QName qname, String value) {
51          return new UserDataAttribute(qname, value);
52      }
53  }
54  
55  /*
56   * Redistribution and use of this software and associated documentation
57   * ("Software"), with or without modification, are permitted provided that the
58   * following conditions are met:
59   * 
60   * 1. Redistributions of source code must retain copyright statements and
61   * notices. Redistributions must also contain a copy of this document.
62   * 
63   * 2. Redistributions in binary form must reproduce the above copyright notice,
64   * this list of conditions and the following disclaimer in the documentation
65   * and/or other materials provided with the distribution.
66   * 
67   * 3. The name "DOM4J" must not be used to endorse or promote products derived
68   * from this Software without prior written permission of MetaStuff, Ltd. For
69   * written permission, please contact dom4j-info@metastuff.com.
70   * 
71   * 4. Products derived from this Software may not be called "DOM4J" nor may
72   * "DOM4J" appear in their names without prior written permission of MetaStuff,
73   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
74   * 
75   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
76   * 
77   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
78   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
79   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
80   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
81   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
82   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
83   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
84   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
85   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
86   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
87   * POSSIBILITY OF SUCH DAMAGE.
88   * 
89   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
90   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/util/IndexedDocumentFactory.html0000644000175000017500000002220310242117737024041 0ustar ebourgebourg IndexedDocumentFactory xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.util;
9   
10  import org.dom4j.DocumentFactory;
11  import org.dom4j.Element;
12  import org.dom4j.QName;
13  
14  /***
15   * <p>
16   * <code>IndexedDocumentFactory</code> is a factory of XML objects which
17   * create indexed Element implementations to allow quicker lookup via name of
18   * Element and Attributes though at the expense of more memory used to create
19   * the name indexes.
20   * </p>
21   * 
22   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
23   * @version $Revision: 1.9 $
24   */
25  public class IndexedDocumentFactory extends DocumentFactory {
26      /*** The Singleton instance */
27      protected static transient IndexedDocumentFactory singleton
28              = new IndexedDocumentFactory();
29  
30      /***
31       * <p>
32       * Access to the singleton instance of this factory.
33       * </p>
34       * 
35       * @return the default singleon instance
36       */
37      public static DocumentFactory getInstance() {
38          return singleton;
39      }
40  
41      // DocumentFactory methods
42      // -------------------------------------------------------------------------
43      public Element createElement(QName qname) {
44          return new IndexedElement(qname);
45      }
46  
47      public Element createElement(QName qname, int attributeCount) {
48          return new IndexedElement(qname, attributeCount);
49      }
50  }
51  
52  /*
53   * Redistribution and use of this software and associated documentation
54   * ("Software"), with or without modification, are permitted provided that the
55   * following conditions are met:
56   * 
57   * 1. Redistributions of source code must retain copyright statements and
58   * notices. Redistributions must also contain a copy of this document.
59   * 
60   * 2. Redistributions in binary form must reproduce the above copyright notice,
61   * this list of conditions and the following disclaimer in the documentation
62   * and/or other materials provided with the distribution.
63   * 
64   * 3. The name "DOM4J" must not be used to endorse or promote products derived
65   * from this Software without prior written permission of MetaStuff, Ltd. For
66   * written permission, please contact dom4j-info@metastuff.com.
67   * 
68   * 4. Products derived from this Software may not be called "DOM4J" nor may
69   * "DOM4J" appear in their names without prior written permission of MetaStuff,
70   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
71   * 
72   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
73   * 
74   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
75   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
76   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
77   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
78   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
79   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
80   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
81   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
82   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
83   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
84   * POSSIBILITY OF SUCH DAMAGE.
85   * 
86   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
87   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/util/package-summary.html0000644000175000017500000001035210242117622022513 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.util

Class Summary
AttributeHelper
IndexedDocumentFactory
IndexedElement
NodeComparator
NonLazyDocumentFactory
NonLazyElement
PerThreadSingleton
ProxyDocumentFactory
SimpleSingleton
SingletonStrategy
UserDataAttribute
UserDataDocumentFactory
UserDataElement
XMLErrorHandler
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref/org/dom4j/util/UserDataElement.html0000644000175000017500000002722310242117757022465 0ustar ebourgebourg UserDataElement xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.util;
9   
10  import org.dom4j.Element;
11  import org.dom4j.QName;
12  import org.dom4j.tree.DefaultElement;
13  
14  /***
15   * <p>
16   * <code>UserDataElement</code> support the adornment of a user data object on
17   * an Element or Attribute instance such that the methods {@link#getData}
18   * {@link #setData(Object)}will get and set the values of a user data object.
19   * This can be useful for developers wishing to create XML trees and adorn the
20   * trees with user defined objects.
21   * </p>
22   * 
23   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
24   * @version $Revision: 1.12 $
25   */
26  public class UserDataElement extends DefaultElement {
27      /*** The user data object */
28      private Object data;
29  
30      public UserDataElement(String name) {
31          super(name);
32      }
33  
34      public UserDataElement(QName qname) {
35          super(qname);
36      }
37  
38      public Object getData() {
39          return data;
40      }
41  
42      public void setData(Object data) {
43          this.data = data;
44      }
45  
46      public String toString() {
47          return super.toString() + " userData: " + data;
48      }
49  
50      public Object clone() {
51          UserDataElement answer = (UserDataElement) super.clone();
52  
53          if (answer != this) {
54              answer.data = getCopyOfUserData();
55          }
56  
57          return answer;
58      }
59  
60      // Implementation methods
61      // -------------------------------------------------------------------------
62  
63      /***
64       * If a deep copy of user data is required whenever the clone() or
65       * createCopy() methods are called on this element then this method should
66       * return a clone of the user data
67       * 
68       * @return DOCUMENT ME!
69       */
70      protected Object getCopyOfUserData() {
71          return data;
72      }
73  
74      protected Element createElement(String name) {
75          Element answer = getDocumentFactory().createElement(name);
76          answer.setData(getCopyOfUserData());
77  
78          return answer;
79      }
80  
81      protected Element createElement(QName qName) {
82          Element answer = getDocumentFactory().createElement(qName);
83          answer.setData(getCopyOfUserData());
84  
85          return answer;
86      }
87  
88      // protected DocumentFactory getDocumentFactory() {
89      // return DOCUMENT_FACTORY;
90      // }
91  }
92  
93  /*
94   * Redistribution and use of this software and associated documentation
95   * ("Software"), with or without modification, are permitted provided that the
96   * following conditions are met:
97   * 
98   * 1. Redistributions of source code must retain copyright statements and
99   * notices. Redistributions must also contain a copy of this document.
100  * 
101  * 2. Redistributions in binary form must reproduce the above copyright notice,
102  * this list of conditions and the following disclaimer in the documentation
103  * and/or other materials provided with the distribution.
104  * 
105  * 3. The name "DOM4J" must not be used to endorse or promote products derived
106  * from this Software without prior written permission of MetaStuff, Ltd. For
107  * written permission, please contact dom4j-info@metastuff.com.
108  * 
109  * 4. Products derived from this Software may not be called "DOM4J" nor may
110  * "DOM4J" appear in their names without prior written permission of MetaStuff,
111  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
112  * 
113  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
114  * 
115  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
116  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
117  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
118  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
119  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
120  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
121  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
122  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
123  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
124  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
125  * POSSIBILITY OF SUCH DAMAGE.
126  * 
127  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
128  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/util/NonLazyDocumentFactory.html0000644000175000017500000002131510242117717024054 0ustar ebourgebourg NonLazyDocumentFactory xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.util;
9   
10  import org.dom4j.DocumentFactory;
11  import org.dom4j.Element;
12  import org.dom4j.QName;
13  
14  /***
15   * <p>
16   * <code>NonLazyDocumentFactory</code> is a factory of XML objects which avoid
17   * using the lazy creation pattern. This results in a slower creation of a
18   * Document and uses more memory but it means that the same Document instance
19   * can be shared across threads provided it is not modified.
20   * </p>
21   * 
22   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
23   * @version $Revision: 1.9 $
24   */
25  public class NonLazyDocumentFactory extends DocumentFactory {
26      /*** The Singleton instance */
27      protected static transient NonLazyDocumentFactory singleton
28              = new NonLazyDocumentFactory();
29  
30      /***
31       * <p>
32       * Access to the singleton instance of this factory.
33       * </p>
34       * 
35       * @return the default singleon instance
36       */
37      public static DocumentFactory getInstance() {
38          return singleton;
39      }
40  
41      // DocumentFactory methods
42      // -------------------------------------------------------------------------
43      public Element createElement(QName qname) {
44          return new NonLazyElement(qname);
45      }
46  }
47  
48  /*
49   * Redistribution and use of this software and associated documentation
50   * ("Software"), with or without modification, are permitted provided that the
51   * following conditions are met:
52   * 
53   * 1. Redistributions of source code must retain copyright statements and
54   * notices. Redistributions must also contain a copy of this document.
55   * 
56   * 2. Redistributions in binary form must reproduce the above copyright notice,
57   * this list of conditions and the following disclaimer in the documentation
58   * and/or other materials provided with the distribution.
59   * 
60   * 3. The name "DOM4J" must not be used to endorse or promote products derived
61   * from this Software without prior written permission of MetaStuff, Ltd. For
62   * written permission, please contact dom4j-info@metastuff.com.
63   * 
64   * 4. Products derived from this Software may not be called "DOM4J" nor may
65   * "DOM4J" appear in their names without prior written permission of MetaStuff,
66   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
67   * 
68   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
69   * 
70   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
71   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
72   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
73   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
74   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
75   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
76   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
77   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
78   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
79   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
80   * POSSIBILITY OF SUCH DAMAGE.
81   * 
82   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
83   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/util/package-frame.html0000644000175000017500000000447710242117733022126 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.util

org.dom4j.util

Classes

  • AttributeHelper
  • IndexedDocumentFactory
  • IndexedElement
  • NodeComparator
  • NonLazyDocumentFactory
  • NonLazyElement
  • PerThreadSingleton
  • ProxyDocumentFactory
  • SimpleSingleton
  • SingletonStrategy
  • UserDataAttribute
  • UserDataDocumentFactory
  • UserDataElement
  • XMLErrorHandler
dom4j-1.6.1/docs/xref/org/dom4j/util/ProxyDocumentFactory.html0000644000175000017500000004524110242117637023610 0ustar ebourgebourg ProxyDocumentFactory xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.util;
9   
10  import java.util.Map;
11  
12  import org.dom4j.Attribute;
13  import org.dom4j.CDATA;
14  import org.dom4j.Comment;
15  import org.dom4j.Document;
16  import org.dom4j.DocumentFactory;
17  import org.dom4j.DocumentType;
18  import org.dom4j.Element;
19  import org.dom4j.Entity;
20  import org.dom4j.Namespace;
21  import org.dom4j.NodeFilter;
22  import org.dom4j.ProcessingInstruction;
23  import org.dom4j.QName;
24  import org.dom4j.Text;
25  import org.dom4j.XPath;
26  import org.dom4j.rule.Pattern;
27  
28  import org.jaxen.VariableContext;
29  
30  /***
31   * <p>
32   * <code>ProxyDocumentFactory</code> implements a proxy to a DocumentFactory
33   * which is useful for implementation inheritence, allowing the pipelining of
34   * various factory implementations. For example an EncodingDocumentFactory which
35   * takes care of encoding strings outside of allowable XML ranges could be used
36   * with a DatatypeDocumentFactory which is XML Schema Data Type aware.
37   * </p>
38   * 
39   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
40   * @version $Revision: 1.13 $
41   */
42  public abstract class ProxyDocumentFactory {
43      private DocumentFactory proxy;
44  
45      public ProxyDocumentFactory() {
46          // use default factory
47          this.proxy = DocumentFactory.getInstance();
48      }
49  
50      public ProxyDocumentFactory(DocumentFactory proxy) {
51          this.proxy = proxy;
52      }
53  
54      // Factory methods
55      // -------------------------------------------------------------------------
56      public Document createDocument() {
57          return proxy.createDocument();
58      }
59  
60      public Document createDocument(Element rootElement) {
61          return proxy.createDocument(rootElement);
62      }
63  
64      public DocumentType createDocType(String name, String publicId,
65              String systemId) {
66          return proxy.createDocType(name, publicId, systemId);
67      }
68  
69      public Element createElement(QName qname) {
70          return proxy.createElement(qname);
71      }
72  
73      public Element createElement(String name) {
74          return proxy.createElement(name);
75      }
76  
77      public Attribute createAttribute(Element owner, QName qname, String value) {
78          return proxy.createAttribute(owner, qname, value);
79      }
80  
81      public Attribute createAttribute(Element owner, String name, String value) {
82          return proxy.createAttribute(owner, name, value);
83      }
84  
85      public CDATA createCDATA(String text) {
86          return proxy.createCDATA(text);
87      }
88  
89      public Comment createComment(String text) {
90          return proxy.createComment(text);
91      }
92  
93      public Text createText(String text) {
94          return proxy.createText(text);
95      }
96  
97      public Entity createEntity(String name, String text) {
98          return proxy.createEntity(name, text);
99      }
100 
101     public Namespace createNamespace(String prefix, String uri) {
102         return proxy.createNamespace(prefix, uri);
103     }
104 
105     public ProcessingInstruction createProcessingInstruction(String target,
106             String data) {
107         return proxy.createProcessingInstruction(target, data);
108     }
109 
110     public ProcessingInstruction createProcessingInstruction(String target,
111             Map data) {
112         return proxy.createProcessingInstruction(target, data);
113     }
114 
115     public QName createQName(String localName, Namespace namespace) {
116         return proxy.createQName(localName, namespace);
117     }
118 
119     public QName createQName(String localName) {
120         return proxy.createQName(localName);
121     }
122 
123     public QName createQName(String name, String prefix, String uri) {
124         return proxy.createQName(name, prefix, uri);
125     }
126 
127     public QName createQName(String qualifiedName, String uri) {
128         return proxy.createQName(qualifiedName, uri);
129     }
130 
131     public XPath createXPath(String xpathExpression) {
132         return proxy.createXPath(xpathExpression);
133     }
134 
135     public XPath createXPath(String xpathExpression,
136             VariableContext variableContext) {
137         return proxy.createXPath(xpathExpression, variableContext);
138     }
139 
140     public NodeFilter createXPathFilter(String xpathFilterExpression,
141             VariableContext variableContext) {
142         return proxy.createXPathFilter(xpathFilterExpression, variableContext);
143     }
144 
145     public NodeFilter createXPathFilter(String xpathFilterExpression) {
146         return proxy.createXPathFilter(xpathFilterExpression);
147     }
148 
149     public Pattern createPattern(String xpathPattern) {
150         return proxy.createPattern(xpathPattern);
151     }
152 
153     // Implementation methods
154     // -------------------------------------------------------------------------
155     protected DocumentFactory getProxy() {
156         return proxy;
157     }
158 
159     protected void setProxy(DocumentFactory proxy) {
160         if (proxy == null) {
161             // use default factory
162             proxy = DocumentFactory.getInstance();
163         }
164 
165         this.proxy = proxy;
166     }
167 }
168 
169 /*
170  * Redistribution and use of this software and associated documentation
171  * ("Software"), with or without modification, are permitted provided that the
172  * following conditions are met:
173  * 
174  * 1. Redistributions of source code must retain copyright statements and
175  * notices. Redistributions must also contain a copy of this document.
176  * 
177  * 2. Redistributions in binary form must reproduce the above copyright notice,
178  * this list of conditions and the following disclaimer in the documentation
179  * and/or other materials provided with the distribution.
180  * 
181  * 3. The name "DOM4J" must not be used to endorse or promote products derived
182  * from this Software without prior written permission of MetaStuff, Ltd. For
183  * written permission, please contact dom4j-info@metastuff.com.
184  * 
185  * 4. Products derived from this Software may not be called "DOM4J" nor may
186  * "DOM4J" appear in their names without prior written permission of MetaStuff,
187  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
188  * 
189  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
190  * 
191  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
192  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
193  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
194  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
195  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
196  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
197  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
198  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
199  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
200  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
201  * POSSIBILITY OF SUCH DAMAGE.
202  * 
203  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
204  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/util/SimpleSingleton.html0000644000175000017500000002175110242117605022547 0ustar ebourgebourg SimpleSingleton xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.util;
9   
10  /***
11   * <p>
12   * <code>SimpleSingleton</code> is an implementation of the SingletonStrategy
13   * interface used to provide common factory access for the same object instance.
14   * This implementation will create a new instance from the class specified and
15   * will not create a new one unless it is reset.
16   * </p>
17   * 
18   * @author <a href="mailto:ddlucas@users.sourceforge.net">David Lucas </a>
19   * @version $Revision: 1.3 $
20   */
21  
22  public class SimpleSingleton implements SingletonStrategy {
23      private String singletonClassName = null;
24  
25      private Object singletonInstance = null;
26  
27      public SimpleSingleton() {
28      }
29  
30      public Object instance() {
31          return singletonInstance;
32      }
33  
34      public void reset() {
35          if (singletonClassName != null) {
36              Class clazz = null;
37              try {
38                  clazz = Thread.currentThread().getContextClassLoader().loadClass(
39                          singletonClassName);
40                  singletonInstance = clazz.newInstance();
41              } catch (Exception ignore) {
42                  try {
43                      clazz = Class.forName(singletonClassName);
44                      singletonInstance = clazz.newInstance();
45                  } catch (Exception ignore2) {
46                  }
47              }
48  
49          }
50      }
51  
52      public void setSingletonClassName(String singletonClassName) {
53          this.singletonClassName = singletonClassName;
54          reset();
55      }
56  
57  }
58  
59  /*
60   * Redistribution and use of this software and associated documentation
61   * ("Software"), with or without modification, are permitted provided that the
62   * following conditions are met:
63   * 
64   * 1. Redistributions of source code must retain copyright statements and
65   * notices. Redistributions must also contain a copy of this document.
66   * 
67   * 2. Redistributions in binary form must reproduce the above copyright notice,
68   * this list of conditions and the following disclaimer in the documentation
69   * and/or other materials provided with the distribution.
70   * 
71   * 3. The name "DOM4J" must not be used to endorse or promote products derived
72   * from this Software without prior written permission of MetaStuff, Ltd. For
73   * written permission, please contact dom4j-info@metastuff.com.
74   * 
75   * 4. Products derived from this Software may not be called "DOM4J" nor may
76   * "DOM4J" appear in their names without prior written permission of MetaStuff,
77   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
78   * 
79   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
80   * 
81   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
82   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
83   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
84   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
85   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
86   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
87   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
88   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
89   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
90   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
91   * POSSIBILITY OF SUCH DAMAGE.
92   * 
93   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
94   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/util/NonLazyElement.html0000644000175000017500000002120110242117635022330 0ustar ebourgebourg NonLazyElement xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.util;
9   
10  import org.dom4j.Namespace;
11  import org.dom4j.QName;
12  import org.dom4j.tree.BaseElement;
13  
14  /***
15   * <p>
16   * <code>NonLazyElement</code> is the default DOM4J default implementation of
17   * an XML element.
18   * </p>
19   * 
20   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
21   * @version $Revision: 1.8 $
22   */
23  public class NonLazyElement extends BaseElement {
24      public NonLazyElement(String name) {
25          super(name);
26          this.attributes = createAttributeList();
27          this.content = createContentList();
28      }
29  
30      public NonLazyElement(QName qname) {
31          super(qname);
32          this.attributes = createAttributeList();
33          this.content = createContentList();
34      }
35  
36      public NonLazyElement(String name, Namespace namespace) {
37          super(name, namespace);
38          this.attributes = createAttributeList();
39          this.content = createContentList();
40      }
41  
42      public NonLazyElement(QName qname, int attributeCount) {
43          super(qname);
44          this.attributes = createAttributeList(attributeCount);
45          this.content = createContentList();
46      }
47  }
48  
49  /*
50   * Redistribution and use of this software and associated documentation
51   * ("Software"), with or without modification, are permitted provided that the
52   * following conditions are met:
53   * 
54   * 1. Redistributions of source code must retain copyright statements and
55   * notices. Redistributions must also contain a copy of this document.
56   * 
57   * 2. Redistributions in binary form must reproduce the above copyright notice,
58   * this list of conditions and the following disclaimer in the documentation
59   * and/or other materials provided with the distribution.
60   * 
61   * 3. The name "DOM4J" must not be used to endorse or promote products derived
62   * from this Software without prior written permission of MetaStuff, Ltd. For
63   * written permission, please contact dom4j-info@metastuff.com.
64   * 
65   * 4. Products derived from this Software may not be called "DOM4J" nor may
66   * "DOM4J" appear in their names without prior written permission of MetaStuff,
67   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
68   * 
69   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
70   * 
71   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
72   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
73   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
74   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
75   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
76   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
77   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
78   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
79   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
80   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
81   * POSSIBILITY OF SUCH DAMAGE.
82   * 
83   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
84   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/util/PerThreadSingleton.html0000644000175000017500000002400010242117627023166 0ustar ebourgebourg PerThreadSingleton xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.util;
9   
10  import java.lang.ref.WeakReference;
11  
12  /***
13   * <p>
14   * <code>PerThreadSingleton</code> is an implementation of the
15   * SingletonStrategy used to provide common factory access to a single object
16   * instance based on an implementation strategy for one object instance per
17   * thread. This is useful in replace of the ThreadLocal usage.
18   * </p>
19   * 
20   * @author <a href="mailto:ddlucas@users.sourceforge.net">David Lucas </a>
21   * @version $Revision: 1.3 $
22   */
23  
24  public class PerThreadSingleton implements SingletonStrategy {
25      private String singletonClassName = null;
26  
27      private ThreadLocal perThreadCache = new ThreadLocal();
28  
29      public PerThreadSingleton() {
30      }
31  
32      public void reset() {
33          perThreadCache = new ThreadLocal();
34      }
35  
36      public Object instance() {
37          Object singletonInstancePerThread = null;
38          // use weak reference to prevent cyclic reference during GC
39          WeakReference ref = (WeakReference) perThreadCache.get();
40          // singletonInstancePerThread=perThreadCache.get();
41          // if (singletonInstancePerThread==null) {
42          if (ref == null || ref.get() == null) {
43              Class clazz = null;
44              try {
45                  clazz = Thread.currentThread().getContextClassLoader().loadClass(
46                          singletonClassName);
47                  singletonInstancePerThread = clazz.newInstance();
48              } catch (Exception ignore) {
49                  try {
50                      clazz = Class.forName(singletonClassName);
51                      singletonInstancePerThread = clazz.newInstance();
52                  } catch (Exception ignore2) {
53                  }
54              }
55              perThreadCache.set(new WeakReference(singletonInstancePerThread));
56          } else {
57              singletonInstancePerThread = ref.get();
58          }
59          return singletonInstancePerThread;
60      }
61  
62      public void setSingletonClassName(String singletonClassName) {
63          this.singletonClassName = singletonClassName;
64      }
65  
66  }
67  
68  /*
69   * Redistribution and use of this software and associated documentation
70   * ("Software"), with or without modification, are permitted provided that the
71   * following conditions are met:
72   * 
73   * 1. Redistributions of source code must retain copyright statements and
74   * notices. Redistributions must also contain a copy of this document.
75   * 
76   * 2. Redistributions in binary form must reproduce the above copyright notice,
77   * this list of conditions and the following disclaimer in the documentation
78   * and/or other materials provided with the distribution.
79   * 
80   * 3. The name "DOM4J" must not be used to endorse or promote products derived
81   * from this Software without prior written permission of MetaStuff, Ltd. For
82   * written permission, please contact dom4j-info@metastuff.com.
83   * 
84   * 4. Products derived from this Software may not be called "DOM4J" nor may
85   * "DOM4J" appear in their names without prior written permission of MetaStuff,
86   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
87   * 
88   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
89   * 
90   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
91   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
92   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
93   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
94   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
95   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
96   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
97   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
98   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
99   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
100  * POSSIBILITY OF SUCH DAMAGE.
101  * 
102  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
103  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/util/IndexedElement.html0000644000175000017500000006407110242117745022334 0ustar ebourgebourg IndexedElement xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.util;
9   
10  import java.util.ArrayList;
11  import java.util.HashMap;
12  import java.util.Iterator;
13  import java.util.List;
14  import java.util.Map;
15  
16  import org.dom4j.Attribute;
17  import org.dom4j.Element;
18  import org.dom4j.Node;
19  import org.dom4j.QName;
20  import org.dom4j.tree.BackedList;
21  import org.dom4j.tree.DefaultElement;
22  
23  /***
24   * <p>
25   * <code>IndexedElement</code> is an implementation of {@link Element}which
26   * maintains an index of the attributes and elements it contains to optimise
27   * lookups via name.
28   * </p>
29   * 
30   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
31   * @version $Revision: 1.10 $
32   */
33  public class IndexedElement extends DefaultElement {
34      /*** Lazily constructed index for elements */
35      private Map elementIndex;
36  
37      /*** Lazily constructed index for attributes */
38      private Map attributeIndex;
39  
40      public IndexedElement(String name) {
41          super(name);
42      }
43  
44      public IndexedElement(QName qname) {
45          super(qname);
46      }
47  
48      public IndexedElement(QName qname, int attributeCount) {
49          super(qname, attributeCount);
50      }
51  
52      public Attribute attribute(String name) {
53          return (Attribute) attributeIndex().get(name);
54      }
55  
56      public Attribute attribute(QName qName) {
57          return (Attribute) attributeIndex().get(qName);
58      }
59  
60      public Element element(String name) {
61          return asElement(elementIndex().get(name));
62      }
63  
64      public Element element(QName qName) {
65          return asElement(elementIndex().get(qName));
66      }
67  
68      public List elements(String name) {
69          return asElementList(elementIndex().get(name));
70      }
71  
72      public List elements(QName qName) {
73          return asElementList(elementIndex().get(qName));
74      }
75  
76      // Implementation methods
77      // -------------------------------------------------------------------------
78      protected Element asElement(Object object) {
79          if (object instanceof Element) {
80              return (Element) object;
81          } else if (object != null) {
82              List list = (List) object;
83  
84              if (list.size() >= 1) {
85                  return (Element) list.get(0);
86              }
87          }
88  
89          return null;
90      }
91  
92      protected List asElementList(Object object) {
93          if (object instanceof Element) {
94              return createSingleResultList(object);
95          } else if (object != null) {
96              List list = (List) object;
97              BackedList answer = createResultList();
98  
99              for (int i = 0, size = list.size(); i < size; i++) {
100                 answer.addLocal(list.get(i));
101             }
102 
103             return answer;
104         }
105 
106         return createEmptyList();
107     }
108 
109     /***
110      * DOCUMENT ME!
111      * 
112      * @param object
113      *            DOCUMENT ME!
114      * 
115      * @return DOCUMENT ME!
116      * 
117      * @deprecated WILL BE REMOVED IN dom4j-1.6 !!
118      */
119     protected Iterator asElementIterator(Object object) {
120         return asElementList(object).iterator();
121     }
122 
123     // #### could we override the add(Element) remove(Element methods?
124     protected void addNode(Node node) {
125         super.addNode(node);
126 
127         if ((elementIndex != null) && node instanceof Element) {
128             addToElementIndex((Element) node);
129         } else if ((attributeIndex != null) && node instanceof Attribute) {
130             addToAttributeIndex((Attribute) node);
131         }
132     }
133 
134     protected boolean removeNode(Node node) {
135         if (super.removeNode(node)) {
136             if ((elementIndex != null) && node instanceof Element) {
137                 removeFromElementIndex((Element) node);
138             } else if ((attributeIndex != null) && node instanceof Attribute) {
139                 removeFromAttributeIndex((Attribute) node);
140             }
141 
142             return true;
143         }
144 
145         return false;
146     }
147 
148     protected Map attributeIndex() {
149         if (attributeIndex == null) {
150             attributeIndex = createAttributeIndex();
151 
152             for (Iterator iter = attributeIterator(); iter.hasNext();) {
153                 addToAttributeIndex((Attribute) iter.next());
154             }
155         }
156 
157         return attributeIndex;
158     }
159 
160     protected Map elementIndex() {
161         if (elementIndex == null) {
162             elementIndex = createElementIndex();
163 
164             for (Iterator iter = elementIterator(); iter.hasNext();) {
165                 addToElementIndex((Element) iter.next());
166             }
167         }
168 
169         return elementIndex;
170     }
171 
172     /***
173      * A Factory Method to create the index for attributes
174      * 
175      * @return DOCUMENT ME!
176      */
177     protected Map createAttributeIndex() {
178         Map answer = createIndex();
179 
180         return answer;
181     }
182 
183     /***
184      * A Factory Method to create the index for elements
185      * 
186      * @return DOCUMENT ME!
187      */
188     protected Map createElementIndex() {
189         Map answer = createIndex();
190 
191         return answer;
192     }
193 
194     protected void addToElementIndex(Element element) {
195         QName qName = element.getQName();
196         String name = qName.getName();
197         addToElementIndex(qName, element);
198         addToElementIndex(name, element);
199     }
200 
201     protected void addToElementIndex(Object key, Element value) {
202         Object oldValue = elementIndex.get(key);
203 
204         if (oldValue == null) {
205             elementIndex.put(key, value);
206         } else {
207             if (oldValue instanceof List) {
208                 List list = (List) oldValue;
209                 list.add(value);
210             } else {
211                 List list = createList();
212                 list.add(oldValue);
213                 list.add(value);
214                 elementIndex.put(key, list);
215             }
216         }
217     }
218 
219     protected void removeFromElementIndex(Element element) {
220         QName qName = element.getQName();
221         String name = qName.getName();
222         removeFromElementIndex(qName, element);
223         removeFromElementIndex(name, element);
224     }
225 
226     protected void removeFromElementIndex(Object key, Element value) {
227         Object oldValue = elementIndex.get(key);
228 
229         if (oldValue instanceof List) {
230             List list = (List) oldValue;
231             list.remove(value);
232         } else {
233             elementIndex.remove(key);
234         }
235     }
236 
237     protected void addToAttributeIndex(Attribute attribute) {
238         QName qName = attribute.getQName();
239         String name = qName.getName();
240         addToAttributeIndex(qName, attribute);
241         addToAttributeIndex(name, attribute);
242     }
243 
244     protected void addToAttributeIndex(Object key, Attribute value) {
245         Object oldValue = attributeIndex.get(key);
246 
247         if (oldValue != null) {
248             attributeIndex.put(key, value);
249         }
250     }
251 
252     protected void removeFromAttributeIndex(Attribute attribute) {
253         QName qName = attribute.getQName();
254         String name = qName.getName();
255         removeFromAttributeIndex(qName, attribute);
256         removeFromAttributeIndex(name, attribute);
257     }
258 
259     protected void removeFromAttributeIndex(Object key, Attribute value) {
260         Object oldValue = attributeIndex.get(key);
261 
262         if ((oldValue != null) && oldValue.equals(value)) {
263             attributeIndex.remove(key);
264         }
265     }
266 
267     /***
268      * Factory method to return a new map implementation for indices
269      * 
270      * @return DOCUMENT ME!
271      */
272     protected Map createIndex() {
273         return new HashMap();
274     }
275 
276     /***
277      * Factory method to return a list implementation for indices
278      * 
279      * @return DOCUMENT ME!
280      */
281     protected List createList() {
282         return new ArrayList();
283     }
284 }
285 
286 /*
287  * Redistribution and use of this software and associated documentation
288  * ("Software"), with or without modification, are permitted provided that the
289  * following conditions are met:
290  * 
291  * 1. Redistributions of source code must retain copyright statements and
292  * notices. Redistributions must also contain a copy of this document.
293  * 
294  * 2. Redistributions in binary form must reproduce the above copyright notice,
295  * this list of conditions and the following disclaimer in the documentation
296  * and/or other materials provided with the distribution.
297  * 
298  * 3. The name "DOM4J" must not be used to endorse or promote products derived
299  * from this Software without prior written permission of MetaStuff, Ltd. For
300  * written permission, please contact dom4j-info@metastuff.com.
301  * 
302  * 4. Products derived from this Software may not be called "DOM4J" nor may
303  * "DOM4J" appear in their names without prior written permission of MetaStuff,
304  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
305  * 
306  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
307  * 
308  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
309  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
310  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
311  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
312  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
313  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
314  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
315  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
316  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
317  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
318  * POSSIBILITY OF SUCH DAMAGE.
319  * 
320  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
321  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/util/SingletonStrategy.html0000644000175000017500000001742510242117653023126 0ustar ebourgebourg SingletonStrategy xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.util;
9   
10  /***
11   * <p>
12   * <code>SingletonStrategy</code> is an interface used to provide common
13   * factory access for the same object based on an implementation strategy for
14   * singleton. Right now there are two that accompany this interface:
15   * SimpleSingleton and PerThreadSingleton. This will replace previous usage of
16   * ThreadLocal to allow for alternate strategies.
17   * </p>
18   * 
19   * @author <a href="mailto:ddlucas@users.sourceforge.net">David Lucas </a>
20   * @version $Revision: 1.2 $
21   */
22  public interface SingletonStrategy {
23      /***
24       * return a singleton instance of the class specified in setSingletonClass
25       */
26      Object instance();
27  
28      /***
29       * reset the instance to a new instance for the implemented strategy
30       */
31      void reset();
32  
33      /***
34       * set a singleton class name that will be used to create the singleton
35       * based on the strategy implementation of this interface. The default
36       * constructor of the class will be used and must be public.
37       */
38      void setSingletonClassName(String singletonClassName);
39  }
40  
41  /*
42   * Redistribution and use of this software and associated documentation
43   * ("Software"), with or without modification, are permitted provided that the
44   * following conditions are met:
45   * 
46   * 1. Redistributions of source code must retain copyright statements and
47   * notices. Redistributions must also contain a copy of this document.
48   * 
49   * 2. Redistributions in binary form must reproduce the above copyright notice,
50   * this list of conditions and the following disclaimer in the documentation
51   * and/or other materials provided with the distribution.
52   * 
53   * 3. The name "DOM4J" must not be used to endorse or promote products derived
54   * from this Software without prior written permission of MetaStuff, Ltd. For
55   * written permission, please contact dom4j-info@metastuff.com.
56   * 
57   * 4. Products derived from this Software may not be called "DOM4J" nor may
58   * "DOM4J" appear in their names without prior written permission of MetaStuff,
59   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
60   * 
61   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
62   * 
63   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
64   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
65   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
66   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
67   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
68   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
69   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
70   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
71   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
72   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
73   * POSSIBILITY OF SUCH DAMAGE.
74   * 
75   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
76   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/util/AttributeHelper.html0000644000175000017500000002152010242117751022532 0ustar ebourgebourg AttributeHelper xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.util;
9   
10  import org.dom4j.Attribute;
11  import org.dom4j.Element;
12  import org.dom4j.QName;
13  
14  /***
15   * <p>
16   * <code>AttributeHelper</code> a number of helper methods for working with
17   * attribute values.
18   * </p>
19   * 
20   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
21   * @version $Revision: 1.7 $
22   */
23  public class AttributeHelper {
24      protected AttributeHelper() {
25      }
26  
27      public static boolean booleanValue(Element element, String attributeName) {
28          return booleanValue(element.attribute(attributeName));
29      }
30  
31      public static boolean booleanValue(Element element, QName attributeQName) {
32          return booleanValue(element.attribute(attributeQName));
33      }
34  
35      protected static boolean booleanValue(Attribute attribute) {
36          if (attribute == null) {
37              return false;
38          }
39  
40          Object value = attribute.getData();
41  
42          if (value == null) {
43              return false;
44          } else if (value instanceof Boolean) {
45              Boolean b = (Boolean) value;
46  
47              return b.booleanValue();
48          } else {
49              return "true".equalsIgnoreCase(value.toString());
50          }
51      }
52  }
53  
54  /*
55   * Redistribution and use of this software and associated documentation
56   * ("Software"), with or without modification, are permitted provided that the
57   * following conditions are met:
58   * 
59   * 1. Redistributions of source code must retain copyright statements and
60   * notices. Redistributions must also contain a copy of this document.
61   * 
62   * 2. Redistributions in binary form must reproduce the above copyright notice,
63   * this list of conditions and the following disclaimer in the documentation
64   * and/or other materials provided with the distribution.
65   * 
66   * 3. The name "DOM4J" must not be used to endorse or promote products derived
67   * from this Software without prior written permission of MetaStuff, Ltd. For
68   * written permission, please contact dom4j-info@metastuff.com.
69   * 
70   * 4. Products derived from this Software may not be called "DOM4J" nor may
71   * "DOM4J" appear in their names without prior written permission of MetaStuff,
72   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
73   * 
74   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
75   * 
76   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
77   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
78   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
79   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
80   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
81   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
82   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
83   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
84   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
85   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
86   * POSSIBILITY OF SUCH DAMAGE.
87   * 
88   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
89   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/util/UserDataAttribute.html0000644000175000017500000002026510242117762023032 0ustar ebourgebourg UserDataAttribute xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.util;
9   
10  import org.dom4j.QName;
11  import org.dom4j.tree.DefaultAttribute;
12  
13  /***
14   * <p>
15   * <code>UserDataAttribute</code> support the adornment of a user data object
16   * on an Element or Attribute instance such that the methods {@link#getData}
17   * {@link #setData(Object)}will get and set the values of a user data object.
18   * This can be useful for developers wishing to create XML trees and adorn the
19   * trees with user defined objects.
20   * </p>
21   * 
22   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
23   * @version $Revision: 1.8 $
24   */
25  public class UserDataAttribute extends DefaultAttribute {
26      /*** The user data object */
27      private Object data;
28  
29      public UserDataAttribute(QName qname) {
30          super(qname);
31      }
32  
33      public UserDataAttribute(QName qname, String text) {
34          super(qname, text);
35      }
36  
37      public Object getData() {
38          return data;
39      }
40  
41      public void setData(Object data) {
42          this.data = data;
43      }
44  }
45  
46  /*
47   * Redistribution and use of this software and associated documentation
48   * ("Software"), with or without modification, are permitted provided that the
49   * following conditions are met:
50   * 
51   * 1. Redistributions of source code must retain copyright statements and
52   * notices. Redistributions must also contain a copy of this document.
53   * 
54   * 2. Redistributions in binary form must reproduce the above copyright notice,
55   * this list of conditions and the following disclaimer in the documentation
56   * and/or other materials provided with the distribution.
57   * 
58   * 3. The name "DOM4J" must not be used to endorse or promote products derived
59   * from this Software without prior written permission of MetaStuff, Ltd. For
60   * written permission, please contact dom4j-info@metastuff.com.
61   * 
62   * 4. Products derived from this Software may not be called "DOM4J" nor may
63   * "DOM4J" appear in their names without prior written permission of MetaStuff,
64   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
65   * 
66   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
67   * 
68   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
69   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
70   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
71   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
72   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
73   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
74   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
75   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
76   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
77   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
78   * POSSIBILITY OF SUCH DAMAGE.
79   * 
80   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
81   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/util/XMLErrorHandler.html0000644000175000017500000003715110242117765022413 0ustar ebourgebourg XMLErrorHandler xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.util;
9   
10  import org.dom4j.DocumentHelper;
11  import org.dom4j.Element;
12  import org.dom4j.QName;
13  
14  import org.xml.sax.ErrorHandler;
15  import org.xml.sax.SAXParseException;
16  
17  /***
18   * <code>XMLErrorHandler</code> is a SAX {@link ErrorHandler}which turns the
19   * SAX parsing errors into XML so that the output can be formatted using XSLT or
20   * the errors can be included in a SOAP message.
21   * 
22   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
23   * @version $Revision: 1.7 $
24   */
25  public class XMLErrorHandler implements ErrorHandler {
26      protected static final QName ERROR_QNAME = QName.get("error");
27  
28      protected static final QName FATALERROR_QNAME = QName.get("fatalError");
29  
30      protected static final QName WARNING_QNAME = QName.get("warning");
31  
32      /*** Stores the errors that occur during a SAX parse */
33      private Element errors;
34  
35      /*** QName used for error elements */
36      private QName errorQName = ERROR_QNAME;
37  
38      /*** QName used for fatalerror elements */
39      private QName fatalErrorQName = FATALERROR_QNAME;
40  
41      /*** QName used for warning elements */
42      private QName warningQName = WARNING_QNAME;
43  
44      public XMLErrorHandler() {
45          this.errors = DocumentHelper.createElement("errors");
46      }
47  
48      public XMLErrorHandler(Element errors) {
49          this.errors = errors;
50      }
51  
52      public void error(SAXParseException e) {
53          Element element = errors.addElement(errorQName);
54          addException(element, e);
55      }
56  
57      public void fatalError(SAXParseException e) {
58          Element element = errors.addElement(fatalErrorQName);
59          addException(element, e);
60      }
61  
62      public void warning(SAXParseException e) {
63          Element element = errors.addElement(warningQName);
64          addException(element, e);
65      }
66  
67      // Properties
68      // -------------------------------------------------------------------------
69      public Element getErrors() {
70          return errors;
71      }
72  
73      public void setErrors(Element errors) {
74          this.errors = errors;
75      }
76  
77      // Allow the QNames used to create subelements to be changed
78      public QName getErrorQName() {
79          return errorQName;
80      }
81  
82      public void setErrorQName(QName errorQName) {
83          this.errorQName = errorQName;
84      }
85  
86      public QName getFatalErrorQName() {
87          return fatalErrorQName;
88      }
89  
90      public void setFatalErrorQName(QName fatalErrorQName) {
91          this.fatalErrorQName = fatalErrorQName;
92      }
93  
94      public QName getWarningQName() {
95          return warningQName;
96      }
97  
98      public void setWarningQName(QName warningQName) {
99          this.warningQName = warningQName;
100     }
101 
102     // Implementation methods
103     // -------------------------------------------------------------------------
104 
105     /***
106      * Adds the given parse exception information to the given element instance
107      * 
108      * @param element
109      *            DOCUMENT ME!
110      * @param e
111      *            DOCUMENT ME!
112      */
113     protected void addException(Element element, SAXParseException e) {
114         element.addAttribute("column", Integer.toString(e.getColumnNumber()));
115         element.addAttribute("line", Integer.toString(e.getLineNumber()));
116 
117         String publicID = e.getPublicId();
118 
119         if ((publicID != null) && (publicID.length() > 0)) {
120             element.addAttribute("publicID", publicID);
121         }
122 
123         String systemID = e.getSystemId();
124 
125         if ((systemID != null) && (systemID.length() > 0)) {
126             element.addAttribute("systemID", systemID);
127         }
128 
129         element.addText(e.getMessage());
130     }
131 }
132 
133 /*
134  * Redistribution and use of this software and associated documentation
135  * ("Software"), with or without modification, are permitted provided that the
136  * following conditions are met:
137  * 
138  * 1. Redistributions of source code must retain copyright statements and
139  * notices. Redistributions must also contain a copy of this document.
140  * 
141  * 2. Redistributions in binary form must reproduce the above copyright notice,
142  * this list of conditions and the following disclaimer in the documentation
143  * and/or other materials provided with the distribution.
144  * 
145  * 3. The name "DOM4J" must not be used to endorse or promote products derived
146  * from this Software without prior written permission of MetaStuff, Ltd. For
147  * written permission, please contact dom4j-info@metastuff.com.
148  * 
149  * 4. Products derived from this Software may not be called "DOM4J" nor may
150  * "DOM4J" appear in their names without prior written permission of MetaStuff,
151  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
152  * 
153  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
154  * 
155  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
156  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
157  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
158  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
159  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
160  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
161  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
162  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
163  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
164  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
165  * POSSIBILITY OF SUCH DAMAGE.
166  * 
167  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
168  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/util/NodeComparator.html0000644000175000017500000007133110242117622022346 0ustar ebourgebourg NodeComparator xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.util;
9   
10  import java.util.Comparator;
11  
12  import org.dom4j.Attribute;
13  import org.dom4j.Branch;
14  import org.dom4j.CDATA;
15  import org.dom4j.CharacterData;
16  import org.dom4j.Comment;
17  import org.dom4j.Document;
18  import org.dom4j.DocumentType;
19  import org.dom4j.Element;
20  import org.dom4j.Entity;
21  import org.dom4j.Namespace;
22  import org.dom4j.Node;
23  import org.dom4j.ProcessingInstruction;
24  import org.dom4j.QName;
25  import org.dom4j.Text;
26  
27  /***
28   * <p>
29   * <code>NodeComparator</code> is a {@link Comparator}of Node instances which
30   * is capable of comparing Nodes for equality based on their values.
31   * </p>
32   * 
33   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
34   * @version $Revision: 1.10 $
35   */
36  public class NodeComparator implements Comparator {
37      /***
38       * Compares its two arguments for order. Returns a negative integer, zero,
39       * or a positive integer as the first argument is less than, equal to, or
40       * greater than the second.
41       * 
42       * <p>
43       * The implementor must ensure that <tt>sgn(compare(x, y)) ==
44       * -sgn(compare(y, x))</tt>
45       * for all <tt>x</tt> and <tt>y</tt>. (This implies that
46       * <tt>compare(x, y)</tt> must throw an exception if and only if
47       * <tt>compare(y, x)</tt> throws an exception.)
48       * </p>
49       * 
50       * <p>
51       * The implementor must also ensure that the relation is transitive:
52       * <tt>((compare(x, y)&gt;0) &amp;&amp; (compare(y, z)&gt;0))</tt> implies
53       * <tt>compare(x, z)&gt;0</tt>.
54       * </p>
55       * 
56       * <p>
57       * Finally, the implementer must ensure that <tt>compare(x, y)==0</tt>
58       * implies that <tt>sgn(compare(x, z))==sgn(compare(y, z))</tt> for all
59       * <tt>z</tt>.
60       * </p>
61       * 
62       * <p>
63       * It is generally the case, but <i>not </i> strictly required that
64       * <tt>(compare(x, y)==0) == (x.equals(y))</tt>. Generally speaking, any
65       * comparator that violates this condition should clearly indicate this
66       * fact. The recommended language is "Note: this comparator imposes
67       * orderings that are inconsistent with equals."
68       * </p>
69       * 
70       * @param o1
71       *            the first object to be compared.
72       * @param o2
73       *            the second object to be compared.
74       * 
75       * @return a negative integer, zero, or a positive integer as the first
76       *         argument is less than, equal to, or greater than the second.
77       */
78      public int compare(Object o1, Object o2) {
79          if (o1 == o2) {
80              return 0;
81          } else if (o1 == null) {
82              // null is less
83              return -1;
84          } else if (o2 == null) {
85              return 1;
86          }
87  
88          if (o1 instanceof Node) {
89              if (o2 instanceof Node) {
90                  return compare((Node) o1, (Node) o2);
91              } else {
92                  // Node implementations are greater
93                  return 1;
94              }
95          } else {
96              if (o2 instanceof Node) {
97                  // Node implementations are greater
98                  return -1;
99              } else {
100                 if (o1 instanceof Comparable) {
101                     Comparable c1 = (Comparable) o1;
102 
103                     return c1.compareTo(o2);
104                 } else {
105                     String name1 = o1.getClass().getName();
106                     String name2 = o2.getClass().getName();
107 
108                     return name1.compareTo(name2);
109                 }
110             }
111         }
112     }
113 
114     public int compare(Node n1, Node n2) {
115         int nodeType1 = n1.getNodeType();
116         int nodeType2 = n2.getNodeType();
117         int answer = nodeType1 - nodeType2;
118 
119         if (answer != 0) {
120             return answer;
121         } else {
122             switch (nodeType1) {
123                 case Node.ELEMENT_NODE:
124                     return compare((Element) n1, (Element) n2);
125 
126                 case Node.DOCUMENT_NODE:
127                     return compare((Document) n1, (Document) n2);
128 
129                 case Node.ATTRIBUTE_NODE:
130                     return compare((Attribute) n1, (Attribute) n2);
131 
132                 case Node.TEXT_NODE:
133                     return compare((Text) n1, (Text) n2);
134 
135                 case Node.CDATA_SECTION_NODE:
136                     return compare((CDATA) n1, (CDATA) n2);
137 
138                 case Node.ENTITY_REFERENCE_NODE:
139                     return compare((Entity) n1, (Entity) n2);
140 
141                 case Node.PROCESSING_INSTRUCTION_NODE:
142                     return compare((ProcessingInstruction) n1,
143                             (ProcessingInstruction) n2);
144 
145                 case Node.COMMENT_NODE:
146                     return compare((Comment) n1, (Comment) n2);
147 
148                 case Node.DOCUMENT_TYPE_NODE:
149                     return compare((DocumentType) n1, (DocumentType) n2);
150 
151                 case Node.NAMESPACE_NODE:
152                     return compare((Namespace) n1, (Namespace) n2);
153 
154                 default:
155                     throw new RuntimeException("Invalid node types. node1: "
156                             + n1 + " and node2: " + n2);
157             }
158         }
159     }
160 
161     public int compare(Document n1, Document n2) {
162         int answer = compare(n1.getDocType(), n2.getDocType());
163 
164         if (answer == 0) {
165             answer = compareContent(n1, n2);
166         }
167 
168         return answer;
169     }
170 
171     public int compare(Element n1, Element n2) {
172         int answer = compare(n1.getQName(), n2.getQName());
173 
174         if (answer == 0) {
175             // lets compare attributes
176             int c1 = n1.attributeCount();
177             int c2 = n2.attributeCount();
178             answer = c1 - c2;
179 
180             if (answer == 0) {
181                 for (int i = 0; i < c1; i++) {
182                     Attribute a1 = n1.attribute(i);
183                     Attribute a2 = n2.attribute(a1.getQName());
184                     answer = compare(a1, a2);
185 
186                     if (answer != 0) {
187                         return answer;
188                     }
189                 }
190 
191                 answer = compareContent(n1, n2);
192             }
193         }
194 
195         return answer;
196     }
197 
198     public int compare(Attribute n1, Attribute n2) {
199         int answer = compare(n1.getQName(), n2.getQName());
200 
201         if (answer == 0) {
202             answer = compare(n1.getValue(), n2.getValue());
203         }
204 
205         return answer;
206     }
207 
208     public int compare(QName n1, QName n2) {
209         int answer = compare(n1.getNamespaceURI(), n2.getNamespaceURI());
210 
211         if (answer == 0) {
212             answer = compare(n1.getQualifiedName(), n2.getQualifiedName());
213         }
214 
215         return answer;
216     }
217 
218     public int compare(Namespace n1, Namespace n2) {
219         int answer = compare(n1.getURI(), n2.getURI());
220 
221         if (answer == 0) {
222             answer = compare(n1.getPrefix(), n2.getPrefix());
223         }
224 
225         return answer;
226     }
227 
228     public int compare(CharacterData t1, CharacterData t2) {
229         return compare(t1.getText(), t2.getText());
230     }
231 
232     public int compare(DocumentType o1, DocumentType o2) {
233         if (o1 == o2) {
234             return 0;
235         } else if (o1 == null) {
236             // null is less
237             return -1;
238         } else if (o2 == null) {
239             return 1;
240         }
241 
242         int answer = compare(o1.getPublicID(), o2.getPublicID());
243 
244         if (answer == 0) {
245             answer = compare(o1.getSystemID(), o2.getSystemID());
246 
247             if (answer == 0) {
248                 answer = compare(o1.getName(), o2.getName());
249             }
250         }
251 
252         return answer;
253     }
254 
255     public int compare(Entity n1, Entity n2) {
256         int answer = compare(n1.getName(), n2.getName());
257 
258         if (answer == 0) {
259             answer = compare(n1.getText(), n2.getText());
260         }
261 
262         return answer;
263     }
264 
265     public int compare(ProcessingInstruction n1, ProcessingInstruction n2) {
266         int answer = compare(n1.getTarget(), n2.getTarget());
267 
268         if (answer == 0) {
269             answer = compare(n1.getText(), n2.getText());
270         }
271 
272         return answer;
273     }
274 
275     public int compareContent(Branch b1, Branch b2) {
276         int c1 = b1.nodeCount();
277         int c2 = b2.nodeCount();
278         int answer = c1 - c2;
279 
280         if (answer == 0) {
281             for (int i = 0; i < c1; i++) {
282                 Node n1 = b1.node(i);
283                 Node n2 = b2.node(i);
284                 answer = compare(n1, n2);
285 
286                 if (answer != 0) {
287                     break;
288                 }
289             }
290         }
291 
292         return answer;
293     }
294 
295     public int compare(String o1, String o2) {
296         if (o1 == o2) {
297             return 0;
298         } else if (o1 == null) {
299             // null is less
300             return -1;
301         } else if (o2 == null) {
302             return 1;
303         }
304 
305         return o1.compareTo(o2);
306     }
307 }
308 
309 /*
310  * Redistribution and use of this software and associated documentation
311  * ("Software"), with or without modification, are permitted provided that the
312  * following conditions are met:
313  * 
314  * 1. Redistributions of source code must retain copyright statements and
315  * notices. Redistributions must also contain a copy of this document.
316  * 
317  * 2. Redistributions in binary form must reproduce the above copyright notice,
318  * this list of conditions and the following disclaimer in the documentation
319  * and/or other materials provided with the distribution.
320  * 
321  * 3. The name "DOM4J" must not be used to endorse or promote products derived
322  * from this Software without prior written permission of MetaStuff, Ltd. For
323  * written permission, please contact dom4j-info@metastuff.com.
324  * 
325  * 4. Products derived from this Software may not be called "DOM4J" nor may
326  * "DOM4J" appear in their names without prior written permission of MetaStuff,
327  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
328  * 
329  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
330  * 
331  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
332  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
333  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
334  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
335  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
336  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
337  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
338  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
339  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
340  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
341  * POSSIBILITY OF SUCH DAMAGE.
342  * 
343  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
344  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/XPath.html0000644000175000017500000007012010242117751017476 0ustar ebourgebourg XPath xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import java.util.List;
11  import java.util.Map;
12  
13  import org.jaxen.FunctionContext;
14  import org.jaxen.NamespaceContext;
15  import org.jaxen.VariableContext;
16  
17  /***
18   * <p>
19   * <code>XPath</code> represents an XPath expression after it has been parsed
20   * from a String.
21   * </p>
22   * 
23   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
24   * @version $Revision: 1.20 $
25   */
26  public interface XPath extends NodeFilter {
27      /***
28       * <p>
29       * <code>getText</code> will return the textual version of the XPath
30       * expression.
31       * </p>
32       * 
33       * @return the textual format of the XPath expression.
34       */
35      String getText();
36  
37      /***
38       * <p>
39       * <code>matches</code> returns true if the given node matches the XPath
40       * expression. To be more precise when evaluating this XPath expression on
41       * the given node the result set must include the node.
42       * </p>
43       * 
44       * @param node
45       *            DOCUMENT ME!
46       * 
47       * @return true if the given node matches this XPath expression
48       */
49      boolean matches(Node node);
50  
51      /***
52       * <p>
53       * <code>evaluate</code> evaluates an XPath expression and returns the
54       * result as an {@link Object}. The object returned can either be a {@link
55       * List} of {@link Node}instances, a {@link Node}instance, a {@link
56       * String} or a {@link Number}instance depending on the XPath expression.
57       * </p>
58       * 
59       * @param context
60       *            is either a node or a list of nodes on which to evalute the
61       *            XPath
62       * 
63       * @return the value of the XPath expression as a {@link List}of {@link
64       *         Node} instances, a {@link Node}instance, a {@link String}or a
65       *         {@link Number}instance depending on the XPath expression.
66       */
67      Object evaluate(Object context);
68  
69      /***
70       * <p>
71       * <code>selectObject</code> evaluates an XPath expression and returns the
72       * result as an {@link Object}. The object returned can either be a {@link
73       * List} of {@link Node}instances, a {@link Node}instance, a {@link
74       * String} or a {@link Number}instance depending on the XPath expression.
75       * </p>
76       * 
77       * @param context
78       *            is either a node or a list of nodes on which to evalute the
79       *            XPath
80       * 
81       * @return the value of the XPath expression as a {@link List}of {@link
82       *         Node} instances, a {@link Node}instance, a {@link String}or a
83       *         {@link Number}instance depending on the XPath expression.
84       * 
85       * @deprecated please use evaluate(Object) instead. WILL BE REMOVED IN
86       *             dom4j-1.6 !!
87       */
88      Object selectObject(Object context);
89  
90      /***
91       * <p>
92       * <code>selectNodes</code> performs this XPath expression on the given
93       * {@link Node}or {@link List}of {@link Node}s instances appending all
94       * the results together into a single list.
95       * </p>
96       * 
97       * @param context
98       *            is either a node or a list of nodes on which to evalute the
99       *            XPath
100      * 
101      * @return the results of all the XPath evaluations as a single list
102      */
103     List selectNodes(Object context);
104 
105     /***
106      * <p>
107      * <code>selectNodes</code> evaluates the XPath expression on the given
108      * {@link Node}or {@link List}of {@link Node}s and returns the result as
109      * a <code>List</code> of <code>Node</code> s sorted by the sort XPath
110      * expression.
111      * </p>
112      * 
113      * @param context
114      *            is either a node or a list of nodes on which to evalute the
115      *            XPath
116      * @param sortXPath
117      *            is the XPath expression to sort by
118      * 
119      * @return a list of <code>Node</code> instances
120      */
121     List selectNodes(Object context, XPath sortXPath);
122 
123     /***
124      * <p>
125      * <code>selectNodes</code> evaluates the XPath expression on the given
126      * {@link Node}or {@link List}of {@link Node}s and returns the result as
127      * a <code>List</code> of <code>Node</code> s sorted by the sort XPath
128      * expression.
129      * </p>
130      * 
131      * @param context
132      *            is either a node or a list of nodes on which to evalute the
133      *            XPath
134      * @param sortXPath
135      *            is the XPath expression to sort by
136      * @param distinct
137      *            specifies whether or not duplicate values of the sort
138      *            expression are allowed. If this parameter is true then only
139      *            distinct sort expressions values are included in the result
140      * 
141      * @return a list of <code>Node</code> instances
142      */
143     List selectNodes(Object context, XPath sortXPath, boolean distinct);
144 
145     /***
146      * <p>
147      * <code>selectSingleNode</code> evaluates this XPath expression on the
148      * given {@link Node}or {@link List}of {@link Node}s and returns the
149      * result as a single <code>Node</code> instance.
150      * </p>
151      * 
152      * @param context
153      *            is either a node or a list of nodes on which to evalute the
154      *            XPath
155      * 
156      * @return a single matching <code>Node</code> instance
157      */
158     Node selectSingleNode(Object context);
159 
160     /***
161      * <p>
162      * <code>valueOf</code> evaluates this XPath expression and returns the
163      * textual representation of the results using the XPath string() function.
164      * </p>
165      * 
166      * @param context
167      *            is either a node or a list of nodes on which to evalute the
168      *            XPath
169      * 
170      * @return the string representation of the results of the XPath expression
171      */
172     String valueOf(Object context);
173 
174     /***
175      * <p>
176      * <code>numberValueOf</code> evaluates an XPath expression and returns
177      * the numeric value of the XPath expression if the XPath expression results
178      * is a number, or null if the result is not a number.
179      * </p>
180      * 
181      * @param context
182      *            is either a node or a list of nodes on which to evalute the
183      *            XPath
184      * 
185      * @return the numeric result of the XPath expression or null if the result
186      *         is not a number.
187      */
188     Number numberValueOf(Object context);
189 
190     /***
191      * Retrieve a boolean-value interpretation of this XPath expression when
192      * evaluated against a given context.
193      * 
194      * <p>
195      * The boolean-value of the expression is determined per the
196      * <code>boolean(..)</code> core function as defined in the XPath
197      * specification. This means that an expression that selects zero nodes will
198      * return <code>false</code>, while an expression that selects
199      * one-or-more nodes will return <code>true</code>.
200      * </p>
201      * 
202      * @param context
203      *            The node, nodeset or Context object for evaluation. This value
204      *            can be null
205      * 
206      * @return The boolean-value interpretation of this expression.
207      * 
208      * @since 1.5
209      */
210     boolean booleanValueOf(Object context);
211 
212     /***
213      * <p>
214      * <code>sort</code> sorts the given List of Nodes using this XPath
215      * expression as a {@link java.util.Comparator}.
216      * </p>
217      * 
218      * @param list
219      *            is the list of Nodes to sort
220      */
221     void sort(List list);
222 
223     /***
224      * <p>
225      * <code>sort</code> sorts the given List of Nodes using this XPath
226      * expression as a {@link java.util.Comparator}and optionally removing
227      * duplicates.
228      * </p>
229      * 
230      * @param list
231      *            is the list of Nodes to sort
232      * @param distinct
233      *            if true then duplicate values (using the sortXPath for
234      *            comparisions) will be removed from the List
235      */
236     void sort(List list, boolean distinct);
237 
238     /***
239      * DOCUMENT ME!
240      * 
241      * @return the current function context
242      */
243     FunctionContext getFunctionContext();
244 
245     /***
246      * Sets the function context to be used when evaluating XPath expressions
247      * 
248      * @param functionContext
249      *            DOCUMENT ME!
250      */
251     void setFunctionContext(FunctionContext functionContext);
252 
253     /***
254      * DOCUMENT ME!
255      * 
256      * @return the current namespace context
257      */
258     NamespaceContext getNamespaceContext();
259 
260     /***
261      * Sets the namespace context to be used when evaluating XPath expressions
262      * 
263      * @param namespaceContext
264      *            DOCUMENT ME!
265      */
266     void setNamespaceContext(NamespaceContext namespaceContext);
267 
268     /***
269      * <p>
270      * Sets the current NamespaceContext from a Map where the keys are the
271      * String namespace prefixes and the values are the namespace URIs.
272      * </p>
273      * 
274      * <p>
275      * For example:
276      * 
277      * <pre>
278      * Map uris = new HashMap();
279      * uris.put("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/");
280      * uris.put("m", "urn:xmethodsBabelFish");
281      * XPath xpath = document
282      *         .createXPath("SOAP-ENV:Envelope/SOAP-ENV:Body/m:BabelFish");
283      * xpath.setNamespaceURIs(uris);
284      * Node babelfish = xpath.selectSingleNode(document);
285      * </pre>
286      * 
287      * </p>
288      * 
289      * @param map
290      *            the map containing the namespace mappings
291      */
292     void setNamespaceURIs(Map map);
293 
294     /***
295      * DOCUMENT ME!
296      * 
297      * @return the current variable context
298      */
299     VariableContext getVariableContext();
300 
301     /***
302      * Sets the variable context to be used when evaluating XPath expressions
303      * 
304      * @param variableContext
305      *            DOCUMENT ME!
306      */
307     void setVariableContext(VariableContext variableContext);
308 }
309 
310 /*
311  * Redistribution and use of this software and associated documentation
312  * ("Software"), with or without modification, are permitted provided that the
313  * following conditions are met:
314  * 
315  * 1. Redistributions of source code must retain copyright statements and
316  * notices. Redistributions must also contain a copy of this document.
317  * 
318  * 2. Redistributions in binary form must reproduce the above copyright notice,
319  * this list of conditions and the following disclaimer in the documentation
320  * and/or other materials provided with the distribution.
321  * 
322  * 3. The name "DOM4J" must not be used to endorse or promote products derived
323  * from this Software without prior written permission of MetaStuff, Ltd. For
324  * written permission, please contact dom4j-info@metastuff.com.
325  * 
326  * 4. Products derived from this Software may not be called "DOM4J" nor may
327  * "DOM4J" appear in their names without prior written permission of MetaStuff,
328  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
329  * 
330  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
331  * 
332  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
333  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
334  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
335  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
336  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
337  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
338  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
339  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
340  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
341  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
342  * POSSIBILITY OF SUCH DAMAGE.
343  * 
344  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
345  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/ElementHandler.html0000644000175000017500000001742610242117761021354 0ustar ebourgebourg ElementHandler xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  /***
11   * <p>
12   * <code>ElementHandler</code> interface defines a handler of
13   * <code>Element</code> objects. It is used primarily in event based
14   * processing models such as for processing large XML documents as they are
15   * being parsed rather than waiting until the whole document is parsed.
16   * </p>
17   * 
18   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
19   * @version $Revision: 1.8 $
20   */
21  public interface ElementHandler {
22      /***
23       * Called by an event based processor when an elements openning tag is
24       * encountered.
25       * 
26       * @param elementPath
27       *            is the current <code>ElementPath</code> to process
28       */
29      void onStart(ElementPath elementPath);
30  
31      /***
32       * Called by an event based processor when an elements closing tag is
33       * encountered.
34       * 
35       * @param elementPath
36       *            is the current <code>ElementPath</code> to process
37       */
38      void onEnd(ElementPath elementPath);
39  }
40  
41  /*
42   * Redistribution and use of this software and associated documentation
43   * ("Software"), with or without modification, are permitted provided that the
44   * following conditions are met:
45   * 
46   * 1. Redistributions of source code must retain copyright statements and
47   * notices. Redistributions must also contain a copy of this document.
48   * 
49   * 2. Redistributions in binary form must reproduce the above copyright notice,
50   * this list of conditions and the following disclaimer in the documentation
51   * and/or other materials provided with the distribution.
52   * 
53   * 3. The name "DOM4J" must not be used to endorse or promote products derived
54   * from this Software without prior written permission of MetaStuff, Ltd. For
55   * written permission, please contact dom4j-info@metastuff.com.
56   * 
57   * 4. Products derived from this Software may not be called "DOM4J" nor may
58   * "DOM4J" appear in their names without prior written permission of MetaStuff,
59   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
60   * 
61   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
62   * 
63   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
64   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
65   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
66   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
67   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
68   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
69   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
70   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
71   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
72   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
73   * POSSIBILITY OF SUCH DAMAGE.
74   * 
75   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
76   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/Attribute.html0000644000175000017500000003511410242117727020424 0ustar ebourgebourg Attribute xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  /***
11   * <p>
12   * <code>Attribute</code> defines an XML attribute. An attribute may have a
13   * name, an optional namespace and a value.
14   * </p>
15   * 
16   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
17   * @version $Revision: 1.9 $
18   */
19  public interface Attribute extends Node {
20      /***
21       * <p>
22       * Returns the <code>QName</code> of this attribute which represents the
23       * local name, the qualified name and the <code>Namespace</code>.
24       * </p>
25       * 
26       * @return the <code>QName</code> associated with this attribute
27       */
28      QName getQName();
29  
30      /***
31       * <p>
32       * Returns the <code>Namespace</code> of this element if one exists
33       * otherwise null is returned returned.
34       * </p>
35       * 
36       * @return the <code>Namespace</code> associated with this node
37       */
38      Namespace getNamespace();
39  
40      /***
41       * <p>
42       * Sets the <code>Namespace</code> of this element or if this element is
43       * read only then an <code>UnsupportedOperationException</code> is thrown.
44       * </p>
45       * 
46       * @param namespace
47       *            is the <code>Namespace</code> to associate with this element
48       */
49      void setNamespace(Namespace namespace);
50  
51      /***
52       * <p>
53       * Returns the namespace prefix of this element if one exists otherwise an
54       * empty <code>String</code> is returned.
55       * </p>
56       * 
57       * @return the prefix of the <code>Namespace</code> of this element or an
58       *         empty <code>String</code>
59       */
60      String getNamespacePrefix();
61  
62      /***
63       * <p>
64       * Returns the URI mapped to the namespace of this element if one exists
65       * otherwise an empty <code>String</code> is returned.
66       * </p>
67       * 
68       * @return the URI for the <code>Namespace</code> of this element or an
69       *         empty <code>String</code>
70       */
71      String getNamespaceURI();
72  
73      /***
74       * <p>
75       * Returns the fully qualified name of this element.
76       * </p>
77       * 
78       * <p>
79       * This will be the same as the value returned from {@link Node#getName()}
80       * if this element has no namespace attached to this element or an
81       * expression of the form
82       * 
83       * <pre>
84       * getNamespacePrefix() + &quot;:&quot; + getName()
85       * </pre>
86       * 
87       * will be returned.
88       * </p>
89       * 
90       * @return the fully qualified name of the element
91       */
92      String getQualifiedName();
93  
94      /***
95       * <p>
96       * Returns the value of the attribute. This method returns the same value as
97       * the {@link Node#getText()}method.
98       * </p>
99       * 
100      * @return the value of the attribute
101      */
102     String getValue();
103 
104     /***
105      * <p>
106      * Sets the value of this attribute or this method will throw an
107      * <code>UnsupportedOperationException</code> if it is read-only.
108      * </p>
109      * 
110      * @param value
111      *            is the new value of this attribute
112      */
113     void setValue(String value);
114 
115     /***
116      * <p>
117      * Accesses the data of this attribute which may implement data typing
118      * bindings such as <code>XML Schema</code> or <code>Java Bean</code>
119      * bindings or will return the same value as {@link Node#getText()}.
120      * </p>
121      * 
122      * @return the attribute data
123      */
124     Object getData();
125 
126     /***
127      * <p>
128      * Sets the data value of this attribute if this element supports data
129      * binding or calls {@link Node#setText(String)}if it doesn't.
130      * </p>
131      * 
132      * @param data
133      *            the attribute data
134      */
135     void setData(Object data);
136 }
137 
138 /*
139  * Redistribution and use of this software and associated documentation
140  * ("Software"), with or without modification, are permitted provided that the
141  * following conditions are met:
142  * 
143  * 1. Redistributions of source code must retain copyright statements and
144  * notices. Redistributions must also contain a copy of this document.
145  * 
146  * 2. Redistributions in binary form must reproduce the above copyright notice,
147  * this list of conditions and the following disclaimer in the documentation
148  * and/or other materials provided with the distribution.
149  * 
150  * 3. The name "DOM4J" must not be used to endorse or promote products derived
151  * from this Software without prior written permission of MetaStuff, Ltd. For
152  * written permission, please contact dom4j-info@metastuff.com.
153  * 
154  * 4. Products derived from this Software may not be called "DOM4J" nor may
155  * "DOM4J" appear in their names without prior written permission of MetaStuff,
156  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
157  * 
158  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
159  * 
160  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
161  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
162  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
163  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
164  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
165  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
166  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
167  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
168  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
169  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
170  * POSSIBILITY OF SUCH DAMAGE.
171  * 
172  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
173  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/Branch.html0000644000175000017500000007303610242117737017664 0ustar ebourgebourg Branch xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import java.util.Iterator;
11  import java.util.List;
12  
13  /***
14   * <p>
15   * <code>Branch</code> interface defines the common behaviour for Nodes which
16   * can contain child nodes (content) such as XML elements and documents. This
17   * interface allows both elements and documents to be treated in a polymorphic
18   * manner when changing or navigating child nodes (content).
19   * </p>
20   * 
21   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
22   * @version $Revision: 1.32 $
23   */
24  public interface Branch extends Node {
25      /***
26       * Returns the <code>Node</code> at the specified index position.
27       * 
28       * @param index
29       *            the index of the node to return.
30       * 
31       * @return the <code>Node</code> at the specified position.
32       * 
33       * @throws IndexOutOfBoundsException
34       *             if the index is out of range (index &lt; 0 || index &gt;=
35       *             {@link Branch#nodeCount()}).
36       */
37      Node node(int index) throws IndexOutOfBoundsException;
38  
39      /***
40       * Returns the index of the given node if it is a child node of this branch
41       * or -1 if the given node is not a child node.
42       * 
43       * @param node
44       *            the content child node to find.
45       * 
46       * @return the index of the given node starting at 0 or -1 if the node is
47       *         not a child node of this branch
48       */
49      int indexOf(Node node);
50  
51      /***
52       * Returns the number of <code>Node</code> instances that this branch
53       * contains.
54       * 
55       * @return the number of nodes this branch contains
56       */
57      int nodeCount();
58  
59      /***
60       * Returns the element of the given ID attribute value. If this tree is
61       * capable of understanding which attribute value should be used for the ID
62       * then it should be used, otherwise this method should return null.
63       * 
64       * @param elementID
65       *            DOCUMENT ME!
66       * 
67       * @return DOCUMENT ME!
68       */
69      Element elementByID(String elementID);
70  
71      /***
72       * <p>
73       * Returns the content nodes of this branch as a backed {@link List}so that
74       * the content of this branch may be modified directly using the
75       * {@link List}interface. The <code>List</code> is backed by the
76       * <code>Branch</code> so that changes to the list are reflected in the
77       * branch and vice versa.
78       * </p>
79       * 
80       * @return the nodes that this branch contains as a <code>List</code>
81       */
82      List content();
83  
84      /***
85       * Returns an iterator through the content nodes of this branch
86       * 
87       * @return an iterator through the content nodes of this branch
88       */
89      Iterator nodeIterator();
90  
91      /***
92       * Sets the contents of this branch as a <code>List</code> of
93       * <code>Node</code> instances.
94       * 
95       * @param content
96       *            is the list of nodes to use as the content for this branch.
97       */
98      void setContent(List content);
99  
100     /***
101      * Appends the content of the given branch to this branch instance. This
102      * method behaves like the {@link
103      * java.util.Collection#addAll(java.util.Collection)} method.
104      * 
105      * @param branch
106      *            is the branch whose content will be added to me.
107      */
108     void appendContent(Branch branch);
109 
110     /***
111      * Clears the content for this branch, removing any <code>Node</code>
112      * instances this branch may contain.
113      */
114     void clearContent();
115 
116     /***
117      * <p>
118      * Returns a list of all the processing instructions in this branch. The
119      * list is backed by this branch so that changes to the list will be
120      * reflected in the branch but the reverse is not the case.
121      * </p>
122      * 
123      * @return a backed list of the processing instructions
124      */
125     List processingInstructions();
126 
127     /***
128      * <p>
129      * Returns a list of the processing instructions for the given target. The
130      * list is backed by this branch so that changes to the list will be
131      * reflected in the branch but the reverse is not the case.
132      * </p>
133      * 
134      * @param target
135      *            DOCUMENT ME!
136      * 
137      * @return a backed list of the processing instructions
138      */
139     List processingInstructions(String target);
140 
141     /***
142      * DOCUMENT ME!
143      * 
144      * @param target
145      *            DOCUMENT ME!
146      * 
147      * @return the processing instruction for the given target
148      */
149     ProcessingInstruction processingInstruction(String target);
150 
151     /***
152      * Sets all the processing instructions for this branch
153      * 
154      * @param listOfPIs
155      *            DOCUMENT ME!
156      */
157     void setProcessingInstructions(List listOfPIs);
158 
159     /***
160      * Adds a new <code>Element</code> node with the given name to this branch
161      * and returns a reference to the new node.
162      * 
163      * @param name
164      *            is the name for the <code>Element</code> node.
165      * 
166      * @return the newly added <code>Element</code> node.
167      */
168     Element addElement(String name);
169 
170     /***
171      * Adds a new <code>Element</code> node with the given {@link QName}to
172      * this branch and returns a reference to the new node.
173      * 
174      * @param qname
175      *            is the qualified name for the <code>Element</code> node.
176      * 
177      * @return the newly added <code>Element</code> node.
178      */
179     Element addElement(QName qname);
180 
181     /***
182      * Adds a new <code>Element</code> node with the given qualified name and
183      * namespace URI to this branch and returns a reference to the new node.
184      * 
185      * @param qualifiedName
186      *            is the fully qualified name of the Element
187      * @param namespaceURI
188      *            is the URI of the namespace to use
189      * 
190      * @return the newly added <code>Element</code> node.
191      */
192     Element addElement(String qualifiedName, String namespaceURI);
193 
194     /***
195      * Removes the processing instruction for the given target if it exists
196      * 
197      * @param target
198      *            DOCUMENT ME!
199      * 
200      * @return true if a processing instruction was removed else false
201      */
202     boolean removeProcessingInstruction(String target);
203 
204     /***
205      * Adds the given <code>Node</code> or throws {@link IllegalAddException}
206      * if the given node is not of a valid type. This is a polymorphic method
207      * which will call the typesafe method for the node type such as
208      * add(Element) or add(Comment).
209      * 
210      * @param node
211      *            is the given node to add
212      */
213     void add(Node node);
214 
215     /***
216      * Adds the given <code>Comment</code> to this branch. If the given node
217      * already has a parent defined then an <code>IllegalAddException</code>
218      * will be thrown.
219      * 
220      * @param comment
221      *            is the comment to be added
222      */
223     void add(Comment comment);
224 
225     /***
226      * Adds the given <code>Element</code> to this branch. If the given node
227      * already has a parent defined then an <code>IllegalAddException</code>
228      * will be thrown.
229      * 
230      * @param element
231      *            is the element to be added
232      */
233     void add(Element element);
234 
235     /***
236      * Adds the given <code>ProcessingInstruction</code> to this branch. If
237      * the given node already has a parent defined then an
238      * <code>IllegalAddException</code> will be thrown.
239      * 
240      * @param pi
241      *            is the processing instruction to be added
242      */
243     void add(ProcessingInstruction pi);
244 
245     /***
246      * Removes the given <code>Node</code> if the node is an immediate child
247      * of this branch. If the given node is not an immediate child of this
248      * branch then the {@link Node#detach()}method should be used instead. This
249      * is a polymorphic method which will call the typesafe method for the node
250      * type such as remove(Element) or remove(Comment).
251      * 
252      * @param node
253      *            is the given node to be removed
254      * 
255      * @return true if the node was removed
256      */
257     boolean remove(Node node);
258 
259     /***
260      * Removes the given <code>Comment</code> if the node is an immediate
261      * child of this branch. If the given node is not an immediate child of this
262      * branch then the {@link Node#detach()}method should be used instead.
263      * 
264      * @param comment
265      *            is the comment to be removed
266      * 
267      * @return true if the comment was removed
268      */
269     boolean remove(Comment comment);
270 
271     /***
272      * Removes the given <code>Element</code> if the node is an immediate
273      * child of this branch. If the given node is not an immediate child of this
274      * branch then the {@link Node#detach()}method should be used instead.
275      * 
276      * @param element
277      *            is the element to be removed
278      * 
279      * @return true if the element was removed
280      */
281     boolean remove(Element element);
282 
283     /***
284      * Removes the given <code>ProcessingInstruction</code> if the node is an
285      * immediate child of this branch. If the given node is not an immediate
286      * child of this branch then the {@link Node#detach()}method should be used
287      * instead.
288      * 
289      * @param pi
290      *            is the processing instruction to be removed
291      * 
292      * @return true if the processing instruction was removed
293      */
294     boolean remove(ProcessingInstruction pi);
295 
296     /***
297      * Puts all <code>Text</code> nodes in the full depth of the sub-tree
298      * underneath this <code>Node</code>, including attribute nodes, into a
299      * "normal" form where only structure (e.g., elements, comments, processing
300      * instructions, CDATA sections, and entity references) separates
301      * <code>Text</code> nodes, i.e., there are neither adjacent
302      * <code>Text</code> nodes nor empty <code>Text</code> nodes. This can
303      * be used to ensure that the DOM view of a document is the same as if it
304      * were saved and re-loaded, and is useful when operations (such as XPointer
305      * lookups) that depend on a particular document tree structure are to be
306      * used.In cases where the document contains <code>CDATASections</code>,
307      * the normalize operation alone may not be sufficient, since XPointers do
308      * not differentiate between <code>Text</code> nodes and
309      * <code>CDATASection</code> nodes.
310      * 
311      * @since DOM Level 2
312      */
313     void normalize();
314 }
315 
316 /*
317  * Redistribution and use of this software and associated documentation
318  * ("Software"), with or without modification, are permitted provided that the
319  * following conditions are met:
320  * 
321  * 1. Redistributions of source code must retain copyright statements and
322  * notices. Redistributions must also contain a copy of this document.
323  * 
324  * 2. Redistributions in binary form must reproduce the above copyright notice,
325  * this list of conditions and the following disclaimer in the documentation
326  * and/or other materials provided with the distribution.
327  * 
328  * 3. The name "DOM4J" must not be used to endorse or promote products derived
329  * from this Software without prior written permission of MetaStuff, Ltd. For
330  * written permission, please contact dom4j-info@metastuff.com.
331  * 
332  * 4. Products derived from this Software may not be called "DOM4J" nor may
333  * "DOM4J" appear in their names without prior written permission of MetaStuff,
334  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
335  * 
336  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
337  * 
338  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
339  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
340  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
341  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
342  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
343  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
344  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
345  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
346  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
347  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
348  * POSSIBILITY OF SUCH DAMAGE.
349  * 
350  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
351  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/Entity.html0000644000175000017500000001420010242117753017725 0ustar ebourgebourg Entity xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  /***
11   * <p>
12   * <code>Entity</code> defines an XML entity.
13   * </p>
14   * 
15   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
16   * @version $Revision: 1.7 $
17   */
18  public interface Entity extends Node {
19  }
20  
21  /*
22   * Redistribution and use of this software and associated documentation
23   * ("Software"), with or without modification, are permitted provided that the
24   * following conditions are met:
25   * 
26   * 1. Redistributions of source code must retain copyright statements and
27   * notices. Redistributions must also contain a copy of this document.
28   * 
29   * 2. Redistributions in binary form must reproduce the above copyright notice,
30   * this list of conditions and the following disclaimer in the documentation
31   * and/or other materials provided with the distribution.
32   * 
33   * 3. The name "DOM4J" must not be used to endorse or promote products derived
34   * from this Software without prior written permission of MetaStuff, Ltd. For
35   * written permission, please contact dom4j-info@metastuff.com.
36   * 
37   * 4. Products derived from this Software may not be called "DOM4J" nor may
38   * "DOM4J" appear in their names without prior written permission of MetaStuff,
39   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
40   * 
41   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
42   * 
43   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
44   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
47   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
48   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
49   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
50   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
51   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
52   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
53   * POSSIBILITY OF SUCH DAMAGE.
54   * 
55   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
56   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/DocumentHelper.html0000644000175000017500000010553010242117746021400 0ustar ebourgebourg DocumentHelper xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import java.io.StringReader;
11  import java.util.List;
12  import java.util.Map;
13  import java.util.StringTokenizer;
14  
15  import org.dom4j.io.SAXReader;
16  import org.dom4j.rule.Pattern;
17  
18  import org.jaxen.VariableContext;
19  
20  import org.xml.sax.InputSource;
21  
22  /***
23   * <p>
24   * <code>DocumentHelper</code> is a collection of helper methods for using
25   * DOM4J.
26   * </p>
27   * 
28   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
29   * @version $Revision: 1.26 $
30   */
31  public final class DocumentHelper {
32      private DocumentHelper() {
33      }
34  
35      private static DocumentFactory getDocumentFactory() {
36          return DocumentFactory.getInstance();
37      }
38  
39      // Static helper methods
40      public static Document createDocument() {
41          return getDocumentFactory().createDocument();
42      }
43  
44      public static Document createDocument(Element rootElement) {
45          return getDocumentFactory().createDocument(rootElement);
46      }
47  
48      public static Element createElement(QName qname) {
49          return getDocumentFactory().createElement(qname);
50      }
51  
52      public static Element createElement(String name) {
53          return getDocumentFactory().createElement(name);
54      }
55  
56      public static Attribute createAttribute(Element owner, QName qname,
57              String value) {
58          return getDocumentFactory().createAttribute(owner, qname, value);
59      }
60  
61      public static Attribute createAttribute(Element owner, String name,
62              String value) {
63          return getDocumentFactory().createAttribute(owner, name, value);
64      }
65  
66      public static CDATA createCDATA(String text) {
67          return DocumentFactory.getInstance().createCDATA(text);
68      }
69  
70      public static Comment createComment(String text) {
71          return DocumentFactory.getInstance().createComment(text);
72      }
73  
74      public static Text createText(String text) {
75          return DocumentFactory.getInstance().createText(text);
76      }
77  
78      public static Entity createEntity(String name, String text) {
79          return DocumentFactory.getInstance().createEntity(name, text);
80      }
81  
82      public static Namespace createNamespace(String prefix, String uri) {
83          return DocumentFactory.getInstance().createNamespace(prefix, uri);
84      }
85  
86      public static ProcessingInstruction createProcessingInstruction(String pi,
87              String d) {
88          return getDocumentFactory().createProcessingInstruction(pi, d);
89      }
90  
91      public static ProcessingInstruction createProcessingInstruction(String pi,
92              Map data) {
93          return getDocumentFactory().createProcessingInstruction(pi, data);
94      }
95  
96      public static QName createQName(String localName, Namespace namespace) {
97          return getDocumentFactory().createQName(localName, namespace);
98      }
99  
100     public static QName createQName(String localName) {
101         return getDocumentFactory().createQName(localName);
102     }
103 
104     /***
105      * <p>
106      * <code>createXPath</code> parses an XPath expression and creates a new
107      * XPath <code>XPath</code> instance using the singleton {@link
108      * DocumentFactory}.
109      * </p>
110      * 
111      * @param xpathExpression
112      *            is the XPath expression to create
113      * 
114      * @return a new <code>XPath</code> instance
115      * 
116      * @throws InvalidXPathException
117      *             if the XPath expression is invalid
118      */
119     public static XPath createXPath(String xpathExpression)
120             throws InvalidXPathException {
121         return getDocumentFactory().createXPath(xpathExpression);
122     }
123 
124     /***
125      * <p>
126      * <code>createXPath</code> parses an XPath expression and creates a new
127      * XPath <code>XPath</code> instance using the singleton {@link
128      * DocumentFactory}.
129      * </p>
130      * 
131      * @param xpathExpression
132      *            is the XPath expression to create
133      * @param context
134      *            is the variable context to use when evaluating the XPath
135      * 
136      * @return a new <code>XPath</code> instance
137      * 
138      * @throws InvalidXPathException
139      *             if the XPath expression is invalid
140      */
141     public static XPath createXPath(String xpathExpression,
142             VariableContext context) throws InvalidXPathException {
143         return getDocumentFactory().createXPath(xpathExpression, context);
144     }
145 
146     /***
147      * <p>
148      * <code>createXPathFilter</code> parses a NodeFilter from the given XPath
149      * filter expression using the singleton {@link DocumentFactory}. XPath
150      * filter expressions occur within XPath expressions such as
151      * <code>self::node()[ filterExpression ]</code>
152      * </p>
153      * 
154      * @param xpathFilterExpression
155      *            is the XPath filter expression to create
156      * 
157      * @return a new <code>NodeFilter</code> instance
158      */
159     public static NodeFilter createXPathFilter(String xpathFilterExpression) {
160         return getDocumentFactory().createXPathFilter(xpathFilterExpression);
161     }
162 
163     /***
164      * <p>
165      * <code>createPattern</code> parses the given XPath expression to create
166      * an XSLT style {@link Pattern}instance which can then be used in an XSLT
167      * processing model.
168      * </p>
169      * 
170      * @param xpathPattern
171      *            is the XPath pattern expression to create
172      * 
173      * @return a new <code>Pattern</code> instance
174      */
175     public static Pattern createPattern(String xpathPattern) {
176         return getDocumentFactory().createPattern(xpathPattern);
177     }
178 
179     /***
180      * <p>
181      * <code>selectNodes</code> performs the given XPath expression on the
182      * {@link List}of {@link Node}instances appending all the results together
183      * into a single list.
184      * </p>
185      * 
186      * @param xpathFilterExpression
187      *            is the XPath filter expression to evaluate
188      * @param nodes
189      *            is the list of nodes on which to evalute the XPath
190      * 
191      * @return the results of all the XPath evaluations as a single list
192      */
193     public static List selectNodes(String xpathFilterExpression, List nodes) {
194         XPath xpath = createXPath(xpathFilterExpression);
195 
196         return xpath.selectNodes(nodes);
197     }
198 
199     /***
200      * <p>
201      * <code>selectNodes</code> performs the given XPath expression on the
202      * {@link List}of {@link Node}instances appending all the results together
203      * into a single list.
204      * </p>
205      * 
206      * @param xpathFilterExpression
207      *            is the XPath filter expression to evaluate
208      * @param node
209      *            is the Node on which to evalute the XPath
210      * 
211      * @return the results of all the XPath evaluations as a single list
212      */
213     public static List selectNodes(String xpathFilterExpression, Node node) {
214         XPath xpath = createXPath(xpathFilterExpression);
215 
216         return xpath.selectNodes(node);
217     }
218 
219     /***
220      * <p>
221      * <code>sort</code> sorts the given List of Nodes using an XPath
222      * expression as a {@link java.util.Comparator}.
223      * </p>
224      * 
225      * @param list
226      *            is the list of Nodes to sort
227      * @param xpathExpression
228      *            is the XPath expression used for comparison
229      */
230     public static void sort(List list, String xpathExpression) {
231         XPath xpath = createXPath(xpathExpression);
232         xpath.sort(list);
233     }
234 
235     /***
236      * <p>
237      * <code>sort</code> sorts the given List of Nodes using an XPath
238      * expression as a {@link java.util.Comparator}and optionally removing
239      * duplicates.
240      * </p>
241      * 
242      * @param list
243      *            is the list of Nodes to sort
244      * @param expression
245      *            is the XPath expression used for comparison
246      * @param distinct
247      *            if true then duplicate values (using the sortXPath for
248      *            comparisions) will be removed from the List
249      */
250     public static void sort(List list, String expression, boolean distinct) {
251         XPath xpath = createXPath(expression);
252         xpath.sort(list, distinct);
253     }
254 
255     /***
256      * <p>
257      * <code>parseText</code> parses the given text as an XML document and
258      * returns the newly created Document.
259      * </p>
260      * 
261      * @param text
262      *            the XML text to be parsed
263      * 
264      * @return a newly parsed Document
265      * 
266      * @throws DocumentException
267      *             if the document could not be parsed
268      */
269     public static Document parseText(String text) throws DocumentException {
270         Document result = null;
271 
272         SAXReader reader = new SAXReader();
273         String encoding = getEncoding(text);
274 
275         InputSource source = new InputSource(new StringReader(text));
276         source.setEncoding(encoding);
277 
278         result = reader.read(source);
279 
280         // if the XML parser doesn't provide a way to retrieve the encoding,
281         // specify it manually
282         if (result.getXMLEncoding() == null) {
283             result.setXMLEncoding(encoding);
284         }
285 
286         return result;
287     }
288 
289     private static String getEncoding(String text) {
290         String result = null;
291 
292         String xml = text.trim();
293 
294         if (xml.startsWith("<?xml")) {
295             int end = xml.indexOf("?>");
296             String sub = xml.substring(0, end);
297             StringTokenizer tokens = new StringTokenizer(sub, " =\"\'");
298 
299             while (tokens.hasMoreTokens()) {
300                 String token = tokens.nextToken();
301 
302                 if ("encoding".equals(token)) {
303                     if (tokens.hasMoreTokens()) {
304                         result = tokens.nextToken();
305                     }
306 
307                     break;
308                 }
309             }
310         }
311 
312         return result;
313     }
314 
315     /***
316      * <p>
317      * makeElement
318      * </p>
319      * a helper method which navigates from the given Document or Element node
320      * to some Element using the path expression, creating any necessary
321      * elements along the way. For example the path <code>a/b/c</code> would
322      * get the first child &lt;a&gt; element, which would be created if it did
323      * not exist, then the next child &lt;b&gt; and so on until finally a
324      * &lt;c&gt; element is returned.
325      * 
326      * @param source
327      *            is the Element or Document to start navigating from
328      * @param path
329      *            is a simple path expression, seperated by '/' which denotes
330      *            the path from the source to the resulting element such as
331      *            a/b/c
332      * 
333      * @return the first Element on the given path which either already existed
334      *         on the path or were created by this method.
335      */
336     public static Element makeElement(Branch source, String path) {
337         StringTokenizer tokens = new StringTokenizer(path, "/");
338         Element parent;
339 
340         if (source instanceof Document) {
341             Document document = (Document) source;
342             parent = document.getRootElement();
343 
344             // lets throw a NoSuchElementException
345             // if we are given an empty path
346             String name = tokens.nextToken();
347 
348             if (parent == null) {
349                 parent = document.addElement(name);
350             }
351         } else {
352             parent = (Element) source;
353         }
354 
355         Element element = null;
356 
357         while (tokens.hasMoreTokens()) {
358             String name = tokens.nextToken();
359 
360             if (name.indexOf(':') > 0) {
361                 element = parent.element(parent.getQName(name));
362             } else {
363                 element = parent.element(name);
364             }
365 
366             if (element == null) {
367                 element = parent.addElement(name);
368             }
369 
370             parent = element;
371         }
372 
373         return element;
374     }
375 }
376 
377 /*
378  * Redistribution and use of this software and associated documentation
379  * ("Software"), with or without modification, are permitted provided that the
380  * following conditions are met:
381  * 
382  * 1. Redistributions of source code must retain copyright statements and
383  * notices. Redistributions must also contain a copy of this document.
384  * 
385  * 2. Redistributions in binary form must reproduce the above copyright notice,
386  * this list of conditions and the following disclaimer in the documentation
387  * and/or other materials provided with the distribution.
388  * 
389  * 3. The name "DOM4J" must not be used to endorse or promote products derived
390  * from this Software without prior written permission of MetaStuff, Ltd. For
391  * written permission, please contact dom4j-info@metastuff.com.
392  * 
393  * 4. Products derived from this Software may not be called "DOM4J" nor may
394  * "DOM4J" appear in their names without prior written permission of MetaStuff,
395  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
396  * 
397  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
398  * 
399  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
400  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
401  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
402  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
403  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
404  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
405  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
406  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
407  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
408  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
409  * POSSIBILITY OF SUCH DAMAGE.
410  * 
411  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
412  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/ProcessingInstruction.html0000644000175000017500000002326310242117631023033 0ustar ebourgebourg ProcessingInstruction xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  import java.util.Map;
11  
12  /***
13   * <p>
14   * <code>ProcessingInstruction</code> defines an XML processing instruction.
15   * The {@link Node#getName}method will return the target of the PI and the
16   * {@link Node#getText}method will return the data from all of the
17   * instructions.
18   * </p>
19   * 
20   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
21   * @version $Revision: 1.10 $
22   */
23  public interface ProcessingInstruction extends Node {
24      /***
25       * This method is the equivalent to the {@link #getName}method. It is added
26       * for clarity.
27       * 
28       * @return the target of this PI
29       */
30      String getTarget();
31  
32      /***
33       * This method is the equivalent to the {@link #setName}method. It is added
34       * for clarity.
35       * 
36       * @param target
37       *            DOCUMENT ME!
38       */
39      void setTarget(String target);
40  
41      /***
42       * DOCUMENT ME!
43       * 
44       * @return the text for all the data associated with the processing
45       *         instruction
46       */
47      String getText();
48  
49      /***
50       * <p>
51       * Returns the value of a specific name in the PI.
52       * </p>
53       * 
54       * @param name
55       *            is the name of the attribute to lookup.
56       * 
57       * @return the value of the named attribute
58       */
59      String getValue(String name);
60  
61      /***
62       * DOCUMENT ME!
63       * 
64       * @return the values for this processing instruction as a Map
65       */
66      Map getValues();
67  
68      void setValue(String name, String value);
69  
70      void setValues(Map data);
71  
72      boolean removeValue(String name);
73  }
74  
75  /*
76   * Redistribution and use of this software and associated documentation
77   * ("Software"), with or without modification, are permitted provided that the
78   * following conditions are met:
79   * 
80   * 1. Redistributions of source code must retain copyright statements and
81   * notices. Redistributions must also contain a copy of this document.
82   * 
83   * 2. Redistributions in binary form must reproduce the above copyright notice,
84   * this list of conditions and the following disclaimer in the documentation
85   * and/or other materials provided with the distribution.
86   * 
87   * 3. The name "DOM4J" must not be used to endorse or promote products derived
88   * from this Software without prior written permission of MetaStuff, Ltd. For
89   * written permission, please contact dom4j-info@metastuff.com.
90   * 
91   * 4. Products derived from this Software may not be called "DOM4J" nor may
92   * "DOM4J" appear in their names without prior written permission of MetaStuff,
93   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
94   * 
95   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
96   * 
97   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
98   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
99   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
100  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
101  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
102  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
103  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
104  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
105  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
106  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
107  * POSSIBILITY OF SUCH DAMAGE.
108  * 
109  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
110  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dtd/0000755000175000017500000000000012133227266016343 5ustar ebourgebourgdom4j-1.6.1/docs/xref/org/dom4j/dtd/ExternalEntityDecl.html0000644000175000017500000003276210242117755023012 0ustar ebourgebourg ExternalEntityDecl xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dtd;
9   
10  /***
11   * <p>
12   * <code>ExternalEntityDecl</code> represents an external entity declaration
13   * in a DTD.
14   * </p>
15   * 
16   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
17   * @version $Revision: 1.9 $
18   */
19  public class ExternalEntityDecl {
20      /*** Holds value of property name. */
21      private String name;
22  
23      /*** Holds value of property publicID. */
24      private String publicID;
25  
26      /*** Holds value of property systemID. */
27      private String systemID;
28  
29      public ExternalEntityDecl() {
30      }
31  
32      public ExternalEntityDecl(String name, String publicID, String systemID) {
33          this.name = name;
34          this.publicID = publicID;
35          this.systemID = systemID;
36      }
37  
38      /***
39       * Getter for property name.
40       * 
41       * @return Value of property name.
42       */
43      public String getName() {
44          return name;
45      }
46  
47      /***
48       * Setter for property name.
49       * 
50       * @param name
51       *            New value of property name.
52       */
53      public void setName(String name) {
54          this.name = name;
55      }
56  
57      /***
58       * Getter for property publicID.
59       * 
60       * @return Value of property publicID.
61       */
62      public String getPublicID() {
63          return publicID;
64      }
65  
66      /***
67       * Setter for property publicID.
68       * 
69       * @param publicID
70       *            New value of property publicID.
71       */
72      public void setPublicID(String publicID) {
73          this.publicID = publicID;
74      }
75  
76      /***
77       * Getter for property systemID.
78       * 
79       * @return Value of property systemID.
80       */
81      public String getSystemID() {
82          return systemID;
83      }
84  
85      /***
86       * Setter for property systemID.
87       * 
88       * @param systemID
89       *            New value of property systemID.
90       */
91      public void setSystemID(String systemID) {
92          this.systemID = systemID;
93      }
94  
95      public String toString() {
96          StringBuffer buffer = new StringBuffer("<!ENTITY ");
97  
98          if (name.startsWith("%")) {
99              buffer.append("% ");
100             buffer.append(name.substring(1));
101         } else {
102             buffer.append(name);
103         }
104 
105         if (publicID != null) {
106             buffer.append(" PUBLIC \"");
107             buffer.append(publicID);
108             buffer.append("\" ");
109 
110             if (systemID != null) {
111                 buffer.append("\"");
112                 buffer.append(systemID);
113                 buffer.append("\" ");
114             }
115         } else if (systemID != null) {
116             buffer.append(" SYSTEM \"");
117             buffer.append(systemID);
118             buffer.append("\" ");
119         }
120 
121         buffer.append(">");
122 
123         return buffer.toString();
124     }
125 }
126 
127 /*
128  * Redistribution and use of this software and associated documentation
129  * ("Software"), with or without modification, are permitted provided that the
130  * following conditions are met:
131  * 
132  * 1. Redistributions of source code must retain copyright statements and
133  * notices. Redistributions must also contain a copy of this document.
134  * 
135  * 2. Redistributions in binary form must reproduce the above copyright notice,
136  * this list of conditions and the following disclaimer in the documentation
137  * and/or other materials provided with the distribution.
138  * 
139  * 3. The name "DOM4J" must not be used to endorse or promote products derived
140  * from this Software without prior written permission of MetaStuff, Ltd. For
141  * written permission, please contact dom4j-info@metastuff.com.
142  * 
143  * 4. Products derived from this Software may not be called "DOM4J" nor may
144  * "DOM4J" appear in their names without prior written permission of MetaStuff,
145  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
146  * 
147  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
148  * 
149  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
150  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
151  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
152  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
153  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
154  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
155  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
156  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
157  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
158  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
159  * POSSIBILITY OF SUCH DAMAGE.
160  * 
161  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
162  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dtd/package-summary.html0000644000175000017500000000476310242117755022331 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.dtd

Class Summary
AttributeDecl
ElementDecl
ExternalEntityDecl
InternalEntityDecl
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref/org/dom4j/dtd/package-frame.html0000644000175000017500000000206110242117647021713 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.dtd

org.dom4j.dtd

Classes

  • AttributeDecl
  • ElementDecl
  • ExternalEntityDecl
  • InternalEntityDecl
dom4j-1.6.1/docs/xref/org/dom4j/dtd/AttributeDecl.html0000644000175000017500000004055610242117700021764 0ustar ebourgebourg AttributeDecl xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dtd;
9   
10  /***
11   * <p>
12   * <code>AttributeDecl</code> represents an attribute declaration in a DTD.
13   * </p>
14   * 
15   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
16   * @version $Revision: 1.7 $
17   */
18  public class AttributeDecl {
19      /*** Holds value of property elementName. */
20      private String elementName;
21  
22      /*** Holds value of property attributeName. */
23      private String attributeName;
24  
25      /*** Holds value of property type. */
26      private String type;
27  
28      /*** Holds value of property value. */
29      private String value;
30  
31      /*** Holds value of property valueDefault. */
32      private String valueDefault;
33  
34      public AttributeDecl() {
35      }
36  
37      public AttributeDecl(String elementName, String attributeName, String type,
38              String valueDefault, String value) {
39          this.elementName = elementName;
40          this.attributeName = attributeName;
41          this.type = type;
42          this.value = value;
43          this.valueDefault = valueDefault;
44      }
45  
46      /***
47       * Getter for property elementName.
48       * 
49       * @return Value of property elementName.
50       */
51      public String getElementName() {
52          return elementName;
53      }
54  
55      /***
56       * Setter for property elementName.
57       * 
58       * @param elementName
59       *            New value of property elementName.
60       */
61      public void setElementName(String elementName) {
62          this.elementName = elementName;
63      }
64  
65      /***
66       * Getter for property attributeName.
67       * 
68       * @return Value of property attributeName.
69       */
70      public String getAttributeName() {
71          return attributeName;
72      }
73  
74      /***
75       * Setter for property attributeName.
76       * 
77       * @param attributeName
78       *            New value of property attributeName.
79       */
80      public void setAttributeName(String attributeName) {
81          this.attributeName = attributeName;
82      }
83  
84      /***
85       * Getter for property type.
86       * 
87       * @return Value of property type.
88       */
89      public String getType() {
90          return type;
91      }
92  
93      /***
94       * Setter for property type.
95       * 
96       * @param type
97       *            New value of property type.
98       */
99      public void setType(String type) {
100         this.type = type;
101     }
102 
103     /***
104      * Getter for property value.
105      * 
106      * @return Value of property value.
107      */
108     public String getValue() {
109         return value;
110     }
111 
112     /***
113      * Setter for property value.
114      * 
115      * @param value
116      *            New value of property value.
117      */
118     public void setValue(String value) {
119         this.value = value;
120     }
121 
122     /***
123      * Getter for property valueDefault.
124      * 
125      * @return Value of property valueDefault.
126      */
127     public String getValueDefault() {
128         return valueDefault;
129     }
130 
131     /***
132      * Setter for property valueDefault.
133      * 
134      * @param valueDefault
135      *            New value of property valueDefault.
136      */
137     public void setValueDefault(String valueDefault) {
138         this.valueDefault = valueDefault;
139     }
140 
141     public String toString() {
142         StringBuffer buffer = new StringBuffer("<!ATTLIST ");
143         buffer.append(elementName);
144         buffer.append(" ");
145         buffer.append(attributeName);
146         buffer.append(" ");
147         buffer.append(type);
148         buffer.append(" ");
149 
150         if (valueDefault != null) {
151             buffer.append(valueDefault);
152 
153             if (valueDefault.equals("#FIXED")) {
154                 buffer.append(" \"");
155                 buffer.append(value);
156                 buffer.append("\"");
157             }
158         } else {
159             buffer.append("\"");
160             buffer.append(value);
161             buffer.append("\"");
162         }
163 
164         buffer.append(">");
165 
166         return buffer.toString();
167     }
168 }
169 
170 /*
171  * Redistribution and use of this software and associated documentation
172  * ("Software"), with or without modification, are permitted provided that the
173  * following conditions are met:
174  * 
175  * 1. Redistributions of source code must retain copyright statements and
176  * notices. Redistributions must also contain a copy of this document.
177  * 
178  * 2. Redistributions in binary form must reproduce the above copyright notice,
179  * this list of conditions and the following disclaimer in the documentation
180  * and/or other materials provided with the distribution.
181  * 
182  * 3. The name "DOM4J" must not be used to endorse or promote products derived
183  * from this Software without prior written permission of MetaStuff, Ltd. For
184  * written permission, please contact dom4j-info@metastuff.com.
185  * 
186  * 4. Products derived from this Software may not be called "DOM4J" nor may
187  * "DOM4J" appear in their names without prior written permission of MetaStuff,
188  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
189  * 
190  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
191  * 
192  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
193  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
194  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
195  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
196  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
197  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
198  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
199  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
200  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
201  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
202  * POSSIBILITY OF SUCH DAMAGE.
203  * 
204  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
205  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dtd/InternalEntityDecl.html0000644000175000017500000003372210242117573022777 0ustar ebourgebourg InternalEntityDecl xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dtd;
9   
10  /***
11   * <p>
12   * <code>InternalEntityDecl</code> represents an internal entity declaration
13   * in a DTD.
14   * </p>
15   * 
16   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
17   * @version $Revision: 1.9 $
18   */
19  public class InternalEntityDecl {
20      /*** Holds value of property name. */
21      private String name;
22  
23      /*** Holds value of property value. */
24      private String value;
25  
26      public InternalEntityDecl() {
27      }
28  
29      public InternalEntityDecl(String name, String value) {
30          this.name = name;
31          this.value = value;
32      }
33  
34      /***
35       * Getter for property name.
36       * 
37       * @return Value of property name.
38       */
39      public String getName() {
40          return name;
41      }
42  
43      /***
44       * Setter for property name.
45       * 
46       * @param name
47       *            New value of property name.
48       */
49      public void setName(String name) {
50          this.name = name;
51      }
52  
53      /***
54       * Getter for property value.
55       * 
56       * @return Value of property value.
57       */
58      public String getValue() {
59          return value;
60      }
61  
62      /***
63       * Setter for property value.
64       * 
65       * @param value
66       *            New value of property value.
67       */
68      public void setValue(String value) {
69          this.value = value;
70      }
71  
72      public String toString() {
73          StringBuffer buffer = new StringBuffer("<!ENTITY ");
74  
75          if (name.startsWith("%")) {
76              buffer.append("% ");
77              buffer.append(name.substring(1));
78          } else {
79              buffer.append(name);
80          }
81  
82          buffer.append(" \"");
83          buffer.append(escapeEntityValue(value));
84          buffer.append("\">");
85  
86          return buffer.toString();
87      }
88  
89      private String escapeEntityValue(String text) {
90          StringBuffer result = new StringBuffer();
91  
92          for (int i = 0; i < text.length(); i++) {
93              char c = text.charAt(i);
94  
95              switch (c) {
96                  case '<':
97                      result.append("&#38;#60;");
98  
99                      break;
100 
101                 case '>':
102                     result.append("&#62;");
103 
104                     break;
105 
106                 case '&':
107                     result.append("&#38;#38;");
108 
109                     break;
110 
111                 case '\'':
112                     result.append("&#39;");
113 
114                     break;
115 
116                 case '\"':
117                     result.append("&#34;");
118 
119                     break;
120 
121                 default:
122 
123                     if (c < 32) {
124                         result.append("&#" + (int) c + ";");
125                     } else {
126                         result.append(c);
127                     }
128 
129                     break;
130             }
131         }
132 
133         return result.toString();
134     }
135 }
136 
137 /*
138  * Redistribution and use of this software and associated documentation
139  * ("Software"), with or without modification, are permitted provided that the
140  * following conditions are met:
141  * 
142  * 1. Redistributions of source code must retain copyright statements and
143  * notices. Redistributions must also contain a copy of this document.
144  * 
145  * 2. Redistributions in binary form must reproduce the above copyright notice,
146  * this list of conditions and the following disclaimer in the documentation
147  * and/or other materials provided with the distribution.
148  * 
149  * 3. The name "DOM4J" must not be used to endorse or promote products derived
150  * from this Software without prior written permission of MetaStuff, Ltd. For
151  * written permission, please contact dom4j-info@metastuff.com.
152  * 
153  * 4. Products derived from this Software may not be called "DOM4J" nor may
154  * "DOM4J" appear in their names without prior written permission of MetaStuff,
155  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
156  * 
157  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
158  * 
159  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
160  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
161  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
162  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
163  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
164  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
165  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
166  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
167  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
168  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
169  * POSSIBILITY OF SUCH DAMAGE.
170  * 
171  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
172  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/dtd/ElementDecl.html0000644000175000017500000002336510242117716021420 0ustar ebourgebourg ElementDecl xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.dtd;
9   
10  /***
11   * <p>
12   * <code>AttributeDecl</code> represents an element declaration in a DTD.
13   * </p>
14   * 
15   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
16   * @version $Revision: 1.6 $
17   */
18  public class ElementDecl {
19      /*** Holds value of property name. */
20      private String name;
21  
22      /*** Holds value of property model. */
23      private String model;
24  
25      public ElementDecl() {
26      }
27  
28      public ElementDecl(String name, String model) {
29          this.name = name;
30          this.model = model;
31      }
32  
33      /***
34       * Getter for property name.
35       * 
36       * @return Value of property name.
37       */
38      public String getName() {
39          return name;
40      }
41  
42      /***
43       * Setter for property name.
44       * 
45       * @param name
46       *            New value of property name.
47       */
48      public void setName(String name) {
49          this.name = name;
50      }
51  
52      /***
53       * Getter for property model.
54       * 
55       * @return Value of property model.
56       */
57      public String getModel() {
58          return model;
59      }
60  
61      /***
62       * Setter for property model.
63       * 
64       * @param model
65       *            New value of property model.
66       */
67      public void setModel(String model) {
68          this.model = model;
69      }
70  
71      public String toString() {
72          return "<!ELEMENT " + name + " " + model + ">";
73      }
74  }
75  
76  /*
77   * Redistribution and use of this software and associated documentation
78   * ("Software"), with or without modification, are permitted provided that the
79   * following conditions are met:
80   * 
81   * 1. Redistributions of source code must retain copyright statements and
82   * notices. Redistributions must also contain a copy of this document.
83   * 
84   * 2. Redistributions in binary form must reproduce the above copyright notice,
85   * this list of conditions and the following disclaimer in the documentation
86   * and/or other materials provided with the distribution.
87   * 
88   * 3. The name "DOM4J" must not be used to endorse or promote products derived
89   * from this Software without prior written permission of MetaStuff, Ltd. For
90   * written permission, please contact dom4j-info@metastuff.com.
91   * 
92   * 4. Products derived from this Software may not be called "DOM4J" nor may
93   * "DOM4J" appear in their names without prior written permission of MetaStuff,
94   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
95   * 
96   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
97   * 
98   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
99   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
100  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
101  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
102  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
103  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
104  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
105  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
106  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
107  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
108  * POSSIBILITY OF SUCH DAMAGE.
109  * 
110  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
111  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/VisitorSupport.html0000644000175000017500000002144510242117603021510 0ustar ebourgebourg VisitorSupport xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  /***
11   * <p>
12   * <code>VisitorSupport</code> is an abstract base class which is useful for
13   * implementation inheritence or when using anonymous inner classes to create
14   * simple <code>Visitor</code> implementations.
15   * </p>
16   * 
17   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
18   * @version $Revision: 1.6 $
19   */
20  public abstract class VisitorSupport implements Visitor {
21      public VisitorSupport() {
22      }
23  
24      public void visit(Document document) {
25      }
26  
27      public void visit(DocumentType documentType) {
28      }
29  
30      public void visit(Element node) {
31      }
32  
33      public void visit(Attribute node) {
34      }
35  
36      public void visit(CDATA node) {
37      }
38  
39      public void visit(Comment node) {
40      }
41  
42      public void visit(Entity node) {
43      }
44  
45      public void visit(Namespace namespace) {
46      }
47  
48      public void visit(ProcessingInstruction node) {
49      }
50  
51      public void visit(Text node) {
52      }
53  }
54  
55  /*
56   * Redistribution and use of this software and associated documentation
57   * ("Software"), with or without modification, are permitted provided that the
58   * following conditions are met:
59   * 
60   * 1. Redistributions of source code must retain copyright statements and
61   * notices. Redistributions must also contain a copy of this document.
62   * 
63   * 2. Redistributions in binary form must reproduce the above copyright notice,
64   * this list of conditions and the following disclaimer in the documentation
65   * and/or other materials provided with the distribution.
66   * 
67   * 3. The name "DOM4J" must not be used to endorse or promote products derived
68   * from this Software without prior written permission of MetaStuff, Ltd. For
69   * written permission, please contact dom4j-info@metastuff.com.
70   * 
71   * 4. Products derived from this Software may not be called "DOM4J" nor may
72   * "DOM4J" appear in their names without prior written permission of MetaStuff,
73   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
74   * 
75   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
76   * 
77   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
78   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
79   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
80   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
81   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
82   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
83   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
84   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
85   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
86   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
87   * POSSIBILITY OF SUCH DAMAGE.
88   * 
89   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
90   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/Visitor.html0000644000175000017500000003437410242117750020123 0ustar ebourgebourg Visitor xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  /***
11   * <p>
12   * <code>Visitor</code> is used to implement the <code>Visitor</code>
13   * pattern in DOM4J. An object of this interface can be passed to a
14   * <code>Node</code> which will then call its typesafe methods. Please refer
15   * to the <i>Gang of Four </i> book of Design Patterns for more details on the
16   * <code>Visitor</code> pattern.
17   * </p>
18   * 
19   * <p>
20   * This <a href="http://www.patterndepot.com/put/8/JavaPatterns.htm">site </a>
21   * has further discussion on design patterns and links to the GOF book. This <a
22   * href="http://www.patterndepot.com/put/8/visitor.pdf">link </a> describes the
23   * Visitor pattern in detail.
24   * </p>
25   * 
26   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
27   * @version $Revision: 1.8 $
28   */
29  public interface Visitor {
30      /***
31       * <p>
32       * Visits the given <code>Document</code>
33       * </p>
34       * 
35       * @param document
36       *            is the <code>Document</code> node to visit.
37       */
38      void visit(Document document);
39  
40      /***
41       * <p>
42       * Visits the given <code>DocumentType</code>
43       * </p>
44       * 
45       * @param documentType
46       *            is the <code>DocumentType</code> node to visit.
47       */
48      void visit(DocumentType documentType);
49  
50      /***
51       * <p>
52       * Visits the given <code>Element</code>
53       * </p>
54       * 
55       * @param node
56       *            is the <code>Element</code> node to visit.
57       */
58      void visit(Element node);
59  
60      /***
61       * <p>
62       * Visits the given <code>Attribute</code>
63       * </p>
64       * 
65       * @param node
66       *            is the <code>Attribute</code> node to visit.
67       */
68      void visit(Attribute node);
69  
70      /***
71       * <p>
72       * Visits the given <code>CDATA</code>
73       * </p>
74       * 
75       * @param node
76       *            is the <code>CDATA</code> node to visit.
77       */
78      void visit(CDATA node);
79  
80      /***
81       * <p>
82       * Visits the given <code>Comment</code>
83       * </p>
84       * 
85       * @param node
86       *            is the <code>Comment</code> node to visit.
87       */
88      void visit(Comment node);
89  
90      /***
91       * <p>
92       * Visits the given <code>Entity</code>
93       * </p>
94       * 
95       * @param node
96       *            is the <code>Entity</code> node to visit.
97       */
98      void visit(Entity node);
99  
100     /***
101      * <p>
102      * Visits the given <code>Namespace</code>
103      * </p>
104      * 
105      * @param namespace
106      *            is the <code>Namespace</code> node to visit.
107      */
108     void visit(Namespace namespace);
109 
110     /***
111      * <p>
112      * Visits the given <code>ProcessingInstruction</code>
113      * </p>
114      * 
115      * @param node
116      *            is the <code>ProcessingInstruction</code> node to visit.
117      */
118     void visit(ProcessingInstruction node);
119 
120     /***
121      * <p>
122      * Visits the given <code>Text</code>
123      * </p>
124      * 
125      * @param node
126      *            is the <code>Text</code> node to visit.
127      */
128     void visit(Text node);
129 }
130 
131 /*
132  * Redistribution and use of this software and associated documentation
133  * ("Software"), with or without modification, are permitted provided that the
134  * following conditions are met:
135  * 
136  * 1. Redistributions of source code must retain copyright statements and
137  * notices. Redistributions must also contain a copy of this document.
138  * 
139  * 2. Redistributions in binary form must reproduce the above copyright notice,
140  * this list of conditions and the following disclaimer in the documentation
141  * and/or other materials provided with the distribution.
142  * 
143  * 3. The name "DOM4J" must not be used to endorse or promote products derived
144  * from this Software without prior written permission of MetaStuff, Ltd. For
145  * written permission, please contact dom4j-info@metastuff.com.
146  * 
147  * 4. Products derived from this Software may not be called "DOM4J" nor may
148  * "DOM4J" appear in their names without prior written permission of MetaStuff,
149  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
150  * 
151  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
152  * 
153  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
154  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
155  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
156  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
157  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
158  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
159  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
160  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
161  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
162  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
163  * POSSIBILITY OF SUCH DAMAGE.
164  * 
165  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
166  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/CharacterData.html0000644000175000017500000001626510242117660021151 0ustar ebourgebourg CharacterData xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  /***
11   * <p>
12   * <code>CharacterData</code> is a marker interface for character based nodes
13   * such as the <code>CDATA</code>,<code>Comment</code> and
14   * <code>Text</code> nodes.
15   * </p>
16   * 
17   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
18   * @version $Revision: 1.9 $
19   */
20  public interface CharacterData extends Node {
21      /***
22       * Appends the given text to this nodes text value. Calling this method is
23       * equivalent of the code <code>node.setText(node.getText() + text)</code>
24       * but allows for possible implementation optimisations (such as a text
25       * based node storing a StringBuffer internally
26       * 
27       * @param text
28       *            the text to append
29       */
30      void appendText(String text);
31  }
32  
33  /*
34   * Redistribution and use of this software and associated documentation
35   * ("Software"), with or without modification, are permitted provided that the
36   * following conditions are met:
37   * 
38   * 1. Redistributions of source code must retain copyright statements and
39   * notices. Redistributions must also contain a copy of this document.
40   * 
41   * 2. Redistributions in binary form must reproduce the above copyright notice,
42   * this list of conditions and the following disclaimer in the documentation
43   * and/or other materials provided with the distribution.
44   * 
45   * 3. The name "DOM4J" must not be used to endorse or promote products derived
46   * from this Software without prior written permission of MetaStuff, Ltd. For
47   * written permission, please contact dom4j-info@metastuff.com.
48   * 
49   * 4. Products derived from this Software may not be called "DOM4J" nor may
50   * "DOM4J" appear in their names without prior written permission of MetaStuff,
51   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
52   * 
53   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
54   * 
55   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
56   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
59   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
60   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
61   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
62   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
63   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
64   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
65   * POSSIBILITY OF SUCH DAMAGE.
66   * 
67   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
68   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/XPathException.html0000644000175000017500000002053710242117765021371 0ustar ebourgebourg XPathException xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j;
9   
10  /***
11   * <p>
12   * <code>XPathException</code> is thrown when an exception occurs while
13   * evaluating an XPath expression, usually due to some function throwing an
14   * exception.
15   * </p>
16   * 
17   * @version $Revision: 1.6 $
18   */
19  public class XPathException extends RuntimeException {
20      /*** The XPath expression that caused the exception */
21      private String xpath;
22  
23      public XPathException(String xpath) {
24          super("Exception occurred evaluting XPath: " + xpath);
25          this.xpath = xpath;
26      }
27  
28      public XPathException(String xpath, String reason) {
29          super("Exception occurred evaluting XPath: " + xpath + " " + reason);
30          this.xpath = xpath;
31      }
32  
33      public XPathException(String xpath, Exception e) {
34          super("Exception occurred evaluting XPath: " + xpath + ". Exception: "
35                  + e.getMessage());
36          this.xpath = xpath;
37      }
38  
39      /***
40       * Returns the XPath expression that caused the problem
41       * 
42       * @return DOCUMENT ME!
43       */
44      public String getXPath() {
45          return xpath;
46      }
47  }
48  
49  /*
50   * Redistribution and use of this software and associated documentation
51   * ("Software"), with or without modification, are permitted provided that the
52   * following conditions are met:
53   * 
54   * 1. Redistributions of source code must retain copyright statements and
55   * notices. Redistributions must also contain a copy of this document.
56   * 
57   * 2. Redistributions in binary form must reproduce the above copyright notice,
58   * this list of conditions and the following disclaimer in the documentation
59   * and/or other materials provided with the distribution.
60   * 
61   * 3. The name "DOM4J" must not be used to endorse or promote products derived
62   * from this Software without prior written permission of MetaStuff, Ltd. For
63   * written permission, please contact dom4j-info@metastuff.com.
64   * 
65   * 4. Products derived from this Software may not be called "DOM4J" nor may
66   * "DOM4J" appear in their names without prior written permission of MetaStuff,
67   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
68   * 
69   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
70   * 
71   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
72   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
73   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
74   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
75   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
76   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
77   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
78   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
79   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
80   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
81   * POSSIBILITY OF SUCH DAMAGE.
82   * 
83   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
84   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/datatype/0000755000175000017500000000000012133227266017403 5ustar ebourgebourgdom4j-1.6.1/docs/xref/org/dom4j/datatype/SchemaParser.html0000644000175000017500000015153110242117717022652 0ustar ebourgebourg SchemaParser xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.datatype;
9   
10  import com.sun.msv.datatype.xsd.DatatypeFactory;
11  import com.sun.msv.datatype.xsd.TypeIncubator;
12  import com.sun.msv.datatype.xsd.XSDatatype;
13  
14  import java.util.HashMap;
15  import java.util.Iterator;
16  import java.util.Map;
17  
18  import org.dom4j.Attribute;
19  import org.dom4j.Document;
20  import org.dom4j.DocumentFactory;
21  import org.dom4j.Element;
22  import org.dom4j.Namespace;
23  import org.dom4j.QName;
24  import org.dom4j.io.SAXReader;
25  import org.dom4j.util.AttributeHelper;
26  
27  import org.relaxng.datatype.DatatypeException;
28  import org.relaxng.datatype.ValidationContext;
29  
30  import org.xml.sax.EntityResolver;
31  import org.xml.sax.InputSource;
32  
33  /***
34   * <p>
35   * <code>SchemaParser</code> reads an XML Schema Document.
36   * </p>
37   * 
38   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
39   * @author Yuxin Ruan
40   * @version $Revision: 1.19 $
41   */
42  public class SchemaParser {
43      private static final Namespace XSD_NAMESPACE = Namespace.get("xsd",
44              "http://www.w3.org/2001/XMLSchema");
45  
46      // Use QNames for the elements
47      private static final QName XSD_ELEMENT = QName
48              .get("element", XSD_NAMESPACE);
49  
50      private static final QName XSD_ATTRIBUTE = QName.get("attribute",
51              XSD_NAMESPACE);
52  
53      private static final QName XSD_SIMPLETYPE = QName.get("simpleType",
54              XSD_NAMESPACE);
55  
56      private static final QName XSD_COMPLEXTYPE = QName.get("complexType",
57              XSD_NAMESPACE);
58  
59      private static final QName XSD_RESTRICTION = QName.get("restriction",
60              XSD_NAMESPACE);
61  
62      private static final QName XSD_SEQUENCE = QName.get("sequence",
63              XSD_NAMESPACE);
64  
65      private static final QName XSD_CHOICE = QName.get("choice", XSD_NAMESPACE);
66  
67      private static final QName XSD_ALL = QName.get("all", XSD_NAMESPACE);
68  
69      private static final QName XSD_INCLUDE = QName
70              .get("include", XSD_NAMESPACE);
71  
72      /*** Document factory used to register Element specific factories */
73      private DatatypeDocumentFactory documentFactory;
74  
75      /***
76       * Cache of <code>XSDatatype</code> instances loaded or created during
77       * this build
78       */
79      private Map dataTypeCache = new HashMap();
80  
81      /*** NamedTypeResolver */
82      private NamedTypeResolver namedTypeResolver;
83  
84      /*** target namespace */
85      private Namespace targetNamespace;
86  
87      public SchemaParser() {
88          this(DatatypeDocumentFactory.singleton);
89      }
90  
91      public SchemaParser(DatatypeDocumentFactory documentFactory) {
92          this.documentFactory = documentFactory;
93          this.namedTypeResolver = new NamedTypeResolver(documentFactory);
94      }
95  
96      /***
97       * Parses the given schema document
98       * 
99       * @param schemaDocument
100      *            is the document of the XML Schema
101      */
102     public void build(Document schemaDocument) {
103         this.targetNamespace = null;
104         internalBuild(schemaDocument);
105     }
106 
107     public void build(Document schemaDocument, Namespace namespace) {
108         this.targetNamespace = namespace;
109         internalBuild(schemaDocument);
110     }
111 
112     private synchronized void internalBuild(Document schemaDocument) {
113         Element root = schemaDocument.getRootElement();
114 
115         if (root != null) {
116             // handle schema includes
117             Iterator includeIter = root.elementIterator(XSD_INCLUDE);
118 
119             while (includeIter.hasNext()) {
120                 Element includeElement = (Element) includeIter.next();
121                 String inclSchemaInstanceURI = includeElement
122                         .attributeValue("schemaLocation");
123                 EntityResolver resolver = schemaDocument.getEntityResolver();
124 
125                 try {
126                     if (resolver == null) {
127                         String msg = "No EntityResolver available";
128                         throw new InvalidSchemaException(msg);
129                     }
130 
131                     InputSource inputSource = resolver.resolveEntity(null,
132                             inclSchemaInstanceURI);
133 
134                     if (inputSource == null) {
135                         String msg = "Could not resolve the schema URI: "
136                                 + inclSchemaInstanceURI;
137                         throw new InvalidSchemaException(msg);
138                     }
139 
140                     SAXReader reader = new SAXReader();
141                     Document inclSchemaDocument = reader.read(inputSource);
142                     build(inclSchemaDocument);
143                 } catch (Exception e) {
144                     System.out.println("Failed to load schema: "
145                             + inclSchemaInstanceURI);
146                     System.out.println("Caught: " + e);
147                     e.printStackTrace();
148                     throw new InvalidSchemaException("Failed to load schema: "
149                             + inclSchemaInstanceURI);
150                 }
151             }
152 
153             // handle elements
154             Iterator iter = root.elementIterator(XSD_ELEMENT);
155 
156             while (iter.hasNext()) {
157                 onDatatypeElement((Element) iter.next(), documentFactory);
158             }
159 
160             // handle named simple types
161             iter = root.elementIterator(XSD_SIMPLETYPE);
162 
163             while (iter.hasNext()) {
164                 onNamedSchemaSimpleType((Element) iter.next());
165             }
166 
167             // hanlde named complex types
168             iter = root.elementIterator(XSD_COMPLEXTYPE);
169 
170             while (iter.hasNext()) {
171                 onNamedSchemaComplexType((Element) iter.next());
172             }
173 
174             namedTypeResolver.resolveNamedTypes();
175         }
176     }
177 
178     // Implementation methods
179     // -------------------------------------------------------------------------
180 
181     /***
182      * processes an XML Schema &lt;element&gt; tag
183      * 
184      * @param xsdElement
185      *            DOCUMENT ME!
186      * @param parentFactory
187      *            DOCUMENT ME!
188      */
189     private void onDatatypeElement(Element xsdElement,
190             DocumentFactory parentFactory) {
191         String name = xsdElement.attributeValue("name");
192         String type = xsdElement.attributeValue("type");
193         QName qname = getQName(name);
194 
195         DatatypeElementFactory factory = getDatatypeElementFactory(qname);
196 
197         if (type != null) {
198             // register type with this element name
199             XSDatatype dataType = getTypeByName(type);
200 
201             if (dataType != null) {
202                 factory.setChildElementXSDatatype(qname, dataType);
203             } else {
204                 QName typeQName = getQName(type);
205                 namedTypeResolver.registerTypedElement(xsdElement, typeQName,
206                         parentFactory);
207             }
208 
209             return;
210         }
211 
212         // handle element types derrived from simpleTypes
213         Element xsdSimpleType = xsdElement.element(XSD_SIMPLETYPE);
214 
215         if (xsdSimpleType != null) {
216             XSDatatype dataType = loadXSDatatypeFromSimpleType(xsdSimpleType);
217 
218             if (dataType != null) {
219                 factory.setChildElementXSDatatype(qname, dataType);
220             }
221         }
222 
223         Element schemaComplexType = xsdElement.element(XSD_COMPLEXTYPE);
224 
225         if (schemaComplexType != null) {
226             onSchemaComplexType(schemaComplexType, factory);
227         }
228 
229         Iterator iter = xsdElement.elementIterator(XSD_ATTRIBUTE);
230 
231         if (iter.hasNext()) {
232             do {
233                 onDatatypeAttribute(xsdElement, factory, (Element) iter
234                         .next());
235             } while (iter.hasNext());
236         }
237     }
238 
239     /***
240      * processes an named XML Schema &lt;complexTypegt; tag
241      * 
242      * @param schemaComplexType
243      *            DOCUMENT ME!
244      */
245     private void onNamedSchemaComplexType(Element schemaComplexType) {
246         Attribute nameAttr = schemaComplexType.attribute("name");
247 
248         if (nameAttr == null) {
249             return;
250         }
251 
252         String name = nameAttr.getText();
253         QName qname = getQName(name);
254 
255         DatatypeElementFactory factory = getDatatypeElementFactory(qname);
256 
257         onSchemaComplexType(schemaComplexType, factory);
258         namedTypeResolver.registerComplexType(qname, factory);
259     }
260 
261     /***
262      * processes an XML Schema &lt;complexTypegt; tag
263      * 
264      * @param schemaComplexType
265      *            DOCUMENT ME!
266      * @param elementFactory
267      *            DOCUMENT ME!
268      */
269     private void onSchemaComplexType(Element schemaComplexType,
270             DatatypeElementFactory elementFactory) {
271         Iterator iter = schemaComplexType.elementIterator(XSD_ATTRIBUTE);
272 
273         while (iter.hasNext()) {
274             Element xsdAttribute = (Element) iter.next();
275             String name = xsdAttribute.attributeValue("name");
276             QName qname = getQName(name);
277 
278             XSDatatype dataType = dataTypeForXsdAttribute(xsdAttribute);
279 
280             if (dataType != null) {
281                 // register the XSDatatype for the given Attribute
282                 // #### should both these be done?
283                 // elementFactory.setChildElementXSDatatype( qname, dataType );
284                 elementFactory.setAttributeXSDatatype(qname, dataType);
285             }
286         }
287 
288         // handle sequence definition
289         Element schemaSequence = schemaComplexType.element(XSD_SEQUENCE);
290 
291         if (schemaSequence != null) {
292             onChildElements(schemaSequence, elementFactory);
293         }
294 
295         // handle choice definition
296         Element schemaChoice = schemaComplexType.element(XSD_CHOICE);
297 
298         if (schemaChoice != null) {
299             onChildElements(schemaChoice, elementFactory);
300         }
301 
302         // handle all definition
303         Element schemaAll = schemaComplexType.element(XSD_ALL);
304 
305         if (schemaAll != null) {
306             onChildElements(schemaAll, elementFactory);
307         }
308     }
309 
310     private void onChildElements(Element element, DatatypeElementFactory fact) {
311         Iterator iter = element.elementIterator(XSD_ELEMENT);
312 
313         while (iter.hasNext()) {
314             Element xsdElement = (Element) iter.next();
315             onDatatypeElement(xsdElement, fact);
316         }
317     }
318 
319     /***
320      * processes an XML Schema &lt;attribute&gt; tag
321      * 
322      * @param xsdElement
323      *            DOCUMENT ME!
324      * @param elementFactory
325      *            DOCUMENT ME!
326      * @param xsdAttribute
327      *            DOCUMENT ME!
328      */
329     private void onDatatypeAttribute(Element xsdElement,
330             DatatypeElementFactory elementFactory, Element xsdAttribute) {
331         String name = xsdAttribute.attributeValue("name");
332         QName qname = getQName(name);
333         XSDatatype dataType = dataTypeForXsdAttribute(xsdAttribute);
334 
335         if (dataType != null) {
336             // register the XSDatatype for the given Attribute
337             elementFactory.setAttributeXSDatatype(qname, dataType);
338         } else {
339             String type = xsdAttribute.attributeValue("type");
340             System.out.println("Warning: Couldn't find XSDatatype for type: "
341                     + type + " attribute: " + name);
342         }
343     }
344 
345     /***
346      * processes an XML Schema &lt;attribute&gt; tag
347      * 
348      * @param xsdAttribute
349      *            DOCUMENT ME!
350      * 
351      * @return DOCUMENT ME!
352      * 
353      * @throws InvalidSchemaException
354      *             DOCUMENT ME!
355      */
356     private XSDatatype dataTypeForXsdAttribute(Element xsdAttribute) {
357         String type = xsdAttribute.attributeValue("type");
358         XSDatatype dataType = null;
359 
360         if (type != null) {
361             dataType = getTypeByName(type);
362         } else {
363             // must parse the <simpleType> element
364             Element xsdSimpleType = xsdAttribute.element(XSD_SIMPLETYPE);
365 
366             if (xsdSimpleType == null) {
367                 String name = xsdAttribute.attributeValue("name");
368                 String msg = "The attribute: " + name
369                         + " has no type attribute and does not contain a "
370                         + "<simpleType/> element";
371                 throw new InvalidSchemaException(msg);
372             }
373 
374             dataType = loadXSDatatypeFromSimpleType(xsdSimpleType);
375         }
376 
377         return dataType;
378     }
379 
380     /***
381      * processes an named XML Schema &lt;simpleTypegt; tag
382      * 
383      * @param schemaSimpleType
384      *            DOCUMENT ME!
385      */
386     private void onNamedSchemaSimpleType(Element schemaSimpleType) {
387         Attribute nameAttr = schemaSimpleType.attribute("name");
388 
389         if (nameAttr == null) {
390             return;
391         }
392 
393         String name = nameAttr.getText();
394         QName qname = getQName(name);
395         XSDatatype datatype = loadXSDatatypeFromSimpleType(schemaSimpleType);
396         namedTypeResolver.registerSimpleType(qname, datatype);
397     }
398 
399     /***
400      * Loads a XSDatatype object from a &lt;simpleType&gt; attribute schema
401      * element
402      * 
403      * @param xsdSimpleType
404      *            DOCUMENT ME!
405      * 
406      * @return DOCUMENT ME!
407      */
408     private XSDatatype loadXSDatatypeFromSimpleType(Element xsdSimpleType) {
409         Element xsdRestriction = xsdSimpleType.element(XSD_RESTRICTION);
410 
411         if (xsdRestriction != null) {
412             String base = xsdRestriction.attributeValue("base");
413 
414             if (base != null) {
415                 XSDatatype baseType = getTypeByName(base);
416 
417                 if (baseType == null) {
418                     onSchemaError("Invalid base type: " + base
419                             + " when trying to build restriction: "
420                             + xsdRestriction);
421                 } else {
422                     return deriveSimpleType(baseType, xsdRestriction);
423                 }
424             } else {
425                 // simpleType and base are mutually exclusive and you
426                 // must have one within a <restriction> tag
427                 Element xsdSubType = xsdSimpleType.element(XSD_SIMPLETYPE);
428 
429                 if (xsdSubType == null) {
430                     String msg = "The simpleType element: " + xsdSimpleType
431                             + " must contain a base attribute or simpleType"
432                             + " element";
433                     onSchemaError(msg);
434                 } else {
435                     return loadXSDatatypeFromSimpleType(xsdSubType);
436                 }
437             }
438         } else {
439             onSchemaError("No <restriction>. Could not create XSDatatype for"
440                     + " simpleType: " + xsdSimpleType);
441         }
442 
443         return null;
444     }
445 
446     /***
447      * Derives a new type from a base type and a set of restrictions
448      * 
449      * @param baseType
450      *            DOCUMENT ME!
451      * @param xsdRestriction
452      *            DOCUMENT ME!
453      * 
454      * @return DOCUMENT ME!
455      */
456     private XSDatatype deriveSimpleType(XSDatatype baseType,
457             Element xsdRestriction) {
458         TypeIncubator incubator = new TypeIncubator(baseType);
459         ValidationContext context = null;
460 
461         try {
462             for (Iterator iter = xsdRestriction.elementIterator(); iter
463                     .hasNext();) {
464                 Element element = (Element) iter.next();
465                 String name = element.getName();
466                 String value = element.attributeValue("value");
467                 boolean fixed = AttributeHelper.booleanValue(element, "fixed");
468 
469                 // add facet
470                 incubator.addFacet(name, value, fixed, context);
471             }
472 
473             // derive a new type by those facets
474             String newTypeName = null;
475 
476             return incubator.derive("", newTypeName);
477         } catch (DatatypeException e) {
478             onSchemaError("Invalid restriction: " + e.getMessage()
479                     + " when trying to build restriction: " + xsdRestriction);
480 
481             return null;
482         }
483     }
484 
485     /***
486      * DOCUMENT ME!
487      * 
488      * @param name
489      *            The name of the element
490      * 
491      * @return the <code>DatatypeElementFactory</code> for the given element
492      *         QName, creating one if it does not already exist
493      */
494     private DatatypeElementFactory getDatatypeElementFactory(QName name) {
495         DatatypeElementFactory factory = documentFactory
496                 .getElementFactory(name);
497 
498         if (factory == null) {
499             factory = new DatatypeElementFactory(name);
500             name.setDocumentFactory(factory);
501         }
502 
503         return factory;
504     }
505 
506     private XSDatatype getTypeByName(String type) {
507         XSDatatype dataType = (XSDatatype) dataTypeCache.get(type);
508 
509         if (dataType == null) {
510             // first check to see if it is a built-in type
511             // maybe a prefix is being used
512             int idx = type.indexOf(':');
513 
514             if (idx >= 0) {
515                 String localName = type.substring(idx + 1);
516 
517                 try {
518                     dataType = DatatypeFactory.getTypeByName(localName);
519                 } catch (DatatypeException e) {
520                 }
521             }
522 
523             if (dataType == null) {
524                 try {
525                     dataType = DatatypeFactory.getTypeByName(type);
526                 } catch (DatatypeException e) {
527                 }
528             }
529 
530             if (dataType == null) {
531                 // it's no built-in type, maybe it's a type we defined ourself
532                 QName typeQName = getQName(type);
533                 dataType = (XSDatatype) namedTypeResolver.simpleTypeMap
534                         .get(typeQName);
535             }
536 
537             if (dataType != null) {
538                 // store in cache for later
539                 dataTypeCache.put(type, dataType);
540             }
541         }
542 
543         return dataType;
544     }
545 
546     private QName getQName(String name) {
547         if (targetNamespace == null) {
548             return documentFactory.createQName(name);
549         } else {
550             return documentFactory.createQName(name, targetNamespace);
551         }
552     }
553 
554     /***
555      * Called when there is a problem with the schema and the builder cannot
556      * handle the XML Schema Data Types correctly
557      * 
558      * @param message
559      *            DOCUMENT ME!
560      * 
561      * @throws InvalidSchemaException
562      *             DOCUMENT ME!
563      */
564     private void onSchemaError(String message) {
565         // Some users may wish to disable exception throwing
566         // and instead use some kind of listener for errors and continue
567         // System.out.println( "WARNING: " + message );
568         throw new InvalidSchemaException(message);
569     }
570 }
571 
572 /*
573  * Redistribution and use of this software and associated documentation
574  * ("Software"), with or without modification, are permitted provided that the
575  * following conditions are met:
576  * 
577  * 1. Redistributions of source code must retain copyright statements and
578  * notices. Redistributions must also contain a copy of this document.
579  * 
580  * 2. Redistributions in binary form must reproduce the above copyright notice,
581  * this list of conditions and the following disclaimer in the documentation
582  * and/or other materials provided with the distribution.
583  * 
584  * 3. The name "DOM4J" must not be used to endorse or promote products derived
585  * from this Software without prior written permission of MetaStuff, Ltd. For
586  * written permission, please contact dom4j-info@metastuff.com.
587  * 
588  * 4. Products derived from this Software may not be called "DOM4J" nor may
589  * "DOM4J" appear in their names without prior written permission of MetaStuff,
590  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
591  * 
592  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
593  * 
594  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
595  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
596  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
597  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
598  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
599  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
600  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
601  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
602  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
603  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
604  * POSSIBILITY OF SUCH DAMAGE.
605  * 
606  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
607  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/datatype/DatatypeElement.html0000644000175000017500000004375510242117720023364 0ustar ebourgebourg DatatypeElement xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.datatype;
9   
10  import com.sun.msv.datatype.DatabindableDatatype;
11  import com.sun.msv.datatype.SerializationContext;
12  import com.sun.msv.datatype.xsd.XSDatatype;
13  
14  import org.dom4j.Element;
15  import org.dom4j.Namespace;
16  import org.dom4j.Node;
17  import org.dom4j.QName;
18  import org.dom4j.tree.DefaultElement;
19  
20  import org.relaxng.datatype.DatatypeException;
21  import org.relaxng.datatype.ValidationContext;
22  
23  /***
24   * <p>
25   * <code>DatatypeElement</code> represents an Element which supports the <a
26   * href="http://www.w3.org/TR/xmlschema-2/">XML Schema Data Types </a>
27   * specification.
28   * </p>
29   * 
30   * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
31   * @version $Revision: 1.9 $
32   */
33  public class DatatypeElement extends DefaultElement implements
34          SerializationContext, ValidationContext {
35      /*** The <code>XSDatatype</code> of the <code>Attribute</code> */
36      private XSDatatype datatype;
37  
38      /*** The data (Object) value of the <code>Attribute</code> */
39      private Object data;
40  
41      public DatatypeElement(QName qname, XSDatatype datatype) {
42          super(qname);
43          this.datatype = datatype;
44      }
45  
46      public DatatypeElement(QName qname, int attributeCount, XSDatatype type) {
47          super(qname, attributeCount);
48          this.datatype = type;
49      }
50  
51      public String toString() {
52          return getClass().getName() + hashCode() + " [Element: <"
53                  + getQualifiedName() + " attributes: " + attributeList()
54                  + " data: " + getData() + " />]";
55      }
56  
57      /***
58       * Returns the MSV XSDatatype for this node
59       * 
60       * @return DOCUMENT ME!
61       */
62      public XSDatatype getXSDatatype() {
63          return datatype;
64      }
65  
66      // SerializationContext interface
67      // -------------------------------------------------------------------------
68      public String getNamespacePrefix(String uri) {
69          Namespace namespace = getNamespaceForURI(uri);
70  
71          return (namespace != null) ? namespace.getPrefix() : null;
72      }
73  
74      // ValidationContext interface
75      // -------------------------------------------------------------------------
76      public String getBaseUri() {
77          // XXXX: could we use a Document for this?
78          return null;
79      }
80  
81      public boolean isNotation(String notationName) {
82          // XXXX: no way to do this yet in dom4j so assume false
83          return false;
84      }
85  
86      public boolean isUnparsedEntity(String entityName) {
87          // XXXX: no way to do this yet in dom4j so assume valid
88          return true;
89      }
90  
91      public String resolveNamespacePrefix(String prefix) {
92          Namespace namespace = getNamespaceForPrefix(prefix);
93  
94          if (namespace != null) {
95              return namespace.getURI();
96          }
97  
98          return null;
99      }
100 
101     // Element interface
102     // -------------------------------------------------------------------------
103     public Object getData() {
104         if (data == null) {
105             String text = getTextTrim();
106 
107             if ((text != null) && (text.length() > 0)) {
108                 if (datatype instanceof DatabindableDatatype) {
109                     DatabindableDatatype bind = (DatabindableDatatype) datatype;
110                     data = bind.createJavaObject(text, this);
111                 } else {
112                     data = datatype.createValue(text, this);
113                 }
114             }
115         }
116 
117         return data;
118     }
119 
120     public void setData(Object data) {
121         String s = datatype.convertToLexicalValue(data, this);
122         validate(s);
123         this.data = data;
124         setText(s);
125     }
126 
127     public Element addText(String text) {
128         validate(text);
129 
130         return super.addText(text);
131     }
132 
133     public void setText(String text) {
134         validate(text);
135         super.setText(text);
136     }
137 
138     // Implementation methods
139     // -------------------------------------------------------------------------
140 
141     /***
142      * Override to force lazy recreation of data object
143      * 
144      * @param node
145      *            DOCUMENT ME!
146      */
147     protected void childAdded(Node node) {
148         data = null;
149         super.childAdded(node);
150     }
151 
152     /***
153      * Override to force lazy recreation of data object
154      * 
155      * @param node
156      *            DOCUMENT ME!
157      */
158     protected void childRemoved(Node node) {
159         data = null;
160         super.childRemoved(node);
161     }
162 
163     protected void validate(String text) throws IllegalArgumentException {
164         try {
165             datatype.checkValid(text, this);
166         } catch (DatatypeException e) {
167             throw new IllegalArgumentException(e.getMessage());
168         }
169     }
170 }
171 
172 /*
173  * Redistribution and use of this software and associated documentation
174  * ("Software"), with or without modification, are permitted provided that the
175  * following conditions are met:
176  * 
177  * 1. Redistributions of source code must retain copyright statements and
178  * notices. Redistributions must also contain a copy of this document.
179  * 
180  * 2. Redistributions in binary form must reproduce the above copyright notice,
181  * this list of conditions and the following disclaimer in the documentation
182  * and/or other materials provided with the distribution.
183  * 
184  * 3. The name "DOM4J" must not be used to endorse or promote products derived
185  * from this Software without prior written permission of MetaStuff, Ltd. For
186  * written permission, please contact dom4j-info@metastuff.com.
187  * 
188  * 4. Products derived from this Software may not be called "DOM4J" nor may
189  * "DOM4J" appear in their names without prior written permission of MetaStuff,
190  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
191  * 
192  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
193  * 
194  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
195  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
196  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
197  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
198  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
199  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
200  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
201  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
202  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
203  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
204  * POSSIBILITY OF SUCH DAMAGE.
205  * 
206  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
207  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/datatype/DatatypeAttribute.html0000644000175000017500000004735110242117717023740 0ustar ebourgebourg DatatypeAttribute xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.datatype;
9   
10  import com.sun.msv.datatype.DatabindableDatatype;
11  import com.sun.msv.datatype.SerializationContext;
12  import com.sun.msv.datatype.xsd.XSDatatype;
13  
14  import org.dom4j.Element;
15  import org.dom4j.Namespace;
16  import org.dom4j.QName;
17  import org.dom4j.tree.AbstractAttribute;
18  
19  import org.relaxng.datatype.DatatypeException;
20  import org.relaxng.datatype.ValidationContext;
21  
22  /***
23   * <p>
24   * <code>DatatypeAttribute</code> represents an Attribute which supports the
25   * <a href="http://www.w3.org/TR/xmlschema-2/">XML Schema Data Types </a>
26   * specification.
27   * </p>
28   * 
29   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
30   * @version $Revision: 1.9 $
31   */
32  public class DatatypeAttribute extends AbstractAttribute implements
33          SerializationContext, ValidationContext {
34      /*** The parent <code>Element</code> of the <code>Attribute</code> */
35      private Element parent;
36  
37      /*** The <code>QName</code> for this element */
38      private QName qname;
39  
40      /*** The <code>XSDatatype</code> of the <code>Attribute</code> */
41      private XSDatatype datatype;
42  
43      /*** The data (Object) value of the <code>Attribute</code> */
44      private Object data;
45  
46      /*** The text value of the <code>Attribute</code> */
47      private String text;
48  
49      public DatatypeAttribute(QName qname, XSDatatype datatype) {
50          this.qname = qname;
51          this.datatype = datatype;
52      }
53  
54      public DatatypeAttribute(QName qname, XSDatatype datatype, String text) {
55          this.qname = qname;
56          this.datatype = datatype;
57          this.text = text;
58          this.data = convertToValue(text);
59      }
60  
61      public String toString() {
62          return getClass().getName() + hashCode() + " [Attribute: name "
63                  + getQualifiedName() + " value \"" + getValue() + "\" data: "
64                  + getData() + "]";
65      }
66  
67      /***
68       * Returns the MSV XSDatatype for this node
69       * 
70       * @return DOCUMENT ME!
71       */
72      public XSDatatype getXSDatatype() {
73          return datatype;
74      }
75  
76      // SerializationContext interface
77      // -------------------------------------------------------------------------
78      public String getNamespacePrefix(String uri) {
79          Element parentElement = getParent();
80  
81          if (parentElement != null) {
82              Namespace namespace = parentElement.getNamespaceForURI(uri);
83  
84              if (namespace != null) {
85                  return namespace.getPrefix();
86              }
87          }
88  
89          return null;
90      }
91  
92      // ValidationContext interface
93      // -------------------------------------------------------------------------
94      public String getBaseUri() {
95          // XXXX: could we use a Document for this?
96          return null;
97      }
98  
99      public boolean isNotation(String notationName) {
100         // XXXX: no way to do this yet in dom4j so assume false
101         return false;
102     }
103 
104     public boolean isUnparsedEntity(String entityName) {
105         // XXXX: no way to do this yet in dom4j so assume valid
106         return true;
107     }
108 
109     public String resolveNamespacePrefix(String prefix) {
110         // first lets see if this is our attribute's prefix
111         if (prefix.equals(getNamespacePrefix())) {
112             return getNamespaceURI();
113         } else {
114             Element parentElement = getParent();
115 
116             if (parentElement != null) {
117                 Namespace namespace = parentElement
118                         .getNamespaceForPrefix(prefix);
119 
120                 if (namespace != null) {
121                     return namespace.getURI();
122                 }
123             }
124         }
125 
126         return null;
127     }
128 
129     // Attribute interface
130     // -------------------------------------------------------------------------
131     public QName getQName() {
132         return qname;
133     }
134 
135     public String getValue() {
136         return text;
137     }
138 
139     public void setValue(String value) {
140         validate(value);
141 
142         this.text = value;
143         this.data = convertToValue(value);
144     }
145 
146     public Object getData() {
147         return data;
148     }
149 
150     public void setData(Object data) {
151         String s = datatype.convertToLexicalValue(data, this);
152         validate(s);
153         this.text = s;
154         this.data = data;
155     }
156 
157     public Element getParent() {
158         return parent;
159     }
160 
161     public void setParent(Element parent) {
162         this.parent = parent;
163     }
164 
165     public boolean supportsParent() {
166         return true;
167     }
168 
169     public boolean isReadOnly() {
170         return false;
171     }
172 
173     // Implementation methods
174     // -------------------------------------------------------------------------
175     protected void validate(String txt) throws IllegalArgumentException {
176         try {
177             datatype.checkValid(txt, this);
178         } catch (DatatypeException e) {
179             throw new IllegalArgumentException(e.getMessage());
180         }
181     }
182 
183     protected Object convertToValue(String txt) {
184         if (datatype instanceof DatabindableDatatype) {
185             DatabindableDatatype bindable = (DatabindableDatatype) datatype;
186 
187             return bindable.createJavaObject(txt, this);
188         } else {
189             return datatype.createValue(txt, this);
190         }
191     }
192 }
193 
194 /*
195  * Redistribution and use of this software and associated documentation
196  * ("Software"), with or without modification, are permitted provided that the
197  * following conditions are met:
198  * 
199  * 1. Redistributions of source code must retain copyright statements and
200  * notices. Redistributions must also contain a copy of this document.
201  * 
202  * 2. Redistributions in binary form must reproduce the above copyright notice,
203  * this list of conditions and the following disclaimer in the documentation
204  * and/or other materials provided with the distribution.
205  * 
206  * 3. The name "DOM4J" must not be used to endorse or promote products derived
207  * from this Software without prior written permission of MetaStuff, Ltd. For
208  * written permission, please contact dom4j-info@metastuff.com.
209  * 
210  * 4. Products derived from this Software may not be called "DOM4J" nor may
211  * "DOM4J" appear in their names without prior written permission of MetaStuff,
212  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
213  * 
214  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
215  * 
216  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
217  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
218  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
219  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
220  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
221  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
222  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
223  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
224  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
225  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
226  * POSSIBILITY OF SUCH DAMAGE.
227  * 
228  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
229  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/datatype/InvalidSchemaException.html0000644000175000017500000001461010242117650024653 0ustar ebourgebourg InvalidSchemaException xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.datatype;
9   
10  /***
11   * <p>
12   * <code>InvalidSchemaException</code> is thrown when an invalid XML Schema
13   * document is used
14   * </p>
15   * 
16   * @version $Revision: 1.6 $
17   */
18  public class InvalidSchemaException extends IllegalArgumentException {
19      public InvalidSchemaException(String reason) {
20          super(reason);
21      }
22  }
23  
24  /*
25   * Redistribution and use of this software and associated documentation
26   * ("Software"), with or without modification, are permitted provided that the
27   * following conditions are met:
28   * 
29   * 1. Redistributions of source code must retain copyright statements and
30   * notices. Redistributions must also contain a copy of this document.
31   * 
32   * 2. Redistributions in binary form must reproduce the above copyright notice,
33   * this list of conditions and the following disclaimer in the documentation
34   * and/or other materials provided with the distribution.
35   * 
36   * 3. The name "DOM4J" must not be used to endorse or promote products derived
37   * from this Software without prior written permission of MetaStuff, Ltd. For
38   * written permission, please contact dom4j-info@metastuff.com.
39   * 
40   * 4. Products derived from this Software may not be called "DOM4J" nor may
41   * "DOM4J" appear in their names without prior written permission of MetaStuff,
42   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
43   * 
44   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
45   * 
46   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
47   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
50   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
51   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
52   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
53   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
54   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
55   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
56   * POSSIBILITY OF SUCH DAMAGE.
57   * 
58   * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
59   */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/datatype/package-summary.html0000644000175000017500000000605210242117722023354 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.datatype

Class Summary
DatatypeAttribute
DatatypeDocumentFactory
DatatypeElement
DatatypeElementFactory
InvalidSchemaException
NamedTypeResolver
SchemaParser
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref/org/dom4j/datatype/DatatypeDocumentFactory.html0000644000175000017500000005403010242117556025074 0ustar ebourgebourg DatatypeDocumentFactory xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.datatype;
9   
10  import org.dom4j.Attribute;
11  import org.dom4j.Document;
12  import org.dom4j.DocumentFactory;
13  import org.dom4j.Element;
14  import org.dom4j.Namespace;
15  import org.dom4j.QName;
16  import org.dom4j.io.SAXReader;
17  
18  import org.xml.sax.EntityResolver;
19  import org.xml.sax.InputSource;
20  
21  /***
22   * <p>
23   * <code>DatatypeDocumentFactory</code> is a factory of XML objects which
24   * support the <a href="http://www.w3.org/TR/xmlschema-2/">XML Schema Data Types
25   * </a> specification.
26   * </p>
27   * 
28   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
29   * @version $Revision: 1.9 $
30   */
31  public class DatatypeDocumentFactory extends DocumentFactory {
32      // XXXX: I don't think interning of QNames is necessary
33      private static final boolean DO_INTERN_QNAME = false;
34  
35      /*** The Singleton instance */
36      protected static transient DatatypeDocumentFactory singleton 
37              = new DatatypeDocumentFactory();
38  
39      private static final Namespace XSI_NAMESPACE = Namespace.get("xsi",
40              "http://www.w3.org/2001/XMLSchema-instance");
41  
42      private static final QName XSI_SCHEMA_LOCATION = QName.get(
43              "schemaLocation", XSI_NAMESPACE);
44  
45      private static final QName XSI_NO_SCHEMA_LOCATION = QName.get(
46              "noNamespaceSchemaLocation", XSI_NAMESPACE);
47  
48      /*** The builder of XML Schemas */
49      private SchemaParser schemaBuilder;
50  
51      /*** reader of XML Schemas */
52      private SAXReader xmlSchemaReader = new SAXReader();
53  
54      /*** If schemas are automatically loaded when parsing instance documents */
55      private boolean autoLoadSchema = true;
56  
57      public DatatypeDocumentFactory() {
58          schemaBuilder = new SchemaParser(this);
59      }
60  
61      /***
62       * <p>
63       * Access to the singleton instance of this factory.
64       * </p>
65       * 
66       * @return the default singleon instance
67       */
68      public static DocumentFactory getInstance() {
69          return singleton;
70      }
71  
72      /***
73       * Loads the given XML Schema document into this factory so schema-aware
74       * Document, Elements and Attributes will be created by this factory.
75       * 
76       * @param schemaDocument
77       *            is an XML Schema Document instance.
78       */
79      public void loadSchema(Document schemaDocument) {
80          schemaBuilder.build(schemaDocument);
81      }
82  
83      public void loadSchema(Document schemaDocument, Namespace targetNamespace) {
84          schemaBuilder.build(schemaDocument, targetNamespace);
85      }
86  
87      /***
88       * Registers the given <code>DatatypeElementFactory</code> for the given
89       * &lt;element&gt; schema element
90       * 
91       * @param elementQName
92       *            DOCUMENT ME!
93       * 
94       * @return DOCUMENT ME!
95       */
96      public DatatypeElementFactory getElementFactory(QName elementQName) {
97          DatatypeElementFactory result = null;
98          
99          if (DO_INTERN_QNAME) {
100             elementQName = intern(elementQName);
101         }
102 
103         DocumentFactory factory = elementQName.getDocumentFactory();
104         if (factory instanceof DatatypeElementFactory) {
105             result = (DatatypeElementFactory) factory;
106         }
107         
108         return result;
109     }
110 
111     // DocumentFactory methods
112     // -------------------------------------------------------------------------
113     public Attribute createAttribute(Element owner, QName qname, String value) {
114         if (autoLoadSchema && qname.equals(XSI_NO_SCHEMA_LOCATION)) {
115             Document document = (owner != null) ? owner.getDocument() : null;
116             loadSchema(document, value);
117         } else if (autoLoadSchema && qname.equals(XSI_SCHEMA_LOCATION)) {
118             Document document = (owner != null) ? owner.getDocument() : null;
119             String uri = value.substring(0, value.indexOf(' '));
120             Namespace namespace = owner.getNamespaceForURI(uri);
121             loadSchema(document, value.substring(value.indexOf(' ') + 1),
122                     namespace);
123         }
124 
125         return super.createAttribute(owner, qname, value);
126     }
127 
128     // Implementation methods
129     // -------------------------------------------------------------------------
130     protected void loadSchema(Document document, String schemaInstanceURI) {
131         try {
132             EntityResolver resolver = document.getEntityResolver();
133 
134             if (resolver == null) {
135                 String msg = "No EntityResolver available for resolving URI: ";
136                 throw new InvalidSchemaException(msg + schemaInstanceURI);
137             }
138 
139             InputSource inputSource = resolver.resolveEntity(null,
140                     schemaInstanceURI);
141 
142             if (resolver == null) {
143                 throw new InvalidSchemaException("Could not resolve the URI: "
144                         + schemaInstanceURI);
145             }
146 
147             Document schemaDocument = xmlSchemaReader.read(inputSource);
148             loadSchema(schemaDocument);
149         } catch (Exception e) {
150             System.out.println("Failed to load schema: " + schemaInstanceURI);
151             System.out.println("Caught: " + e);
152             e.printStackTrace();
153             throw new InvalidSchemaException("Failed to load schema: "
154                     + schemaInstanceURI);
155         }
156     }
157 
158     protected void loadSchema(Document document, String schemaInstanceURI,
159             Namespace namespace) {
160         try {
161             EntityResolver resolver = document.getEntityResolver();
162 
163             if (resolver == null) {
164                 String msg = "No EntityResolver available for resolving URI: ";
165                 throw new InvalidSchemaException(msg + schemaInstanceURI);
166             }
167 
168             InputSource inputSource = resolver.resolveEntity(null,
169                     schemaInstanceURI);
170 
171             if (resolver == null) {
172                 throw new InvalidSchemaException("Could not resolve the URI: "
173                         + schemaInstanceURI);
174             }
175 
176             Document schemaDocument = xmlSchemaReader.read(inputSource);
177             loadSchema(schemaDocument, namespace);
178         } catch (Exception e) {
179             System.out.println("Failed to load schema: " + schemaInstanceURI);
180             System.out.println("Caught: " + e);
181             e.printStackTrace();
182             throw new InvalidSchemaException("Failed to load schema: "
183                     + schemaInstanceURI);
184         }
185     }
186 }
187 
188 /*
189  * Redistribution and use of this software and associated documentation
190  * ("Software"), with or without modification, are permitted provided that the
191  * following conditions are met:
192  * 
193  * 1. Redistributions of source code must retain copyright statements and
194  * notices. Redistributions must also contain a copy of this document.
195  * 
196  * 2. Redistributions in binary form must reproduce the above copyright notice,
197  * this list of conditions and the following disclaimer in the documentation
198  * and/or other materials provided with the distribution.
199  * 
200  * 3. The name "DOM4J" must not be used to endorse or promote products derived
201  * from this Software without prior written permission of MetaStuff, Ltd. For
202  * written permission, please contact dom4j-info@metastuff.com.
203  * 
204  * 4. Products derived from this Software may not be called "DOM4J" nor may
205  * "DOM4J" appear in their names without prior written permission of MetaStuff,
206  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
207  * 
208  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
209  * 
210  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
211  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
212  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
213  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
214  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
215  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
216  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
217  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
218  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
219  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
220  * POSSIBILITY OF SUCH DAMAGE.
221  * 
222  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
223  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/datatype/package-frame.html0000644000175000017500000000273210242117746022760 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.datatype

org.dom4j.datatype

Classes

  • DatatypeAttribute
  • DatatypeDocumentFactory
  • DatatypeElement
  • DatatypeElementFactory
  • InvalidSchemaException
  • NamedTypeResolver
  • SchemaParser
dom4j-1.6.1/docs/xref/org/dom4j/datatype/DatatypeElementFactory.html0000644000175000017500000003712010242117721024702 0ustar ebourgebourg DatatypeElementFactory xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.datatype;
9   
10  import com.sun.msv.datatype.xsd.XSDatatype;
11  
12  import java.util.HashMap;
13  import java.util.Map;
14  
15  import org.dom4j.Attribute;
16  import org.dom4j.DocumentFactory;
17  import org.dom4j.Element;
18  import org.dom4j.QName;
19  
20  /***
21   * <p>
22   * <code>DatatypeElementFactory</code> is a factory for a specific Element in
23   * an XML Schema.
24   * </p>
25   * 
26   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
27   * @author Yuxin Ruan
28   * @version $Revision: 1.9 $
29   */
30  public class DatatypeElementFactory extends DocumentFactory {
31      private QName elementQName;
32  
33      /***
34       * Cache of <code>XSDatatype</code> instances per Attribute
35       * <code>QName</code>
36       */
37      private Map attributeXSDatatypes = new HashMap();
38  
39      /***
40       * Cache of <code>XSDatatype</code> instances per child Element
41       * <code>QName</code>
42       */
43      private Map childrenXSDatatypes = new HashMap();
44  
45      public DatatypeElementFactory(QName elementQName) {
46          this.elementQName = elementQName;
47      }
48  
49      /***
50       * DOCUMENT ME!
51       * 
52       * @return the QName this element factory is associated with
53       */
54      public QName getQName() {
55          return elementQName;
56      }
57  
58      /***
59       * DOCUMENT ME!
60       * 
61       * @param attributeQName
62       *            DOCUMENT ME!
63       * 
64       * @return the <code>XSDatatype</code> associated with the given Attribute
65       *         QName
66       */
67      public XSDatatype getAttributeXSDatatype(QName attributeQName) {
68          return (XSDatatype) attributeXSDatatypes.get(attributeQName);
69      }
70  
71      /***
72       * Registers the given <code>XSDatatype</code> for the given
73       * &lt;attribute&gt; QNames
74       * 
75       * @param attributeQName
76       *            DOCUMENT ME!
77       * @param type
78       *            DOCUMENT ME!
79       */
80      public void setAttributeXSDatatype(QName attributeQName, XSDatatype type) {
81          attributeXSDatatypes.put(attributeQName, type);
82      }
83  
84      /***
85       * DOCUMENT ME!
86       * 
87       * @param qname
88       *            DOCUMENT ME!
89       * 
90       * @return the <code>XSDatatype</code> associated with the given child
91       *         Element QName
92       */
93      public XSDatatype getChildElementXSDatatype(QName qname) {
94          return (XSDatatype) childrenXSDatatypes.get(qname);
95      }
96  
97      public void setChildElementXSDatatype(QName qname, XSDatatype dataType) {
98          childrenXSDatatypes.put(qname, dataType);
99      }
100 
101     // DocumentFactory methods
102     // -------------------------------------------------------------------------
103     public Element createElement(QName qname) {
104         // the element may have its own element factory!
105         // use factory from the qname for datatype
106         XSDatatype dataType = getChildElementXSDatatype(qname);
107 
108         if (dataType != null) {
109             return new DatatypeElement(qname, dataType);
110         }
111 
112         DocumentFactory factory = qname.getDocumentFactory();
113 
114         if (factory instanceof DatatypeElementFactory) {
115             DatatypeElementFactory dtFactory = (DatatypeElementFactory) factory;
116             dataType = dtFactory.getChildElementXSDatatype(qname);
117 
118             if (dataType != null) {
119                 return new DatatypeElement(qname, dataType);
120             }
121         }
122 
123         return super.createElement(qname);
124     }
125 
126     public Attribute createAttribute(Element owner, QName qname, String value) {
127         XSDatatype dataType = getAttributeXSDatatype(qname);
128 
129         if (dataType == null) {
130             return super.createAttribute(owner, qname, value);
131         } else {
132             return new DatatypeAttribute(qname, dataType, value);
133         }
134     }
135 }
136 
137 /*
138  * Redistribution and use of this software and associated documentation
139  * ("Software"), with or without modification, are permitted provided that the
140  * following conditions are met:
141  * 
142  * 1. Redistributions of source code must retain copyright statements and
143  * notices. Redistributions must also contain a copy of this document.
144  * 
145  * 2. Redistributions in binary form must reproduce the above copyright notice,
146  * this list of conditions and the following disclaimer in the documentation
147  * and/or other materials provided with the distribution.
148  * 
149  * 3. The name "DOM4J" must not be used to endorse or promote products derived
150  * from this Software without prior written permission of MetaStuff, Ltd. For
151  * written permission, please contact dom4j-info@metastuff.com.
152  * 
153  * 4. Products derived from this Software may not be called "DOM4J" nor may
154  * "DOM4J" appear in their names without prior written permission of MetaStuff,
155  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
156  * 
157  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
158  * 
159  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
160  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
161  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
162  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
163  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
164  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
165  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
166  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
167  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
168  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
169  * POSSIBILITY OF SUCH DAMAGE.
170  * 
171  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
172  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/datatype/NamedTypeResolver.html0000644000175000017500000003043610242117744023705 0ustar ebourgebourg NamedTypeResolver xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.datatype;
9   
10  import com.sun.msv.datatype.xsd.XSDatatype;
11  
12  import java.util.HashMap;
13  import java.util.Iterator;
14  import java.util.Map;
15  
16  import org.dom4j.DocumentFactory;
17  import org.dom4j.Element;
18  import org.dom4j.QName;
19  
20  /***
21   * <p>
22   * <code>NamedTypeResolver</code> resolves named types for a given QName.
23   * </p>
24   * 
25   * @author Yuxin Ruan
26   * @version $Revision: 1.8 $
27   */
28  class NamedTypeResolver {
29      protected Map complexTypeMap = new HashMap();
30  
31      protected Map simpleTypeMap = new HashMap();
32  
33      protected Map typedElementMap = new HashMap();
34  
35      protected Map elementFactoryMap = new HashMap();
36  
37      protected DocumentFactory documentFactory;
38  
39      NamedTypeResolver(DocumentFactory documentFactory) {
40          this.documentFactory = documentFactory;
41      }
42  
43      void registerComplexType(QName type, DocumentFactory factory) {
44          complexTypeMap.put(type, factory);
45      }
46  
47      void registerSimpleType(QName type, XSDatatype datatype) {
48          simpleTypeMap.put(type, datatype);
49      }
50  
51      void registerTypedElement(Element element, QName type,
52              DocumentFactory parentFactory) {
53          typedElementMap.put(element, type);
54          elementFactoryMap.put(element, parentFactory);
55      }
56  
57      void resolveElementTypes() {
58          Iterator iterator = typedElementMap.keySet().iterator();
59  
60          while (iterator.hasNext()) {
61              Element element = (Element) iterator.next();
62              QName elementQName = getQNameOfSchemaElement(element);
63              QName type = (QName) typedElementMap.get(element);
64  
65              if (complexTypeMap.containsKey(type)) {
66                  DocumentFactory factory = (DocumentFactory) complexTypeMap
67                          .get(type);
68                  elementQName.setDocumentFactory(factory);
69              } else if (simpleTypeMap.containsKey(type)) {
70                  XSDatatype datatype = (XSDatatype) simpleTypeMap.get(type);
71                  DocumentFactory factory = (DocumentFactory) elementFactoryMap
72                          .get(element);
73  
74                  if (factory instanceof DatatypeElementFactory) {
75                      ((DatatypeElementFactory) factory)
76                              .setChildElementXSDatatype(elementQName, datatype);
77                  }
78              }
79          }
80      }
81  
82      void resolveNamedTypes() {
83          resolveElementTypes();
84      }
85  
86      private QName getQNameOfSchemaElement(Element element) {
87          String name = element.attributeValue("name");
88  
89          return getQName(name);
90      }
91  
92      private QName getQName(String name) {
93          return documentFactory.createQName(name);
94      }
95  }
96  
97  /*
98   * Redistribution and use of this software and associated documentation
99   * ("Software"), with or without modification, are permitted provided that the
100  * following conditions are met:
101  * 
102  * 1. Redistributions of source code must retain copyright statements and
103  * notices. Redistributions must also contain a copy of this document.
104  * 
105  * 2. Redistributions in binary form must reproduce the above copyright notice,
106  * this list of conditions and the following disclaimer in the documentation
107  * and/or other materials provided with the distribution.
108  * 
109  * 3. The name "DOM4J" must not be used to endorse or promote products derived
110  * from this Software without prior written permission of MetaStuff, Ltd. For
111  * written permission, please contact dom4j-info@metastuff.com.
112  * 
113  * 4. Products derived from this Software may not be called "DOM4J" nor may
114  * "DOM4J" appear in their names without prior written permission of MetaStuff,
115  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
116  * 
117  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
118  * 
119  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
120  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
121  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
122  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
123  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
124  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
125  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
126  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
127  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
128  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
129  * POSSIBILITY OF SUCH DAMAGE.
130  * 
131  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
132  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/xpath/0000755000175000017500000000000012133227266016714 5ustar ebourgebourgdom4j-1.6.1/docs/xref/org/dom4j/xpath/DefaultNamespaceContext.html0000644000175000017500000002360410242117757024357 0ustar ebourgebourg DefaultNamespaceContext xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import java.io.Serializable;
11  
12  import org.dom4j.Document;
13  import org.dom4j.Element;
14  import org.dom4j.Namespace;
15  import org.dom4j.Node;
16  
17  import org.jaxen.NamespaceContext;
18  
19  /***
20   * <p>
21   * <code>DefaultNamespaceContext</code> implements a Jaxen NamespaceContext
22   * such that a context node is used to determine the current XPath namespace
23   * prefixes and namespace URIs available.
24   * </p>
25   * 
26   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
27   */
28  public class DefaultNamespaceContext implements NamespaceContext, Serializable {
29      private final Element element;
30  
31      public DefaultNamespaceContext(Element element) {
32          this.element = element;
33      }
34  
35      public static DefaultNamespaceContext create(Object node) {
36          Element element = null;
37  
38          if (node instanceof Element) {
39              element = (Element) node;
40          } else if (node instanceof Document) {
41              Document doc = (Document) node;
42              element = doc.getRootElement();
43          } else if (node instanceof Node) {
44              element = ((Node) node).getParent();
45          }
46  
47          if (element != null) {
48              return new DefaultNamespaceContext(element);
49          }
50  
51          return null;
52      }
53  
54      public String translateNamespacePrefixToUri(String prefix) {
55          if ((prefix != null) && (prefix.length() > 0)) {
56              Namespace ns = element.getNamespaceForPrefix(prefix);
57  
58              if (ns != null) {
59                  return ns.getURI();
60              }
61          }
62  
63          return null;
64      }
65  }
66  
67  /*
68   * Redistribution and use of this software and associated documentation
69   * ("Software"), with or without modification, are permitted provided that the
70   * following conditions are met:
71   * 
72   * 1. Redistributions of source code must retain copyright statements and
73   * notices. Redistributions must also contain a copy of this document.
74   * 
75   * 2. Redistributions in binary form must reproduce the above copyright notice,
76   * this list of conditions and the following disclaimer in the documentation
77   * and/or other materials provided with the distribution.
78   * 
79   * 3. The name "DOM4J" must not be used to endorse or promote products derived
80   * from this Software without prior written permission of MetaStuff, Ltd. For
81   * written permission, please contact dom4j-info@metastuff.com.
82   * 
83   * 4. Products derived from this Software may not be called "DOM4J" nor may
84   * "DOM4J" appear in their names without prior written permission of MetaStuff,
85   * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
86   * 
87   * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
88   * 
89   * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
90   * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
91   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
92   * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
93   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
94   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
95   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
96   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
97   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
98   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
99   * POSSIBILITY OF SUCH DAMAGE.
100  * 
101  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
102  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/xpath/DefaultXPath.html0000644000175000017500000007725610242117752022151 0ustar ebourgebourg DefaultXPath xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import java.io.Serializable;
11  import java.util.Collections;
12  import java.util.Comparator;
13  import java.util.HashMap;
14  import java.util.HashSet;
15  import java.util.Iterator;
16  import java.util.List;
17  import java.util.Map;
18  
19  import org.dom4j.InvalidXPathException;
20  import org.dom4j.Node;
21  import org.dom4j.NodeFilter;
22  import org.dom4j.XPathException;
23  
24  import org.jaxen.FunctionContext;
25  import org.jaxen.JaxenException;
26  import org.jaxen.NamespaceContext;
27  import org.jaxen.SimpleNamespaceContext;
28  import org.jaxen.VariableContext;
29  import org.jaxen.XPath;
30  import org.jaxen.dom4j.Dom4jXPath;
31  
32  /***
33   * <p>
34   * Default implementation of {@link org.dom4j.XPath}which uses the <a
35   * href="http://jaxen.org">Jaxen </a> project.
36   * </p>
37   * 
38   * @author bob mcwhirter
39   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
40   */
41  public class DefaultXPath implements org.dom4j.XPath, NodeFilter, Serializable {
42      private String text;
43  
44      private XPath xpath;
45  
46      private NamespaceContext namespaceContext;
47  
48      /***
49       * Construct an XPath
50       * 
51       * @param text
52       *            DOCUMENT ME!
53       * 
54       * @throws InvalidXPathException
55       *             DOCUMENT ME!
56       */
57      public DefaultXPath(String text) throws InvalidXPathException {
58          this.text = text;
59          this.xpath = parse(text);
60      }
61  
62      public String toString() {
63          return "[XPath: " + xpath + "]";
64      }
65  
66      // XPath interface
67  
68      /***
69       * Retrieve the textual XPath string used to initialize this Object
70       * 
71       * @return The XPath string
72       */
73      public String getText() {
74          return text;
75      }
76  
77      public FunctionContext getFunctionContext() {
78          return xpath.getFunctionContext();
79      }
80  
81      public void setFunctionContext(FunctionContext functionContext) {
82          xpath.setFunctionContext(functionContext);
83      }
84  
85      public NamespaceContext getNamespaceContext() {
86          return namespaceContext;
87      }
88  
89      public void setNamespaceURIs(Map map) {
90          setNamespaceContext(new SimpleNamespaceContext(map));
91      }
92  
93      public void setNamespaceContext(NamespaceContext namespaceContext) {
94          this.namespaceContext = namespaceContext;
95          xpath.setNamespaceContext(namespaceContext);
96      }
97  
98      public VariableContext getVariableContext() {
99          return xpath.getVariableContext();
100     }
101 
102     public void setVariableContext(VariableContext variableContext) {
103         xpath.setVariableContext(variableContext);
104     }
105 
106     public Object evaluate(Object context) {
107         try {
108             setNSContext(context);
109 
110             List answer = xpath.selectNodes(context);
111 
112             if ((answer != null) && (answer.size() == 1)) {
113                 return answer.get(0);
114             }
115 
116             return answer;
117         } catch (JaxenException e) {
118             handleJaxenException(e);
119 
120             return null;
121         }
122     }
123 
124     public Object selectObject(Object context) {
125         return evaluate(context);
126     }
127 
128     public List selectNodes(Object context) {
129         try {
130             setNSContext(context);
131 
132             return xpath.selectNodes(context);
133         } catch (JaxenException e) {
134             handleJaxenException(e);
135 
136             return Collections.EMPTY_LIST;
137         }
138     }
139 
140     public List selectNodes(Object context, org.dom4j.XPath sortXPath) {
141         List answer = selectNodes(context);
142         sortXPath.sort(answer);
143 
144         return answer;
145     }
146 
147     public List selectNodes(Object context, org.dom4j.XPath sortXPath,
148             boolean distinct) {
149         List answer = selectNodes(context);
150         sortXPath.sort(answer, distinct);
151 
152         return answer;
153     }
154 
155     public Node selectSingleNode(Object context) {
156         try {
157             setNSContext(context);
158 
159             Object answer = xpath.selectSingleNode(context);
160 
161             if (answer instanceof Node) {
162                 return (Node) answer;
163             }
164 
165             if (answer == null) {
166                 return null;
167             }
168 
169             throw new XPathException("The result of the XPath expression is "
170                     + "not a Node. It was: " + answer + " of type: "
171                     + answer.getClass().getName());
172         } catch (JaxenException e) {
173             handleJaxenException(e);
174 
175             return null;
176         }
177     }
178 
179     public String valueOf(Object context) {
180         try {
181             setNSContext(context);
182 
183             return xpath.stringValueOf(context);
184         } catch (JaxenException e) {
185             handleJaxenException(e);
186 
187             return "";
188         }
189     }
190 
191     public Number numberValueOf(Object context) {
192         try {
193             setNSContext(context);
194 
195             return xpath.numberValueOf(context);
196         } catch (JaxenException e) {
197             handleJaxenException(e);
198 
199             return null;
200         }
201     }
202 
203     public boolean booleanValueOf(Object context) {
204         try {
205             setNSContext(context);
206 
207             return xpath.booleanValueOf(context);
208         } catch (JaxenException e) {
209             handleJaxenException(e);
210 
211             return false;
212         }
213     }
214 
215     /***
216      * <p>
217      * <code>sort</code> sorts the given List of Nodes using this XPath
218      * expression as a {@link Comparator}.
219      * </p>
220      * 
221      * @param list
222      *            is the list of Nodes to sort
223      */
224     public void sort(List list) {
225         sort(list, false);
226     }
227 
228     /***
229      * <p>
230      * <code>sort</code> sorts the given List of Nodes using this XPath
231      * expression as a {@link Comparator}and optionally removing duplicates.
232      * </p>
233      * 
234      * @param list
235      *            is the list of Nodes to sort
236      * @param distinct
237      *            if true then duplicate values (using the sortXPath for
238      *            comparisions) will be removed from the List
239      */
240     public void sort(List list, boolean distinct) {
241         if ((list != null) && !list.isEmpty()) {
242             int size = list.size();
243             HashMap sortValues = new HashMap(size);
244 
245             for (int i = 0; i < size; i++) {
246                 Object object = list.get(i);
247 
248                 if (object instanceof Node) {
249                     Node node = (Node) object;
250                     Object expression = getCompareValue(node);
251                     sortValues.put(node, expression);
252                 }
253             }
254 
255             sort(list, sortValues);
256 
257             if (distinct) {
258                 removeDuplicates(list, sortValues);
259             }
260         }
261     }
262 
263     public boolean matches(Node node) {
264         try {
265             setNSContext(node);
266 
267             List answer = xpath.selectNodes(node);
268 
269             if ((answer != null) && (answer.size() > 0)) {
270                 Object item = answer.get(0);
271 
272                 if (item instanceof Boolean) {
273                     return ((Boolean) item).booleanValue();
274                 }
275 
276                 return answer.contains(node);
277             }
278 
279             return false;
280         } catch (JaxenException e) {
281             handleJaxenException(e);
282 
283             return false;
284         }
285     }
286 
287     /***
288      * Sorts the list based on the sortValues for each node
289      * 
290      * @param list
291      *            DOCUMENT ME!
292      * @param sortValues
293      *            DOCUMENT ME!
294      */
295     protected void sort(List list, final Map sortValues) {
296         Collections.sort(list, new Comparator() {
297             public int compare(Object o1, Object o2) {
298                 o1 = sortValues.get(o1);
299                 o2 = sortValues.get(o2);
300 
301                 if (o1 == o2) {
302                     return 0;
303                 } else if (o1 instanceof Comparable) {
304                     Comparable c1 = (Comparable) o1;
305 
306                     return c1.compareTo(o2);
307                 } else if (o1 == null) {
308                     return 1;
309                 } else if (o2 == null) {
310                     return -1;
311                 } else {
312                     return o1.equals(o2) ? 0 : (-1);
313                 }
314             }
315         });
316     }
317 
318     // Implementation methods
319 
320     /***
321      * Removes items from the list which have duplicate values
322      * 
323      * @param list
324      *            DOCUMENT ME!
325      * @param sortValues
326      *            DOCUMENT ME!
327      */
328     protected void removeDuplicates(List list, Map sortValues) {
329         // remove distinct
330         HashSet distinctValues = new HashSet();
331 
332         for (Iterator iter = list.iterator(); iter.hasNext();) {
333             Object node = iter.next();
334             Object value = sortValues.get(node);
335 
336             if (distinctValues.contains(value)) {
337                 iter.remove();
338             } else {
339                 distinctValues.add(value);
340             }
341         }
342     }
343 
344     /***
345      * DOCUMENT ME!
346      * 
347      * @param node
348      *            DOCUMENT ME!
349      * 
350      * @return the node expression used for sorting comparisons
351      */
352     protected Object getCompareValue(Node node) {
353         return valueOf(node);
354     }
355 
356     protected static XPath parse(String text) {
357         try {
358             return new Dom4jXPath(text);
359         } catch (JaxenException e) {
360             throw new InvalidXPathException(text, e.getMessage());
361         } catch (Throwable t) {
362         	throw new InvalidXPathException(text, t);
363         }
364     }
365 
366     protected void setNSContext(Object context) {
367         if (namespaceContext == null) {
368             xpath.setNamespaceContext(DefaultNamespaceContext.create(context));
369         }
370     }
371 
372     protected void handleJaxenException(JaxenException exception)
373             throws XPathException {
374         throw new XPathException(text, exception);
375     }
376 }
377 
378 /*
379  * Redistribution and use of this software and associated documentation
380  * ("Software"), with or without modification, are permitted provided that the
381  * following conditions are met:
382  * 
383  * 1. Redistributions of source code must retain copyright statements and
384  * notices. Redistributions must also contain a copy of this document.
385  * 
386  * 2. Redistributions in binary form must reproduce the above copyright notice,
387  * this list of conditions and the following disclaimer in the documentation
388  * and/or other materials provided with the distribution.
389  * 
390  * 3. The name "DOM4J" must not be used to endorse or promote products derived
391  * from this Software without prior written permission of MetaStuff, Ltd. For
392  * written permission, please contact dom4j-info@metastuff.com.
393  * 
394  * 4. Products derived from this Software may not be called "DOM4J" nor may
395  * "DOM4J" appear in their names without prior written permission of MetaStuff,
396  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
397  * 
398  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
399  * 
400  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
401  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
402  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
403  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
404  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
405  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
406  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
407  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
408  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
409  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
410  * POSSIBILITY OF SUCH DAMAGE.
411  * 
412  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
413  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/xref/org/dom4j/xpath/package-summary.html0000644000175000017500000000451510242117721022666 0ustar ebourgebourg dom4j 1.6.1 Reference Package
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Package org.dom4j.xpath

Class Summary
DefaultNamespaceContext
DefaultXPath
XPathPattern
  • Overview
  • Package
  • FRAMES
  • NO FRAMES

Copyright © 2001-2005 MetaStuff Ltd.. All Rights Reserved. dom4j-1.6.1/docs/xref/org/dom4j/xpath/package-frame.html0000644000175000017500000000167610242117713022271 0ustar ebourgebourg dom4j 1.6.1 Reference Package org.dom4j.xpath

org.dom4j.xpath

Classes

  • DefaultNamespaceContext
  • DefaultXPath
  • XPathPattern
dom4j-1.6.1/docs/xref/org/dom4j/xpath/XPathPattern.html0000644000175000017500000003514710242117744022174 0ustar ebourgebourg XPathPattern xref
View Javadoc

1   /*
2    * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    */
7   
8   package org.dom4j.xpath;
9   
10  import java.util.ArrayList;
11  
12  import org.dom4j.InvalidXPathException;
13  import org.dom4j.Node;
14  import org.dom4j.XPathException;
15  
16  import org.jaxen.Context;
17  import org.jaxen.ContextSupport;
18  import org.jaxen.JaxenException;
19  import org.jaxen.SimpleNamespaceContext;
20  import org.jaxen.SimpleVariableContext;
21  import org.jaxen.VariableContext;
22  import org.jaxen.XPathFunctionContext;
23  import org.jaxen.dom4j.DocumentNavigator;
24  import org.jaxen.pattern.Pattern;
25  import org.jaxen.pattern.PatternParser;
26  import org.jaxen.saxpath.SAXPathException;
27  
28  /***
29   * <p>
30   * <code>XPathPattern</code> is an implementation of Pattern which uses an
31   * XPath xpath.
32   * </p>
33   * 
34   * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
35   * @version $Revision: 1.18.2.1 $
36   */
37  public class XPathPattern implements org.dom4j.rule.Pattern {
38      private String text;
39  
40      private Pattern pattern;
41  
42      private Context context;
43  
44      public XPathPattern(Pattern pattern) {
45          this.pattern = pattern;
46          this.text = pattern.getText();
47          this.context = new Context(getContextSupport());
48      }
49  
50      public XPathPattern(String text) {
51          this.text = text;
52          this.context = new Context(getContextSupport());
53  
54          try {
55              this.pattern = PatternParser.parse(text);
56          } catch (SAXPathException e) {
57              throw new InvalidXPathException(text, e.getMessage());
58          } catch (Throwable t) {
59              throw new InvalidXPathException(text, t);
60          }
61      }
62  
63      public boolean matches(Node node) {
64          try {
65              ArrayList list = new ArrayList(1);
66              list.add(node);
67              context.setNodeSet(list);
68  
69              return pattern.matches(node, context);
70          } catch (JaxenException e) {
71              handleJaxenException(e);
72  
73              return false;
74          }
75      }
76  
77      public String getText() {
78          return text;
79      }
80  
81      public double getPriority() {
82          return pattern.getPriority();
83      }
84  
85      public org.dom4j.rule.Pattern[] getUnionPatterns() {
86          Pattern[] patterns = pattern.getUnionPatterns();
87  
88          if (patterns != null) {
89              int size = patterns.length;
90              XPathPattern[] answer = new XPathPattern[size];
91  
92              for (int i = 0; i < size; i++) {
93                  answer[i] = new XPathPattern(patterns[i]);
94              }
95  
96              return answer;
97          }
98  
99          return null;
100     }
101 
102     public short getMatchType() {
103         return pattern.getMatchType();
104     }
105 
106     public String getMatchesNodeName() {
107         return pattern.getMatchesNodeName();
108     }
109 
110     public void setVariableContext(VariableContext variableContext) {
111         context.getContextSupport().setVariableContext(variableContext);
112     }
113 
114     public String toString() {
115         return "[XPathPattern: text: " + text + " Pattern: " + pattern + "]";
116     }
117 
118     protected ContextSupport getContextSupport() {
119         return new ContextSupport(new SimpleNamespaceContext(),
120                 XPathFunctionContext.getInstance(),
121                 new SimpleVariableContext(), DocumentNavigator.getInstance());
122     }
123 
124     protected void handleJaxenException(JaxenException exception)
125             throws XPathException {
126         throw new XPathException(text, exception);
127     }
128 }
129 
130 /*
131  * Redistribution and use of this software and associated documentation
132  * ("Software"), with or without modification, are permitted provided that the
133  * following conditions are met:
134  * 
135  * 1. Redistributions of source code must retain copyright statements and
136  * notices. Redistributions must also contain a copy of this document.
137  * 
138  * 2. Redistributions in binary form must reproduce the above copyright notice,
139  * this list of conditions and the following disclaimer in the documentation
140  * and/or other materials provided with the distribution.
141  * 
142  * 3. The name "DOM4J" must not be used to endorse or promote products derived
143  * from this Software without prior written permission of MetaStuff, Ltd. For
144  * written permission, please contact dom4j-info@metastuff.com.
145  * 
146  * 4. Products derived from this Software may not be called "DOM4J" nor may
147  * "DOM4J" appear in their names without prior written permission of MetaStuff,
148  * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
149  * 
150  * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
151  * 
152  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
153  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
154  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
155  * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
156  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
157  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
158  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
159  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
160  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
161  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
162  * POSSIBILITY OF SUCH DAMAGE.
163  * 
164  * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
165  */

This page was automatically generated by Maven
dom4j-1.6.1/docs/dependencies.html0000644000175000017500000001737510242117564016347 0ustar ebourgebourgdom4j - Dependencies
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
    • Mailing Lists
    • Project Team
    • Dependencies
    • Source Repository
    • Issue Tracking
  • Project Reports
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Dependencies

The following is a list of dependencies for this project. These dependencies are required to compile and run the application:

Artifact IDTypeVersionURL
jaxenjar1.1-beta-6 http://jaxen.codehaus.org/
jaxme-apijar0.3 http://ws.apache.org/jaxme/index.html
junitperfjar1.8 http://www.clarkware.com/software/JUnitPerf.html
relaxngDatatypejar20030807 https://msv.dev.java.net/
xsdlibjar20030807 https://msv.dev.java.net/
pull-parserjar2 http://www.extreme.indiana.edu/xgws/xsoap/xpp/
staxjar1.0 http://jcp.org/aboutJava/communityprocess/final/jsr173/index.html
stax-rijar1.0 http://dev2dev.bea.com/technologies/stax/index.jsp
xalanjar2.5.1 http://xml.apache.org/xalan-j/index.html
xercesImpljar2.6.2 http://xml.apache.org/xerces2-j/index.html
xml-apisjar2.0.2 http://xml.apache.org/xerces2-j/index.html
xpp3jar1.1.3.3 http://www.extreme.indiana.edu/xgws/xsoap/xpp/

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/download.html0000644000175000017500000001420710242117744015517 0ustar ebourgebourgdom4j - Download dom4j
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Download the current release

The current release can be downloaded at SourceForge

Download a snapshot build

You can download an interim snapshot build from the Maven repository

Obtaining the latest CVS snapshot

You can browse the current CVS repository here

To learn more about CVS go here.

Anonymous CVS Access

This project's SourceForge CVS repository can be checked out through anonymous (pserver) CVS with the following instruction set. When prompted for a password for anonymous, simply press the Enter key.

cvs -d:pserver:anonymous@cvs.dom4j.org:/cvsroot/dom4j login 

cvs -d:pserver:anonymous@cvs.dom4j.org:/cvsroot/dom4j co dom4j
        

Updates from within the module's directory do not need the -d parameter.

Developer CVS Access via SSH

Only project developers can access the CVS tree via this method. SSH1 must be installed on your client machine. Substitute developername with the proper values. Enter your site password when prompted.

export CVS_RSH=ssh 
 
cvs -d:ext:developername@cvs.dom4j.org:/cvsroot/dom4j co dom4j
        

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/apidocs/0000755000175000017500000000000012133227266014442 5ustar ebourgebourgdom4j-1.6.1/docs/team-list.html0000644000175000017500000002555310242117662015614 0ustar ebourgebourgdom4j - Project Team
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
    • Mailing Lists
    • Project Team
    • Dependencies
    • Source Repository
    • Issue Tracking
  • Project Reports
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

The Team

A successful project requires many people to play many roles. Some members write code or documentation, while others are valuable as testers, submitting patches and suggestions.

The team is comprised of Members and Contributors. Members have direct access to the source of a project and actively evolve the code-base. Contributors improve the project through submission of patches and suggestions to the Members. The number of Contributors to the project is unbounded. Get involved today. All contributions to the project are greatly appreciated.

Members

The following is a list of developers with commit privileges that have directly contributed to the project in one way or another.

NameIdEmailOrganizationRolesTZ OffsetTime
Curt Arnoldcarnoldcarnold@users.sourceforge.net Unknown
David Lucasddlucasddlucas@users.sourceforge.net Unknown
David Whitedrwhitedrwhite@users.sourceforge.net Unknown
Jakob Jenkovjjenkovjjenkov@users.sourceforge.net Unknown
James Strachanjstrachanjstrachan@apache.orgSpiritSoft, Inc. Unknown
Laramie Crockerlaramieclaramiec@users.sourceforge.net Unknown
Maarten Coenemaartencmaartenc@users.sourceforge.netCronos Unknown
Michael Skellsmskellsmskells@users.sourceforge.net Unknown
Nick Sandersonnicksandersonnicksanderson@users.sourceforge.net Unknown
Steen Lehmannslehmannslehmann@users.sourceforge.net Unknown
Tobias Rademachertrademtradem@users.sourceforge.net Unknown
Bob McWhirterwerkenwerken@users.sourceforge.net Unknown
Todd Wolffwolfftwwolfftw@users.sourceforge.net Unknown
OuYang Chenyeekeeyeekee@users.sourceforge.net Unknown
Yuxin Ruanyruan2yruan2@users.sourceforge.net Unknown

Contributors

There are no contributors listed for this project. Please check back again later.


2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/project-info.html0000644000175000017500000001406410242117744016310 0ustar ebourgebourgdom4j - Project Information
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
    • Mailing Lists
    • Project Team
    • Dependencies
    • Source Repository
    • Issue Tracking
  • Project Reports
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

General Project Information

This document provides an overview of the various documents and links that are part of this project's general information. All of this content is automatically generated by Maven on behalf of the project.

Overview

DocumentDescription
Mailing Lists This document provides subscription and archive information for this project's mailing lists.
Project Team This document provides information on the members of this project. These are the individuals who have contributed to the project in one form or another.
Dependencies This document lists the projects dependencies and provides information on each dependency.
Source Repository This is a link to the online source repository that can be viewed via a web browser.
Issue Tracking This is a link to the issue tracking system for this project. Issues (bugs, features, change requests) can be created and queried using this link.

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/junit-report.html0000644000175000017500000042333710242117655016363 0ustar ebourgebourgdom4j - JUnit Test Results
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
    • Change Log
    • Changes
    • Checkstyle
    • Clover
    • Developer Activity
    • FAQs
    • File Activity
    • JavaDocs
    • JavaDoc Report
    • JavaDoc Warnings Report
    • Metrics
    • Unit Tests
    • Source Xref
    • Test Xref
    • Project License
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Summary

[ summary] [ package list] [ test cases]

TestsErrorsFailuresSuccess rateTime(s)
39100100,00%56,79

Note: failuresare anticipated and checked for with assertions while errorsare unanticipated.

Package List

[ summary] [ package list] [ test cases]

PackageTestsErrorsFailuresSuccess RateTime
org.dom4j 24400100,00%31,27
org.dom4j.bean 100100,00%3,18
org.dom4j.datatype 5300100,00%4,88
org.dom4j.dom 400100,00%0,49
org.dom4j.dtd 1000100,00%1,20
org.dom4j.io 2500100,00%3,68
org.dom4j.rule 1000100,00%1,34
org.dom4j.swing 200100,00%0,55
org.dom4j.tree 1900100,00%1,83
org.dom4j.util 200100,00%0,24
org.dom4j.xpath 2100100,00%8,13

Note: package statistics are not computed recursively, they only sum up all of its testsuites numbers.

org.dom4j

ClassTestsErrorsFailuresSuccess RateTime
Success AddAttributeTest 200100,00%0,470
Success AddNodeTest 300100,00%0,451
Success AttributeDetachTest 100100,00%0,400
Success BackedListTest 300100,00%0,440
Success CloneTest 1000100,00%0,501
Success ContentTest 800100,00%0,341
Success CopyTest 100100,00%0,321
Success DetachTest 100100,00%0,300
Success DocTypeTest 100100,00%0,431
Success ElementByIDTest 100100,00%0,460
Success EmbeddedHandlerTest 300100,00%0,431
Success GetQNamesTest 200100,00%0,361
Success GetXMLEncodingTest 300100,00%0,431
Success HTMLWriterTest 500100,00%0,361
Success IndexedElementTest 100100,00%0,531
Success IsTextOnlyTest 100100,00%0,321
Success IteratorTest 500100,00%0,281
Success LineFeedTest 400100,00%0,351
Success MakeElementTest 200100,00%0,381
Success MergeTextTest 100100,00%0,341
Success NamespacesTest 800100,00%0,792
Success NamespaceTest 400100,00%0,451
Success NodeTypeNameTest 500100,00%0,391
Success NormalizeTest 100100,00%0,441
Success NullAttributesTest 300100,00%0,260
Success ParentTest 200100,00%0,300
Success ParseTextTest 100100,00%0,440
Success ProcessingInstructionTest 200100,00%0,300
Success RoundTripTest 600100,00%2,904
Success SAXContentHandlerTest 200100,00%0,441
Success SerializeTest 400100,00%2,464
Success SetContentTest 200100,00%0,300
Success SetTextTest 200100,00%0,390
Success ThreadingTest 10000100,00%8,302
Success UserDataTest 400100,00%0,371
Success ValidationTest 100100,00%0,341
Success XMLResultTest 100100,00%0,351
Success XMLSpaceAttributeTest 500100,00%0,541
Success XMLWriterTest 2200100,00%0,561
Success XPathBugTest 400100,00%0,510
Success XPathExamplesTest 100100,00%1,302
Success XPathTest 500100,00%0,511
Success XSLTTest 100100,00%0,701

org.dom4j.bean

ClassTestsErrorsFailuresSuccess RateTime
Success BeansTest 100100,00%3,175

org.dom4j.datatype

ClassTestsErrorsFailuresSuccess RateTime
Success AutoSchemaTest 600100,00%0,721
Success Datatype2Test 400100,00%0,591
Success DataTypesTest 2700100,00%0,931
Success ManualSchemaPrefixTest 600100,00%0,711
Success ManualSchemaTest 600100,00%0,811
Success SchemaParseTest 100100,00%0,621
Success SetDataTest 300100,00%0,490

org.dom4j.dom

ClassTestsErrorsFailuresSuccess RateTime
Success DOMTest 400100,00%0,491

org.dom4j.dtd

ClassTestsErrorsFailuresSuccess RateTime
Success AttributeDeclTest 300100,00%0,310
Success ElementDeclTest 100100,00%0,300
Success ExternalEntityDeclTest 300100,00%0,300
Success InternalEntityDeclTest 300100,00%0,290

org.dom4j.io

ClassTestsErrorsFailuresSuccess RateTime
Success DispatchHandlerTest 100100,00%0,360
Success DocumentSourceTest 100100,00%0,440
Success DOMReaderTest 100100,00%0,350
Success DOMWriterTest 300100,00%0,400
Success DTDTest 300100,00%0,441
Success SAXReaderTest 700100,00%0,531
Success StaxTest 100100,00%0,370
Success WriteUnmergedTextTest 600100,00%0,420
Success XPP3ReaderTest 200100,00%0,371

org.dom4j.rule

ClassTestsErrorsFailuresSuccess RateTime
Success PriorityTest 400100,00%0,410
Success RuleTest 300100,00%0,400
Success StylesheetTest 300100,00%0,531

org.dom4j.swing

ClassTestsErrorsFailuresSuccess RateTime
Success TableModelTest 200100,00%0,551

org.dom4j.tree

ClassTestsErrorsFailuresSuccess RateTime
Success CDataTest 300100,00%0,400
Success DefaultDocumentTest 600100,00%0,370
Success DefaultElementTest 600100,00%0,461
Success NamespaceCacheTest 400100,00%0,601

org.dom4j.util

ClassTestsErrorsFailuresSuccess RateTime
Success SimpleSingletonTest 200100,00%0,240

org.dom4j.xpath

ClassTestsErrorsFailuresSuccess RateTime
Success AttributeTest 100100,00%0,551
Success BadPathTest 100100,00%0,400
Success BooleanTest 100100,00%0,431
Success FilterTest 100100,00%0,591
Success GetPathTest 400100,00%0,481
Success MatrixConcatTest 100100,00%0,450
Success NamespaceTest 100100,00%0,451
Success NumberTest 100100,00%0,431
Success ObjectTest 100100,00%0,401
Success PrefixTest 100100,00%0,451
Success SelectSingleNodeTest 200100,00%0,530
Success SortByTest 100100,00%0,851
Success SubstringTest 100100,00%0,450
Success TextTest 100100,00%0,390
Success UriMapTest 100100,00%0,441
Success ValueOfTest 100100,00%0,461
Success VariableTest 100100,00%0,370

Test Cases

[ summary] [ package list] [ test cases]

AddAttributeTest

Success testAddAttributeNormalValue0,18
Success testAddAttributeNullValue0,00

AddNodeTest

Success testDom4jAddNodeClone0,18
Success testDom4jAddNodeCreateCopy0,00
Success testDom4jAddNodeBug0,00

AttributeDetachTest

Success testDetachAttribute0,16

BackedListTest

Success testXPaths0,18
Success testAddRemove0,00
Success testAddWithIndex0,01

BeansTest

Success testReadXML2,96

CloneTest

Success testBug11483330,07
Success testElementWithNamespaceClone0,00
Success testDocumentClone0,01
Success testAddCloneToOtherElement0,00
Success testRootElementClone0,00
Success testAuthorElementClone0,11
Success testRootCompare10,00
Success testRootCompare20,00
Success testAuthorCompare10,00
Success testAuthorCompare20,00

ContentTest

Success testRoot0,05
Success testContent0,00
Success testGetNode0,00
Success testGetXPathNode0,00
Success testOrderOfPI0,05
Success testAddingInTheMiddle0,00
Success testAddAtIndex0,00
Success testAddAtIndex20,00

CopyTest

Success testRoot0,05

AutoSchemaTest

Success testIntAttribute0,41
Success testIntElement0,03
Success testString0,01
Success testDate0,02
Success testDateTime0,01
Success testInteger0,01

Datatype2Test

Success testSchema0,26
Success testSchemaWithNamedComplexType0,01
Success testSchemaWithReference0,02
Success testSchemaWithNamedSimpleType0,02

DataTypesTest

Success testgMonthDay0,41
Success testgDay0,01
Success testgMonth0,02
Success testDate0,00
Success testTime0,01
Success testDateTime0,02
Success testgYearMonth0,00
Success testgYear0,01
Success testBoolean0,01
Success testBase64Binary0,01
Success testHexBinary0,01
Success testFloat0,01
Success testDouble0,01
Success testDecimal0,02
Success testInteger0,01
Success testNonPositiveInteger0,01
Success testNegativeInteger0,01
Success testLong0,02
Success testInt0,01
Success testShort0,01
Success testByte0,00
Success testNonNegativeInteger0,01
Success testUnsignedLong0,01
Success testUnsignedInt0,01
Success testUnsignedShort0,02
Success testUnsignedByte0,00
Success testPositiveInteger0,01

ManualSchemaPrefixTest

Success testIntAttribute0,36
Success testIntElement0,03
Success testString0,02
Success testDate0,02
Success testDateTime0,02
Success testInteger0,03

ManualSchemaTest

Success testIntAttribute0,46
Success testIntElement0,03
Success testString0,02
Success testDate0,02
Success testDateTime0,02
Success testInteger0,03

SchemaParseTest

Success testParseSchema0,36

SetDataTest

Success testAttribute0,19
Success testAttributeWithNamespace0,03
Success testElement0,02

DetachTest

Success testRoot0,06

DocTypeTest

Success testDocType0,16

DOMTest

Success testCount0,19
Success testNamespace0,03
Success testClassCastBug0,01
Success testReplaceChild0,00

AttributeDeclTest

Success testIdImpliedNone0,06
Success testCDataFixedValue0,00
Success testCDataNoneValue0,00

ElementDeclTest

Success testSimpleElementDecl0,07

ExternalEntityDeclTest

Success testToString0,06
Success testSystemId0,00
Success testPublicIdSystemId0,00

InternalEntityDeclTest

Success testToString0,06
Success testParameterEntity0,00
Success testGeneralEntity0,00

ElementByIDTest

Success testElementByID0,22

EmbeddedHandlerTest

Success testMainReader0,15
Success testOnEndReader0,02
Success testBothReaders0,02

GetQNamesTest

Success testQNames0,13
Success testRename0,00

GetXMLEncodingTest

Success testXMLEncodingFromString0,11
Success testXMLEncodingFromURL0,05
Success testXMLEncodingFromStringWithHelper0,00

HTMLWriterTest

Success testWriter0,11
Success testBug9238820,00
Success testBug923882asWriter0,00
Success testBug923882asWriterWithEmptyCharArray0,00
Success testBug6194150,02

IndexedElementTest

Success testXPaths0,19

DispatchHandlerTest

Success testBug6114450,13

DocumentSourceTest

Success testBug5555490,20

DOMReaderTest

Success testBug9727370,11

DOMWriterTest

Success testNamespaceBug0,16
Success testBug9057450,01
Success testBug9267520,00

DTDTest

Success testInternalDTDSubset0,19
Success testExternalDTDSubset0,01
Success testMixedDTDSubset0,01

SAXReaderTest

Success testReadFile0,11
Success testEncoding0,00
Success testRussian0,04
Success testRussian20,01
Success testBug8337650,03
Success testBug5270620,11
Success testEscapedComment0,00

StaxTest

Success testEncoding0,13

WriteUnmergedTextTest

Success testWithoutFormatNonMerged0,13
Success testWithCompactFormatNonMerged0,00
Success testWithPrettyPrintFormatNonMerged0,01
Success testWithoutFormatMerged0,00
Success testWithCompactFormatMerged0,00
Success testWithPrettyPrintFormatMerged0,00

XPP3ReaderTest

Success testRussian0,10
Success testRussian20,01

IsTextOnlyTest

Success testDocument0,06

IteratorTest

Success testElementCount0,06
Success testPlainIteration0,00
Success testSkipAlternates0,00
Success testNoHasNext0,00
Success testExtraHasNexts0,00

LineFeedTest

Success testElement0,10
Success testAttribute0,00
Success testCDATA0,01
Success testXmlWriter0,01

MakeElementTest

Success testMakeElement0,15
Success testMakeQualifiedElement0,00

MergeTextTest

Success testNoAdjacentText0,11

NamespacesTest

Success testNamespaces0,17
Success testNamespaceForPrefix0,01
Success testNamespaceForDefaultPrefix0,12
Success testAttributeDefaultPrefix0,03
Success testNamespaceForURI0,02
Success testRedeclareNamespaces0,06
Success testDefaultNamespaceIssue0,15
Success testDefaultNamespace0,01

NamespaceTest

Success testGetElement0,09
Success testGetElements0,01
Success testElementIterator0,01
Success testNamespaceUriMap0,11

NodeTypeNameTest

Success testDocument0,05
Success testCDATA0,04
Success testNamespaces0,02
Success testPI0,00
Success testInline0,04

NormalizeTest

Success testNormalize0,21

NullAttributesTest

Success testStringNames0,02
Success testQNames0,00
Success testAttributes0,00

ParentTest

Success testDocument0,06
Success testFragment0,00

ParseTextTest

Success testDocument0,21

ProcessingInstructionTest

Success testParseValues0,06
Success testBug7874280,00

RoundTripTest

Success testTextRoundTrip0,23
Success testSAXRoundTrip0,06
Success testDOMRoundTrip0,08
Success testJAXPRoundTrip0,10
Success testFullRoundTrip0,14
Success testRoundTrip2,06

PriorityTest

Success testNameNode0,16
Success testFilter0,01
Success testURI0,00
Success testAnyNode0,00

RuleTest

Success testOrder0,15
Success testDocument0,00
Success testTextMatchesCDATA0,01

StylesheetTest

Success testRules0,23
Success testLittleDoc0,05
Success testFireRuleForNode0,01

SAXContentHandlerTest

Success testSAXContentHandler0,20
Success testBug9267130,01

SerializeTest

Success testSerializePeriodicTable0,98
Success testSerializeMuchAdo0,97
Success testSerializeTestSchema0,03
Success testSerializeXPath0,17

SetContentTest

Success testDocument0,05
Success testRootElement0,00

SetTextTest

Success testSetText10,16
Success testSetText20,00

TableModelTest

Success testServletTable0,30
Success testServletTableViaXMLDescription0,01

ThreadingTest

Success testCombo
Success testCombo
Success testCombo
Success testCombo
Success testCombo0,24
Success testCombo0,01
Success testCombo0,03
Success testCombo0,06
Success testCombo0,07
Success testCombo0,02
Success testCombo0,00
Success testCombo0,01
Success testCombo0,02
Success testCombo0,09
Success testCombo0,01
Success testCombo0,00
Success testCombo0,01
Success testCombo0,02
Success testCombo0,06
Success testCombo0,00
Success testCombo0,01
Success testCombo
Success testCombo0,04
Success testCombo0,01
Success testCombo0,07
Success testCombo0,01
Success testCombo0,02
Success testCombo0,00
Success testCombo0,03
Success testCombo0,02
Success testCombo0,00
Success testCombo0,02
Success testCombo0,02
Success testCombo0,03
Success testCombo0,02
Success testCombo0,00
Success testCombo0,07
Success testCombo0,02
Success testCombo0,01
Success testCombo0,01
Success testCombo0,04
Success testCombo0,04
Success testCombo0,02
Success testCombo0,01
Success testCombo0,01
Success testCombo0,01
Success testCombo0,03
Success testCombo0,02
Success testCombo0,02
Success testCombo0,04
Success testQNameCache
Success testQNameCache
Success testQNameCache
Success testQNameCache
Success testQNameCache0,66
Success testQNameCache0,06
Success testQNameCache0,06
Success testQNameCache0,01
Success testQNameCache0,06
Success testQNameCache0,80
Success testQNameCache0,05
Success testQNameCache0,01
Success testQNameCache0,21
Success testQNameCache0,09
Success testQNameCache0,37
Success testQNameCache0,06
Success testQNameCache0,01
Success testQNameCache0,06
Success testQNameCache0,10
Success testQNameCache0,46
Success testQNameCache0,04
Success testQNameCache0,00
Success testQNameCache0,15
Success testQNameCache0,20
Success testQNameCache0,29
Success testQNameCache0,06
Success testQNameCache0,02
Success testQNameCache0,03
Success testQNameCache0,16
Success testQNameCache0,23
Success testQNameCache0,09
Success testQNameCache0,02
Success testQNameCache0,04
Success testQNameCache0,14
Success testQNameCache0,24
Success testQNameCache0,06
Success testQNameCache0,02
Success testQNameCache0,15
Success testQNameCache0,08
Success testQNameCache0,24
Success testQNameCache0,01
Success testQNameCache0,01
Success testQNameCache0,23
Success testQNameCache0,07
Success testQNameCache0,26
Success testQNameCache0,04
Success testQNameCache0,01
Success testQNameCache0,17
Success testQNameCache0,03
Success testQNameCache0,40

CDataTest

Success testNullTest0,06
Success testNormal0,00
Success testLongCData0,11

DefaultDocumentTest

Success testDoubleRootElement0,05
Success testBug7996560,05
Success testAsXMLWithEncoding0,01
Success testBug11569090,00
Success testAsXMLWithEncodingAndContent0,00
Success testEncoding0,00

DefaultElementTest

Success testParentAfterSetContent0,19
Success testGetStringValue0,01
Success testBug8948780,01
Success testGetNamespacesForURI0,00
Success testDeclaredNamespaces0,00
Success testAdditionalNamespaces0,01

NamespaceCacheTest

Success testGetSameNamespaceSingleThread0,09
Success testGetSameNamespaceMultiThread0,06
Success testGetNewNamespaceSingleThread0,16
Success testGetNewNamespaceMultiThread0,07

UserDataTest

Success testSetData0,12
Success testCloneAttribute0,00
Success testNewAdditions0,01
Success testNewDocument0,00

SimpleSingletonTest

Success testFirstInstance0,00
Success testSecondInstance0,00

ValidationTest

Success testValidation0,09

XMLResultTest

Success testWriter0,10

XMLSpaceAttributeTest

Success testWithTextTrimOn0,21
Success testWithTextTrimOff0,01
Success testWithTextTrimOnFollow0,01
Success testWithTextTrimOnNested0,01
Success testWithEscapeTextTrimOn0,01

XMLWriterTest

Success testBug11807910,10
Success testBug11197330,01
Success testBug1119733WithSAXEvents0,00
Success testWriter0,00
Success testEncodingFormats0,00
Success testWritingEmptyElement0,01
Success testWriterBug0,01
Success testNamespaceBug0,00
Success testContentHandler0,11
Success testWhitespaceBug0,01
Success testWhitespaceBug20,00
Success testPadding0,00
Success testPadding20,00
Success testPrettyPrinting0,01
Success testAttributeQuotes0,00
Success testBug8684080,01
Success testBug9238820,00
Success testEscapeXML0,01
Success testWriteEntities0,04
Success testEscapeChars0,00
Success testEscapeText0,00
Success testNullCData0,00

AttributeTest

Success testXPaths0,19

BadPathTest

Success testBadPaths0,10

BooleanTest

Success testXPaths0,19

FilterTest

Success testXPaths0,35

GetPathTest

Success testGetPath0,07
Success testDefaultNamespace0,05
Success testBug7704100,13
Success testBug5699270,00

MatrixConcatTest

Success testMatrixConcat0,22

NamespaceTest

Success testXPaths0,22

NumberTest

Success testXPaths0,20

ObjectTest

Success testXPaths0,17

PrefixTest

Success testXPaths0,21

SelectSingleNodeTest

Success testSelectSingleNode0,25
Success testSteensBug0,04

SortByTest

Success testXPaths0,62

SubstringTest

Success testSubstring0,21

TextTest

Success testXPaths0,15

UriMapTest

Success testURIMap0,21

ValueOfTest

Success testXPaths0,21

VariableTest

Success testXPaths0,14

XPathBugTest

Success testXPaths0,25
Success testRobLebowitz0,01
Success testStefan0,01
Success testMikeSkells0,00

XPathExamplesTest

Success testXPaths1,07

XPathTest

Success testBug11164710,20
Success testXPaths0,06
Success testCreateXPathBug0,00
Success testBug8577040,00
Success testBooleanValueOf0,01

XSLTTest

Success testTransform0,47

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/guide.html0000644000175000017500000002774110242117562015012 0ustar ebourgebourgdom4j - Quick Start Guide
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Parsing XML

One of the first things you'll probably want to do is to parse an XML document of some kind. This is easy to do in dom4j. The following code demonstrates how to this.

import java.net.URL;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class Foo {

    public Document parse(URL url) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(url);
        return document;
    }
}

Using Iterators

A document can be navigated using a variety of methods that return standard Java Iterators. For example

    public void bar(Document document) throws DocumentException {

        Element root = document.getRootElement();

        // iterate through child elements of root
        for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
            Element element = (Element) i.next();
            // do something
        }

        // iterate through child elements of root with element name "foo"
        for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) {
            Element foo = (Element) i.next();
            // do something
        }

        // iterate through attributes of root 
        for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {
            Attribute attribute = (Attribute) i.next();
            // do something
        }
     }

Powerful Navigation with XPath

In dom4j XPath expressions can be evaluated on the Document or on any Node in the tree (such as Attribute, Element or ProcessingInstruction). This allows complex navigation throughout the document with a single line of code. For example.

    public void bar(Document document) {
        List list = document.selectNodes( "//foo/bar" );

        Node node = document.selectSingleNode( "//foo/bar/author" );

        String name = node.valueOf( "@name" );
    }

For example if you wish to find all the hypertext links in an XHTML document the following code would do the trick.

    public void findLinks(Document document) throws DocumentException {

        List list = document.selectNodes( "//a/@href" );

        for (Iterator iter = list.iterator(); iter.hasNext(); ) {
            Attribute attribute = (Attribute) iter.next();
            String url = attribute.getValue();
        }
    }

If you need any help learning the XPath language we highly recommend the Zvon tutorial which allows you to learn by example.

Fast Looping

If you ever have to walk a large XML document tree then for performance we recommend you use the fast looping method which avoids the cost of creating an Iterator object for each loop. For example

    public void treeWalk(Document document) {
        treeWalk( document.getRootElement() );
    }

    public void treeWalk(Element element) {
        for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
            Node node = element.node(i);
            if ( node instanceof Element ) {
                treeWalk( (Element) node );
            }
            else {
                // do something....
            }
        }
    }

Creating a new XML document

Often in dom4j you will need to create a new document from scratch. Here's an example of doing that.

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Foo {

    public Document createDocument() {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement( "root" );

        Element author1 = root.addElement( "author" )
            .addAttribute( "name", "James" )
            .addAttribute( "location", "UK" )
            .addText( "James Strachan" );
        
        Element author2 = root.addElement( "author" )
            .addAttribute( "name", "Bob" )
            .addAttribute( "location", "US" )
            .addText( "Bob McWhirter" );

        return document;
    }
}

Writing a document to a file

A quick and easy way to write a Document (or any Node) to a Writer is via the write() method.

  FileWriter out = new FileWriter( "foo.xml" );
  document.write( out );

If you want to be able to change the format of the output, such as pretty printing or a compact format, or you want to be able to work with Writer objects or OutputStream objects as the destination, then you can use the XMLWriter class.

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class Foo {

    public void write(Document document) throws IOException {

        // lets write to a file
        XMLWriter writer = new XMLWriter(
            new FileWriter( "output.xml" )
        );
        writer.write( document );
        writer.close();


        // Pretty print the document to System.out
        OutputFormat format = OutputFormat.createPrettyPrint();
        writer = new XMLWriter( System.out, format );
        writer.write( document );

        // Compact format to System.out
        format = OutputFormat.createCompactFormat();
        writer = new XMLWriter( System.out, format );
        writer.write( document );
    }
}

Converting to and from Strings

If you have a reference to a Document or any other Node such as an Attribute or Element, you can turn it into the default XML text via the asXML() method.

        Document document = ...;
        String text = document.asXML();

If you have some XML as a String you can parse it back into a Document again using the helper method DocumentHelper.parseText()

        String text = "<person> <name>James</name> </person>";
        Document document = DocumentHelper.parseText(text);

Styling a Document with XSLT

Applying XSLT on a Document is quite straightforward using the JAXP API from Sun. This allows you to work against any XSLT engine such as Xalan or SAXON. Here is an example of using JAXP to create a transformer and then applying it to a Document.

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;

import org.dom4j.Document;
import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;

public class Foo {

    public Document styleDocument(
        Document document, 
        String stylesheet
    ) throws Exception {

        // load the transformer using JAXP
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer( 
            new StreamSource( stylesheet ) 
        );

        // now lets style the given document
        DocumentSource source = new DocumentSource( document );
        DocumentResult result = new DocumentResult();
        transformer.transform( source, result );

        // return the transformed document
        Document transformedDoc = result.getDocument();
        return transformedDoc;
    }
}

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/checkstyle-report.html0000644000175000017500000002435110242117710017351 0ustar ebourgebourgdom4j - Checkstyle Results
MetaStuff Ltd.dom4j

Last published: 16 May 2005 | Doc for 1.6.1
XPath Spec | Jaxen | dom4j@SourceForge

dom4j
  • Home
  • FAQ
  • Quick start
  • Cookbook
  • Comparison
  • Goals
  • Changes
  • Download
  • License
  • Javadoc (1.6.1)
  • Javadoc (1.5.2)
  • Javadoc (1.4)
Project Documentation
  • About dom4j
  • Project Info
  • Project Reports
    • Change Log
    • Changes
    • Checkstyle
    • Clover
    • Developer Activity
    • FAQs
    • File Activity
    • JavaDocs
    • JavaDoc Report
    • JavaDoc Warnings Report
    • Metrics
    • Unit Tests
    • Source Xref
    • Test Xref
    • Project License
  • Development Process
Legend
  • External Link
  • Opens in a new window
Code Coverage by CloverHosted by SourceForgeBuilt by Maven

Checkstyle Results

The following document contains the results of Checkstyle .

Summary

FilesInfosWarningsErrors
165070

Files

FilesIWE
org/dom4j/InvalidXPathException.java 040
org/dom4j/util/PerThreadSingleton.java 010
org/dom4j/util/SimpleSingleton.java 010
org/dom4j/xpath/DefaultXPath.java 010

org/dom4j/InvalidXPathException.java

ErrorLine
Warning Line contains a tab character. 19
Warning Line contains a tab character. 20
Warning Line contains a tab character. 22
Warning Line contains a tab character. 32

org/dom4j/util/PerThreadSingleton.java

ErrorLine
Warning Line is longer than 80 characters. 45

org/dom4j/util/SimpleSingleton.java

ErrorLine
Warning Line is longer than 80 characters. 38

org/dom4j/xpath/DefaultXPath.java

ErrorLine
Warning Line contains a tab character. 362

2001-2005, MetaStuff Ltd.

dom4j-1.6.1/docs/style/0000755000175000017500000000000012133227266014160 5ustar ebourgebourgdom4j-1.6.1/docs/style/maven-theme.css0000644000175000017500000000373610242117766017113 0ustar ebourgebourgbody, td, select, input, li{ font-family: Verdana, Helvetica, Arial, sans-serif; font-size: 13px; } a { text-decoration: none; } a:link { color:#36a; } a:visited { color:#47a; } a:active, a:hover { color:#69c; } #legend li.externalLink { background: url(../images/external.png) left top no-repeat; padding-left: 18px; } a.externalLink, a.externalLink:link, a.externalLink:visited, a.externalLink:active, a.externalLink:hover { background: url(../images/external.png) right center no-repeat; padding-right: 18px; } #legend li.newWindow { background: url(../images/newwindow.png) left top no-repeat; padding-left: 18px; } a.newWindow, a.newWindow:link, a.newWindow:visited, a.newWindow:active, a.newWindow:hover { background: url(../images/newwindow.png) right center no-repeat; padding-right: 18px; } h2 { padding: 4px 4px 4px 6px; border: 1px solid #999; color: #900; background-color: #ddd; font-weight:900; font-size: x-large; } h3 { padding: 4px 4px 4px 6px; border: 1px solid #aaa; color: #900; background-color: #eee; font-weight: normal; font-size: large; } p { line-height: 1.3em; font-size: small; } #breadcrumbs { border-top: 1px solid #aaa; border-bottom: 1px solid #aaa; background-color: #ccc; } #leftColumn { margin: 10px 0 0 5px; border: 1px solid #999; background-color: #eee; } #navcolumn h5 { font-size: smaller; border-bottom: 1px solid #aaaaaa; padding-top: 2px; } table.bodyTable th { color: white; background-color: #bbb; text-align: left; font-weight: bold; } table.bodyTable th, table.bodyTable td { font-size: 1em; } table.bodyTable tr.a { background-color: #ddd; } table.bodyTable tr.b { background-color: #eee; } .source { border: 1px solid #999; } dt { padding: 4px 4px 4px 6px; border: 1px solid #aaa; color: #900; background-color: #eee; font-weight: normal; font-size: large; } dom4j-1.6.1/docs/style/maven-classic.css0000644000175000017500000003471410242117545017425 0ustar ebourgebourgbody { background: #fff; color: #000; } .contentBox h2 { color: #fff; background-color: #036; } .contentBox h3 { color: #fff; background-color: #888; } .a td { background: #ddd; color: #000; } .b td { background: #efefef; color: #000; } .contentBox th { background-color: #bbb; color: #fff; } div#banner { border-top: 1px solid #369; border-bottom: 1px solid #003; } #banner, #banner td { background: #fff; color: #000; } #leftColumn { background: #eee; color: #000; border-right: 1px solid #aaa; border-bottom: 1px solid #aaa; border-top: 1px solid #fff; } #navcolumn { /* bad for IE background: #eee; */ color: #000; border-right: none; border-bottom: none; border-top: none; } #breadcrumbs { background-color: #ddd; color: #000; border-top: 1px solid #fff; border-bottom: 1px solid #aaa; } .source { background-color: #fff; color: #000; border-right: 1px solid #888; border-left: 1px solid #888; border-top: 1px solid #888; border-bottom: 1px solid #888; margin-right: 7px; margin-left: 7px; margin-top: 1em; } .source pre { margin-right: 7px; margin-left: 7px; } a[name]:hover, #leftColumn a[name]:hover { color: inherit !important; } a:link, #breadcrumbs a:visited, #navcolumn a:visited, .contentBox a:visited, .tasknav a:visited { color: blue; } a:active, a:hover, #leftColumn a:active, #leftColumn a:hover { color: #f30 !important; } a:link.selfref, a:visited.selfref { color: #555 !important; } #legend li.externalLink { background: url(../images/external-classic.png) left top no-repeat; padding-left: 18px; } a.externalLink, a.externalLink:link, a.externalLink:visited, a.externalLink:active, a.externalLink:hover { background: url(../images/external-classic.png) right center no-repeat; padding-right: 18px; } #legend li.newWindow { background: url(../images/newwindow-classic.png) left top no-repeat; padding-left: 18px; } a.newWindow, a.newWindow:link, a.newWindow:visited, a.newWindow:active, a.newWindow:hover { background: url(../images/newwindow-classic.png) right center no-repeat; padding-right: 18px; } h2, h3 { margin-top: 1em; margin-bottom: 0; } img.handle { border: 0; padding-right: 2px; } #navcolumn div div { background-image: none; background-repeat: no-repeat; } #navcolumn div div { padding-left: 10px; } /* $Id: maven-classic.css,v 1.4 2004/07/13 12:18:59 brett Exp $ This file defines basic default formatting for HTML conforming to Tigris application style. To extend or override these rules for your instance, edit inst.css instead of this file. */ /* colors, backgrounds, borders, link indication */ .contentBox h2, .contentBox h3, .tabs td, .tabs th, .functnbar { background-image: url(../images/nw_maj_rond.gif); background-repeat: no-repeat; } .functnbar, .functnbar2 { background-color: #aaa; } .functnbar2, .functnbar3 { background-color: #aaa; background-image: url(../images/sw_maj_rond.gif); background-repeat: no-repeat; background-position: bottom left; } .functnbar3 { background-color: #ddd; background-image: url(../images/sw_med_rond.gif); } .functnbar, .functnbar2, .functnbar3 { color: #000; } .functnbar a, .functnbar2 a, .functnbar3 a { color: #000; text-decoration: underline; } #navcolumn .body div, body.docs #toc li li { background-image: url(../images/strich.gif); background-repeat: no-repeat; background-position: .5em .5em; } #searchbox .body div, #navcolumn .body .heading { background-image: none; } a:link.selfref, a:visited.selfref { text-decoration: none; } #leftColumn a, #breadcrumbs a { text-decoration: none; } /* Unsure of this. TODO */ .contentBox h2 a:link, .contentBox h2 a:visited, .contentBox h3 a:link, .contentBox h3 a:visited { color: #fff !important; text-decoration: underline; } table, th, td { border: none; } div.colbar { background: #eee; border-color: #999 #EEE #EEE #999; border-width: 1px; border-style: solid; } .toolgroup { background: #efefef; } .toolgroup .label { border-bottom: 1px solid #666; border-right: 1px solid #666; background: #ddd; color: #555; } .toolgroup .body { border-right: 1px solid #aaa; border-bottom: 1px solid #aaa; } #main { border-top: 1px solid #999; } #rightcol div.www, #rightcol div.help { border: 1px solid #ddd; } body.docs div.docs { background-color: #fff; border-left: 1px solid #ddd; border-top: 1px solid #ddd; } #helptext .label { background-image: url(../images/icon_help_sml.gif); background-repeat: no-repeat; background-position: 97%; } body.docs { background: #eee url(../images/help_logo.gif) top right no-repeat !important; } .docs h2, .docs h3 { border-top: solid 1px #000; } #apphead h2 em { color: #777; } .tabs th { border-right: 1px solid #333; background-color: #ddd; color: #fff; border-left: 1px solid #fff; } .tabs td { background-color: #999; border-bottom: 1px solid #fff; border-right: 1px solid #fff; border-left: 1px solid #fff; } .tabs { border-bottom: 6px #ddd solid; } .tabs th, .tabs th a:link, .tabs th a:visited { color: #555; } .tabs td, .tabs td a:link, .tabs td a:visited { color: #fff; } .tabs a { text-decoration: none; } .axial th { background-color: #ddd; color: black; } .alert { background-color: #ff9; } .expandedwaste { background: url(../images/icon_arrowwaste2_sml.gif) no-repeat; } .collapsedwaste { background: url(../images/icon_arrowwaste1_sml.gif) no-repeat; } .filebrowse .expanded, .filebrowse-alt .expanded { background-image: url(../images/icon_arrowfolderopen2_sml.gif); background-repeat: no-repeat; } .filebrowse .collapsed, .filebrowse-alt .collapsed { background-image: url(../images/icon_arrowfolderclosed1_sml.gif); background-repeat: no-repeat; } .filebrowse .leafnode, .filebrowse-alt .leafnode { background-image: url(../images/icon_folder_sml.gif); background-repeat: no-repeat; } .filebrowse .leaf, .filebrowse-alt .leaf { background-image: url(../images/icon_doc_sml.gif); background-repeat: no-repeat; } .sortup { background: url(../images/icon_sortup.gif) no-repeat; } .sortdown { background: url(../images/icon_sortdown.gif) no-repeat; } .collapsedwaste { background: url(../images/icon_arrowwaste1_sml.gif) no-repeat; } body .grid td { border-top: 1px solid #ccc; border-left: 1px solid #ccc; background-color: transparent; } .confirm { color: #090; } .info { color: #069; } .errormessage, .warningmessage, .donemessage, .infomessage { border-top: 5px solid #900; border-left: 1px solid #900; background-image: url(../images/icon_error_lrg.gif); background-repeat: no-repeat; background-position: 5px 1.33em; } .warningmessage { background-image: url(../images/icon_warning_lrg.gif); border-color: #c60; } .donemessage { background-image: url(../images/icon_success_lrg.gif); border-color: #090; } .infomessage { background-image: url(../images/icon_info_lrg.gif); border-color: #069; } .docinfo { background: url(../images/icon_doc_lrg.gif) no-repeat; } .dirinfo { background: url(../images/icon_folder_lrg.gif) no-repeat; } .memberinfo { background: url(../images/icon_members_lrg.gif) no-repeat; } .usergroupinfo { background: url(../images/icon_usergroups_lrg.gif) no-repeat; } .errormark, .warningmark, .donemark, .infomark { background: url(../images/icon_error_sml.gif) no-repeat; } .warningmark { background-image: url(../images/icon_warning_sml.gif); } .donemark { background-image: url(../images/icon_success_sml.gif); } .infomark { background-image: url(../images/icon_info_sml.gif); } .cvsdiff, .cvsblame { background-color: #ccc; } .cvsdiffadd { background-color: #afa; } .cvsdiffremove { background-color: #faa; } .cvsdiffchanges1 { background-color: #ff7; } .cvsdiffchanges2 { background-color: #ff7; } li.selection ul a { background: #fff; } .band1 { color: #fff; background-color: #663; } .band2 { color: #fff; background-color: #66C; } .band3 { background-color: #C99; } .band4 { background-color: #CFF; } .band5 { color: #fff; background-color: #336; } .band6 { color: #fff; background-color: #966; } .band7 { background-color: #9CC; } .band8 { background-color: #FFC; } .band9 { color: #fff; background-color: #633; } .band10 { color: #fff; background-color: #699; } .band11 { background-color: #CC9; } .band12 { background-color: #CCF; } .band13 { color: #fff; background-color: #366; } .band14 { color: #fff; background-color: #996; } .band15 { background-color: #99C; } .band16 { background-color: #FCC; } .contentBox .helplink, #helptext .helplink { cursor: help; } .legend th, .bars th { background-color: #fff; } /* font and text properties, exclusive of link indication, alignment, text-indent */ body, th, td, input, select { font-family: Verdana, Helvetica, Arial, sans-serif; } code, pre { font-family: 'Andale Mono', Courier, monospace; } body, .contentBox h2, .contentBox h3, #rightcol h2, pre, code, #apphead h2 small, h3, th, td { font-size: x-small; voice-family: "\"}\""; voice-family: inherit; font-size: small; } small, div#footer, div#login, div.tabs th, div.tabs td, input, select, .paginate, .functnbar, .functnbar2, .functnbar3, #breadcrumbs, .courtesylinks, #rightcol div.help, .colbar, .tasknav, body.docs div#toc, #leftColumn, .legend, .bars { font-size: xx-small; voice-family: "\"}\""; voice-family: inherit; font-size: x-small; } .tabs td, .tabs th, dt, .tasknav .selfref, #login .username, .selection { font-weight: bold; } li.selection ul { font-weight: normal; } #apphead h2 em { font-style: normal; } #banner h1 { font-size: 1.25em; } /* box properties (exclusive of borders), positioning, alignments, list types, text-indent */ #bodyColumn h2 { margin-top: .3em; margin-bottom: .5em; } p, ul, ol, dl, .bars table { margin-top: .67em; margin-bottom: .67em; } form { margin: 0; } #bodyColumn { padding-left: 12px; padding-right: 12px; width: 100%; voice-family: "\"}\""; voice-family: inherit; width: auto; } html>body #bodyColumn { width: auto; } .docs { line-height: 1.4; } ol ol { list-style-type: lower-alpha; } ol ol ol { list-style-type: lower-roman; } .contentBox h2, .contentBox h3 { padding: 5px; margin-right: 2px; } .contentBox td, .contentBox th { padding: 2px 3px; } .h2 p, .h3 p, .h2 dt, .h3 dt { margin-right: 7px; margin-left: 7px; } .tasknav { margin-bottom: 1.33em; } div.colbar { padding: 3px; margin: 2px 2px 0; } .tabs { margin-top: .67em; margin-right: 2px; margin-left: 2px; padding-left: 8px; } .tabs td, .tabs th { padding: 3px 9px; } #rightcol div.www, #rightcol div.help { padding: 0 .5em; } body.docs #toc { position: absolute; top: 15px; left: 0px; width: 120px; padding: 0 20px 0 0; } body.docs #toc ul, #toc ol { margin-left: 0; padding-left: 0; } body.docs #toc li { margin-top: 7px; padding-left: 10px; list-style-type: none; } body.docs div.docs { margin: 61px 0 0 150px; padding: 1em 2em 1em 1em !important; } .docs p+p { text-indent: 5%; margin-top: -.67em; } .docs h2, .docs h3 { margin-bottom: .1em; padding-top: .3em; } .functnbar, .functnbar2, .functnbar3 { padding: 5px; margin: .67em 2px; } .functnbar3 { margin-top: 0; } body { padding: 1em; } body.composite, body.docs { margin: 0; padding: 0; } th, td { text-align: left; vertical-align: top; } .right { text-align: right !important; } .center { text-align: center !important; } .axial th, .axial th .strut { text-align: right; } .contentBox .axial td th { text-align: left; } body .stb { margin-top: 1em; text-indent: 0; } body .mtb { margin-top: 2em; text-indent: 0; } .courtesylinks { margin-top: 1em; padding-top: 1em; } dd { margin-bottom: .67em; } .toolgroup { margin-bottom: 6px; } .toolgroup .body { padding: 4px 4px 4px 0; } .toolgroup .label { padding: 4px; } .toolgroup .body div { padding-bottom: .3em; padding-left: 1em; } .toolgroup .body div div { margin-top: .3em; padding-bottom: 0; } .tier1 { margin-left: 0; } .tier2 { margin-left: 1.5em; } .tier3 { margin-left: 3em; } .tier4 { margin-left: 4.5em; } .tier5 { margin-left: 6em; } .tier6 { margin-left: 7.5em; } .tier7 { margin-left: 9em; } .tier8 { margin-left: 10.5em; } .tier9 { margin-left: 12em; } .tier10 { margin-left: 13.5em; } .filebrowse .expanded, .filebrowse .collapsed { padding-left: 34px; } .filebrowse .leafnode, .filebrowse .leaf { padding-left: 20px; } .messagechild { padding-left: 34px; } .filebrowse-alt .expanded, .filebrowse-alt .collapsed, .filebrowse-alt .leaf, .filebrowse-alt .leafnode, .expandedwaste, .collapsedwaste, .sortup, .sortdown { /* hide from macie5\*/ float: left; /* resume */ display: inline-block; height: 15px; width: 34px; padding-left: 0 !important; } .filebrowse-alt .leaf, .filebrowse-alt .leafnode, .sortup, .sortdown { width: 20px; } .filebrowse ul, .filebrowse-alt ul { list-style-type: none; padding-left: 0; margin-left: 0; } .filebrowse ul ul, .filebrowse-alt ul ul { margin-left: 1.5em; margin-top: 0; padding-top: .67em; } .filebrowse li, .filebrowse-alt li { margin-bottom: .67em; } td.filebrowse h2 { margin-top: 0; } .errormessage, .warningmessage, .donemessage, .infomessage, .docinfo, .dirinfo, .memberinfo, .usergroupinfo { margin: .67em 0; padding: .33em 0 .67em 42px; min-height: 32px; } .errormark, .warningmark, .donemark, .infomark { padding-left: 20px; min-height: 15px; } .alt { display: none; } #banner h1 { margin: 0; } .axial th, .axial th .strut, #leftColumn .strut { width: 12em; } #breadcrumbs { padding: 2px 8px; } /* Bad for IE .contentBox h2, .contentBox h3, .bars { clear: both; } */ .legend { float: right; } .legend th, .bars th { text-align: right; padding-left: 1em; } .bars table { table-layout: fixed; } .bars th { width: 12em; } #projectdocumentlist td.filebrowse-alt { padding-right: .75em; } dom4j-1.6.1/docs/style/maven-base.css0000644000175000017500000000477510242117710016714 0ustar ebourgebourgbody { margin: 0px; padding: 0px 0px 10px 0px; } img { border:none; } table { padding:0px; width: 100%; margin-left: -2px; margin-right: -2px; } acronym { cursor: help; border-bottom: 1px dotted #feb; } table.bodyTable th, table.bodyTable td { padding: 2px 4px 2px 4px; vertical-align: top; } div.clear{ clear:both; visibility: hidden; } div.clear hr{ display: none; } #projectLogo { font-size: xx-large; font-weight: bold; } #organizationLogo img, #projectLogo img, #projectLogo span{ margin: 8px; } #projectLogo span{ border: 1px solid; padding: 4px 10px 4px 10px; background-color: #eee; cursor: pointer; } .xleft, #organizationLogo img{ float:left; } .xright, #projectLogo img, #projectLogo span{ float:right; text-shadow: #7CFC00; } #banner { border-bottom: 1px solid #fff; } #banner img { border: none; } #footer, #breadcrumbs { padding: 3px 10px 3px 10px; } #leftColumn { width: 18%; float:left; } #bodyColumn { margin-left: 20%; } #legend { padding: 8px 0 8px 0; } #navcolumn { padding: 8px 4px 0 8px; } #navcolumn h5, #navcolumn ul { margin: 0; padding: 0; font-size: small; } #navcolumn li { list-style-type: none; background-image: none; background-repeat: no-repeat; background-position: 0 0.4em; padding-left: 16px; list-style-position: ouside; line-height: 1.2em; font-size: smaller; } #navcolumn li.expanded { background-image: url(../images/expanded.gif); } #navcolumn li.collapsed { background-image: url(../images/collapsed.gif); } #navcolumn img { margin-top: 10px; margin-bottom: 3px; } #poweredBy, #poweredByExternal { text-align: center; } #poweredBy img { display:block; margin: 20px 0 20px 17px; border: 1px solid black; width: 90px; height: 30px; } #poweredByExternal img { display: block; margin: 20px 0 20px 17px; } #search img { margin: 0px; display: block; } #search #q, #search #btnG { border: 1px solid #999; margin-bottom:10px; } #search form { margin: 0px; } #lastPublished { font-size: x-small; } .navSection { margin-bottom: 2px; padding: 8px; } .navSectionHead { font-weight: bold; font-size: x-small; } .section { padding: 4px; } #footer { font-size: x-small; } #breadcrumbs { font-size: x-small; margin: 0pt; } .source { padding: 12px; margin: 1em 7px 1em 7px; } .source pre { margin: 0px; padding: 0px; } dom4j-1.6.1/docs/style/print.css0000644000175000017500000000032310242117704016016 0ustar ebourgebourg#banner, #footer, #leftcol, #breadcrumbs, .docs #toc, .docs .courtesylinks, #leftColumn, #navColumn { display: none; } #bodyColumn, body.docs div.docs { margin: 0 !important; border: none !important }