jenkins-dom4j-1.6.1-hudson-3/0000755000175000017500000000000011603102323014574 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/jalopy.xml0000644000175000017500000004056111332657403016637 0ustar chuckchuck 14 false [A-Z][a-zA-Z0-9]+ [A-Z][a-zA-Z0-9]+ [a-z][\w]+ [a-z][\w]+ [a-zA-Z][\w]+ [a-z][\w]+ [a-z][\w]+ [a-zA-Z][\w]+ [a-z][\w]+ [a-z][\w]+ [a-zA-Z][\w]+ [a-z][\w]+ [a-z][\w]+ [a-zA-Z][\w]+ [A-Z][a-zA-Z0-9]+ \w+ [a-z][\w]+ [a-z][\w]+ [a-z][\w]+ [a-z][\w]+ [a-z][\w]+ [a-z][\w]+ [a-z][\w]+ [a-z][\w]+ [a-z][\w]+ [a-z][\w]+ [a-z][\w]+ [a-z][\w]+ [a-z]+(?:\.[a-z]+)* [a-z][\w]+ [a-z][\w]+ [a-z][\w]* false false false false false false false false false false false false false false false false false false 6 30000 30000 30000 30000 30000 30000 true 1 true false true false false bak 0 1 0 1 0
1
1
1 1 1 1
1 0 1 1 1 1 1 1
4
0
1
false false true true true true false false false false false false false true true false false true true true 0 0 0 0 false */ * @throws $exceptionType$ DOCUMENT ME! * @param $paramType$ DOCUMENT ME! * @return DOCUMENT ME! /**| * DOCUMENT ME! false false false - false false Inner Classes Constructors Instance fields Instance initializers Inner Interfaces Methods Static fields/initializers
MetaStuff 20 /*| * Redistribution and use of this software and associated documentation| * ("Software"), with or without modification, are permitted provided| * that the following conditions are met:| *| * 1. Redistributions of source code must retain copyright| * statements and notices. Redistributions must also contain a| * copy of this document.| *| * 2. Redistributions in binary form must reproduce the| * above copyright notice, this list of conditions and the| * following disclaimer in the documentation and/or other| * materials provided with the distribution.| *| * 3. The name "DOM4J" must not be used to endorse or promote| * products derived from this Software without prior written| * permission of MetaStuff, Ltd. For written permission,| * please contact dom4j-info@metastuff.com.| *| * 4. Products derived from this Software may not be called "DOM4J"| * nor may "DOM4J" appear in their names without prior written| * permission of MetaStuff, Ltd. DOM4J is a registered| * trademark of MetaStuff, Ltd.| *| * 5. Due credit should be given to the DOM4J Project -| * http://www.dom4j.org| *| * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS| * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT| * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND| * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL| * METASTUFF, LTD. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,| * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES| * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR| * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)| * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,| * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)| * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED| * OF THE POSSIBILITY OF SUCH DAMAGE.| *| * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.| */ true
MetaStuff 20 /*| * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.| *| * This software is open source.| * See the bottom of this file for the licence.| */ true
disabled 3 *:0|java:1|javax:1|org:2 disabled true true true false false true 1 1 0 1 4 55 -1 4 -1 0 8 -1 1 false false false false true false true false false false false false false static|field|initializer|constructor|method|interface|class false true public|protected|private|abstract|static|final|synchronized|transient|volatile|native|strictfp true true true true false false false false false false true false false true true true true true true false false 1 false false false false false false false false false false false false false false true false 80 true false false false false false false false
jenkins-dom4j-1.6.1-hudson-3/xml/0000755000175000017500000000000011332657403015411 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xml/cookbook.xml0000644000175000017500000010262011332657403017742 0ustar chuckchuck 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
jenkins-dom4j-1.6.1-hudson-3/xml/test/0000755000175000017500000000000011332657403016370 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xml/test/nestedNamespaces.xml0000644000175000017500000000034111332657403022372 0ustar chuckchuck works jenkins-dom4j-1.6.1-hudson-3/xml/test/junk.xml0000644000175000017500000000005511332657403020061 0ustar chuckchuckhi therehello worldjenkins-dom4j-1.6.1-hudson-3/xml/test/schema/0000755000175000017500000000000011332657403017630 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xml/test/schema/personal.dtd0000644000175000017500000000120411332657403022145 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/test/schema/personal-schema.xml0000644000175000017500000000351611332657403023440 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/xml/test/schema/personal_dtd.xml0000644000175000017500000000241711332657403023034 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/xml/test/schema/test.xsd0000644000175000017500000000344511332657403021335 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/test/schema/personal.xsd0000644000175000017500000000423611332657403022200 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/test/schema/personal.xml0000644000175000017500000000334611332657403022203 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/xml/test/schema/personal-prefix.xsd0000644000175000017500000000403311332657403023466 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/test/schema/test.xml0000644000175000017500000000243511332657403021335 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/xml/test/defaultNamespace.xml0000644000175000017500000000012411332657403022350 0ustar chuckchuck Hello jenkins-dom4j-1.6.1-hudson-3/xml/test/journal.xml0000644000175000017500000000052411332657403020565 0ustar chuckchuck May 19, 2002 Sample text. We should support some markup here. May 19, 2002 10:27 Second batch. jenkins-dom4j-1.6.1-hudson-3/xml/test/product.xml0000644000175000017500000000070411332657403020573 0ustar chuckchuck EQUITY_ CF1 11.11 CF2 22.22 CF3 33.33 jenkins-dom4j-1.6.1-hudson-3/xml/test/mergetext.xml0000644000175000017500000000035211332657403021116 0ustar chuckchuck test < one >]]> test two test three test four test five test six test seven jenkins-dom4j-1.6.1-hudson-3/xml/test/toby.xml0000644000175000017500000010147211332657403020074 0ustar chuckchuck 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 ""
jenkins-dom4j-1.6.1-hudson-3/xml/test/cdata.xml0000644000175000017500000000015511332657403020167 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/test/soap2.xml0000644000175000017500000000220611332657403020136 0ustar chuckchuck en_fr SOAP is quite easy with JSP. jenkins-dom4j-1.6.1-hudson-3/xml/test/webwhitespace.xml0000644000175000017500000000162211332657403021745 0ustar chuckchuck snoop SnoopServlet file ViewFile initial 1000 The initial value for the counter mv *.wm manager director president jenkins-dom4j-1.6.1-hudson-3/xml/test/soap3.xml0000644000175000017500000000061311332657403020137 0ustar chuckchuck
5
DEF
jenkins-dom4j-1.6.1-hudson-3/xml/test/encode.xml0000644000175000017500000000025711332657403020353 0ustar chuckchuck This & that This < that This > that jenkins-dom4j-1.6.1-hudson-3/xml/test/xpath/0000755000175000017500000000000011332657403017514 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xml/test/xpath/tests.xml0000644000175000017500000003320111332657403021377 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/xml/test/jimBrain.xml0000644000175000017500000000131411332657403020644 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/xml/test/DavidHooker.xml0000644000175000017500000000115211332657403021310 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/test/FranzBeilImport1.xml0000644000175000017500000000032011332657403022235 0ustar chuckchuck first text second text third text jenkins-dom4j-1.6.1-hudson-3/xml/test/dosLineFeeds.xml0000644000175000017500000000031311332657403021453 0ustar chuckchuck
Mary had a little lamb.

Test URL Hello, this is a test. jenkins-dom4j-1.6.1-hudson-3/xml/test/sample.xml0000644000175000017500000000035411332657403020375 0ustar chuckchuck red blue green jenkins-dom4j-1.6.1-hudson-3/xml/test/FranzBeilMain.xml0000644000175000017500000000026111332657403021572 0ustar chuckchuck
jenkins-dom4j-1.6.1-hudson-3/xml/test/journal.xsl0000644000175000017500000000112011332657403020564 0ustar chuckchuck Journal

jenkins-dom4j-1.6.1-hudson-3/xml/test/LuisSchema.xsd0000644000175000017500000003666511332657403021165 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/test/test_text.xml0000644000175000017500000000013411332657403021133 0ustar chuckchuck This should work jenkins-dom4j-1.6.1-hudson-3/xml/test/test_schema.xml0000644000175000017500000000057511332657403021420 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/test/FranzBeilImport2.xml0000644000175000017500000000032011332657403022236 0ustar chuckchuck fourth text fifth text sixth text jenkins-dom4j-1.6.1-hudson-3/xml/test/littledoc.xml0000644000175000017500000000036711332657403021103 0ustar chuckchuck Bwahahahah! Twas a dark, rainy night... dfjsdfjsdf fdsfsdfhdsff gyuf uysgf ds jenkins-dom4j-1.6.1-hudson-3/xml/test/longCDATA.xml0000644000175000017500000000375711332657403020622 0ustar chuckchuck 3 Message Matt 4;5 If a shareholder ceases to work for Codex Computing for any reason.doc Moramdum of Understanding 814BFD3FDC5843F0B6DC688C99E1C31E jenkins-dom4j-1.6.1-hudson-3/xml/test/FranzBeilImport3.xml0000644000175000017500000000032411332657403022243 0ustar chuckchuck seventh text eighth text ninth text jenkins-dom4j-1.6.1-hudson-3/xml/test/elementByID.xml0000644000175000017500000000027511332657403021257 0ustar chuckchuck Squeak!

Squeak!

squeak squeak squeak jenkins-dom4j-1.6.1-hudson-3/xml/test/fields.xml0000644000175000017500000000036211332657403020361 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/test/namespaces.xml0000644000175000017500000000044311332657403021232 0ustar chuckchuck Hello Hey Hey2 Hey3 jenkins-dom4j-1.6.1-hudson-3/xml/test/test.xml0000644000175000017500000000024411332657403020071 0ustar chuckchuck ]> &LmInclude; jenkins-dom4j-1.6.1-hudson-3/xml/test/badcomment.xml0000644000175000017500000000013711332657403021224 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/test/defaultNamespaceIssue.xsd0000644000175000017500000007012611332657403023370 0ustar chuckchuck 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. jenkins-dom4j-1.6.1-hudson-3/xml/relaxng/0000755000175000017500000000000011332657403017051 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xml/relaxng/address.rng0000644000175000017500000000044311332657403021207 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/relaxng/bad_address.xml0000644000175000017500000000034511332657403022030 0ustar chuckchuck js@example.com Fred Bloggs Fred Bloggs jenkins-dom4j-1.6.1-hudson-3/xml/relaxng/address.dtd0000644000175000017500000000016411332657403021174 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/relaxng/address.xml0000644000175000017500000000032611332657403021221 0ustar chuckchuck John Smith js@example.com Fred Bloggs fb@example.net jenkins-dom4j-1.6.1-hudson-3/xml/xmlspec.xml0000644000175000017500000046513111332657403017620 0ustar chuckchuck
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 heißem Bemüh'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.) Brüggemann-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. Brüggemann-Klein, Anne, and Derick Wood. Deterministic Regular Languages. Universität Freiburg, Institut für 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 Brüggemann-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
jenkins-dom4j-1.6.1-hudson-3/xml/xml.xml0000644000175000017500000046750711332657403016756 0ustar chuckchuck "> '"> 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 heißem Bemüh'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.) Brüggemann-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. Brüggemann-Klein, Anne, and Derick Wood. Deterministic Regular Languages. Universität Freiburg, Institut für 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 Brüggemann-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
jenkins-dom4j-1.6.1-hudson-3/xml/schema/0000755000175000017500000000000011332657403016651 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xml/schema/invalid.xml0000644000175000017500000000217111332657403021022 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/xml/schema/personal.dtd0000644000175000017500000000120411332657403021166 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/schema/personal-schema.xml0000644000175000017500000000226711332657403022463 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/xml/schema/invalid-schema.xml0000644000175000017500000000234011332657403022256 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/xml/schema/personal.xsd0000644000175000017500000000425211332657403021217 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/schema/personal.xml0000644000175000017500000000212011332657403021211 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/xml/schema/personal-dtd.xml0000644000175000017500000000217111332657403021770 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/xml/periodic_table.xml0000644000175000017500000033475711332657403021123 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/xml/contents.xml0000644000175000017500000000500011332657403017763 0ustar chuckchuck 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? jenkins-dom4j-1.6.1-hudson-3/xml/testNamespaces.xml0000644000175000017500000000072711332657403021120 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/cdata.xml0000644000175000017500000000013511332657403017206 0ustar chuckchuck test < one >]]> test two jenkins-dom4j-1.6.1-hudson-3/xml/soap.xml0000644000175000017500000000072011332657403017074 0ustar chuckchuck en_fr SOAP is quite easy with JSP & dom4j! jenkins-dom4j-1.6.1-hudson-3/xml/dtd/0000755000175000017500000000000011332657403016164 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xml/dtd/external.xml0000644000175000017500000000021511332657403020526 0ustar chuckchuck Hello, world! jenkins-dom4j-1.6.1-hudson-3/xml/dtd/sample.dtd0000644000175000017500000000025411332657403020143 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/dtd/mixed.xml0000644000175000017500000000061011332657403020011 0ustar chuckchuck ]> Hello, world! jenkins-dom4j-1.6.1-hudson-3/xml/dtd/internal.xml0000644000175000017500000000053411332657403020524 0ustar chuckchuck ]> Hello, world! jenkins-dom4j-1.6.1-hudson-3/xml/fibo.xml0000644000175000017500000000212111332657403017046 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/xml/russArticle.xml0000644000175000017500000000105511332657403020434 0ustar chuckchuck
Russian Ïðîãðàììà îáó÷åíèÿ Âèêòîð Âàñèëüåâ Foto & Video_01_03_1.pdf Any caption relating to the article Ïðîãðàììà îáó÷åíèÿ Ôîòîëþáèòåëþ íå ñëåäóåò çàäóìûâàòüñÿ íàä òåì, êàê óïðàâëÿòü öèôðîâîé êàìåðîé. Ýòîò ïðîöåññ äîëæåí áûòü ïðîñòûì è ïîíÿòíûì, êàê â îáû÷íîì ïëåíî÷íîì àïïàðàòå. Casio QV-R3
jenkins-dom4j-1.6.1-hudson-3/xml/inline.xml0000644000175000017500000000052411332657403017412 0ustar chuckchuck ]> God fortsättning på det nya millenniet! jenkins-dom4j-1.6.1-hudson-3/xml/moreover/0000755000175000017500000000000011332657403017247 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xml/moreover/sample.xml0000644000175000017500000002712411332657403021260 0ustar chuckchuck
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
jenkins-dom4j-1.6.1-hudson-3/xml/moreover/moreovernews.dtd0000644000175000017500000000103511332657403022476 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/#.xml0000644000175000017500000000001011332657403016244 0ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xml/xhtml.xml0000644000175000017500000000215311332657403017270 0ustar chuckchuck ]>

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 jenkins-dom4j-1.6.1-hudson-3/xml/much_ado.xml0000644000175000017500000057515311332657403017732 0ustar chuckchuck 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
jenkins-dom4j-1.6.1-hudson-3/xml/xhtml/0000755000175000017500000000000011332657403016545 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xml/xhtml/xhtml-special.ent0000644000175000017500000001017711332657403022035 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/xhtml/xhtml-lat1.ent0000644000175000017500000002732111332657403021255 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/xhtml/xhtml-symbol.ent0000644000175000017500000003404111332657403021716 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/xhtml/xhtml-basic.xml0000644000175000017500000013563111332657403021513 0ustar chuckchuck 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.

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

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:

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:

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:

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 -->
jenkins-dom4j-1.6.1-hudson-3/xml/xhtml/xhtml1-strict.dtd0000644000175000017500000006464211332657403022001 0ustar chuckchuck %HTMLlat1; %HTMLsymbol; %HTMLspecial; jenkins-dom4j-1.6.1-hudson-3/xml/nitf/0000755000175000017500000000000011332657403016351 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xml/nitf/invalid.xml0000644000175000017500000000463511332657403020531 0ustar chuckchuck 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

jenkins-dom4j-1.6.1-hudson-3/xml/nitf/valid.xml0000644000175000017500000000601311332657403020172 0ustar chuckchuck 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

jenkins-dom4j-1.6.1-hudson-3/xml/nitf/sample.xml0000644000175000017500000000575111332657403020364 0ustar chuckchuck 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

jenkins-dom4j-1.6.1-hudson-3/xml/nitf/nitf.dtd0000644000175000017500000024253211332657403020016 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/nitf/ashtml.xsl0000644000175000017500000000367311332657403020402 0ustar chuckchuck
Related Stock: http://localhost/stock?ts=

jenkins-dom4j-1.6.1-hudson-3/xml/jaxb/0000755000175000017500000000000011332657403016335 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xml/jaxb/primer.xml0000644000175000017500000000174211332657403020361 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/xml/jaxb/primer.xsd0000644000175000017500000000474411332657403020364 0ustar chuckchuck Purchase order schema for Example.com. Copyright 2000 Example.com. All rights reserved. jenkins-dom4j-1.6.1-hudson-3/xml/namespaces.xml0000644000175000017500000000116311332657403020253 0ustar chuckchuck <xsl:value-of select="JavaXML:Title" /> jenkins-dom4j-1.6.1-hudson-3/xml/bean/0000755000175000017500000000000011332657403016316 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xml/bean/gui.xml0000644000175000017500000000025411332657403017625 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/rabo1ae.xml0000644000175000017500000002450211332657403017450 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/xml/swing/0000755000175000017500000000000011332657403016540 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xml/swing/tableForAtoms.xml0000644000175000017500000000074111332657403022026 0ustar chuckchuck NameSymbolWeightNumberOxidation States
jenkins-dom4j-1.6.1-hudson-3/xml/swing/tableForWeb.xml0000644000175000017500000000046511332657403021463 0ustar chuckchuck NameClassMapping
jenkins-dom4j-1.6.1-hudson-3/xml/axis.xml0000644000175000017500000000033511332657403017100 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/xml/testPI.xml0000644000175000017500000000031311332657403017340 0ustar chuckchuck Hello he said. The DOM4J home page. More text! jenkins-dom4j-1.6.1-hudson-3/xml/web.xml0000644000175000017500000000146111332657403016712 0ustar chuckchuck snoop SnoopServlet file ViewFile initial 1000 The initial value for the counter snoop /foo/snoop manager director president jenkins-dom4j-1.6.1-hudson-3/TODO.txt0000644000175000017500000000631111332657403016120 0ustar chuckchuckTO DO LIST ========== By all means help yourself to any of these tasks if you fancy rolling your sleeves up and doing some development, tuning, testing or documentation. Any contributions will be greatly received. Development Tasks ================= * As suggested by Robert Lebowitz, consider the pretty printing and OutputFormat to allow very large text nodes to wrap their text at (say) 80 characters per line. * Implement a Saxon adapter so that the SAxon XSLT engine can work natively on top of dom4j. * implement a Locator Element that maintains the column & line number that errors may occur on for better debugging. * implement a proper lazy tree parsing mechanism using the XPP pull parser. * JDBC ResultSet implementation of an Element so that XPath and XSLT can be easily done on a JDBC result set. * Integrate Dennis Sosnoski's XML-Stream work for the default serialization mechansism * Support XPath and XSLT patterns in the ElementHandler mechansim * As suggested by Kesav Kumar Kolla, implement a better, mutable Swing TreeModel possibly along with an optional document event mechansim * get the DOM implementation to pass the DOM conformance tests at http://xmlconf.sourceforge.net/ * a persistent dom4j implementation using XMLDB or some other persistence mechansim * investigate the generation of more optimal Element implementations based on a schema definition, which could still take additional extra schema adjuncts if necessary but would by default use instance member variables for attributes. e.g. could generate public class CustomerElement extends DefaultElement { private String id; private String name; private String location; ... } So the performance benefit of using a bean would remain yet the XPath, XML, SAX benefits would remain, indeed the use of the 'bean' would be invisible. Though this might well be similar to using the BeanElement. Documentation ============= * make cookbook fit for dom4j 1.2 * adding UML diagramms into cookbook * add a easier instruction for programmers that starts to use xml and a instruction for programmers that came form jdom world * add the test-suite html output created by junit-report to project page. * improve FOp output for source code samples Test completed ============== These features have been developed but require more testing to determine that they are complete... * support for setExpandEntities(true) to expand entities, so that text using "&" could just be treated as a String. So A & B could be treated as a single Element with a Text node containing a String "A & B" * merging adjacent text nodes; use an internal StringBuffer to add multiple characters() SAX events together. * whilespace removal option. Without access to a schema or DTD its hard to do proper whitespace removal thanks to mixed content, however a simple option for data-related XML applications, to ignoring all whieespace-only nodes such that James would only contain 1 child element and not 2 whilespace nodes. * support of XMLDB native database (org.dom4j.persistence) jenkins-dom4j-1.6.1-hudson-3/project.xml0000644000175000017500000002134411332657403017005 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/.hgignore0000644000175000017500000000004611332657403016414 0ustar chuckchuckbuild dom4j.ipr dom4j.iws src/Src.iml jenkins-dom4j-1.6.1-hudson-3/.gitignore0000644000175000017500000000001511332657403016575 0ustar chuckchuckbuild target jenkins-dom4j-1.6.1-hudson-3/dom4j/0000755000175000017500000000000011332657403015626 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/dom4j/.cvsignore0000644000175000017500000000012511332657403017624 0ustar chuckchuckvelocity.log* build target dist junit*.properties *.log .classpath .project binjenkins-dom4j-1.6.1-hudson-3/gump.xml0000644000175000017500000000417211332657403016307 0ustar chuckchuck The flexible XML framework for Java org.dom4j sxt xpp jenkins-dom4j-1.6.1-hudson-3/lib/0000755000175000017500000000000011332657403015357 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/lib/test/0000755000175000017500000000000011332657403016336 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/lib/test/JUnitPerf_LICENSE0000644000175000017500000000305611332657403021275 0ustar chuckchuckCopyright (C) 2001 Clarkware Consulting, Inc. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Clarkware Consulting, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact clarkware@clarkware.com. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CLARKWARE CONSULTING OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.jenkins-dom4j-1.6.1-hudson-3/lib/endorsed/0000755000175000017500000000000011332657403017162 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/lib/tools/0000755000175000017500000000000011332657403016517 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/lib/tools/clover.license0000644000175000017500000001652111332657403021362 0ustar chuckchuckProduct: Clover License: Open Source License, 0.x, 1.x Issued: Mon Apr 19 2004 20:06:14 CDT Expiry: Never Key: 1396f93a739a4dc9ac350277e Name: Maarten Coene Org: dom4j Certificate: AAABhW+Ow8B7/zEbxOMqqKwwrdpP+a1COmJGHco7sCNLjHkHnajPF+dQW Ct12PMy0uml0s9xuus5wKngJ9OFk5TFeh01dzQF66bhXH1bvegLfvja3Kle6BYtDv4LZgE gk3E0aJN4IbgTn+TgUckSevXDR4KzK77NWJfrVzkxV3/Jerg/Q7IjCbX2gEysSyZKJen1e /KmvMnPcfTUNYOj6HT1483QqnhPOWFsBfC77ggTTr2uQmWq3MzTQfAKPFy3LHNEKtZUPnG Oayn9MYKn6lmaEzXqkkrLrzG3xhP5oUU1LFdl2T/WJkv0K0aW4dJSu103bnXS7mbk/qDJ3 m2nrSTGvuM92O7Wz6BkUlp6OBju6ewTAk7T9ltmt9vL1lSVECEPtzRyAnPHUC5463gr9iu X5PEC6hs/5tVFy7Y2qNZJ06NXImEZOIMtqycA5SxHlPGOCKpHP0Rj0u8y7OmixYx99ME/0 aHvIN/gzIauaAAlZmw27rvuBAUF0+Zfef7Hzc5dogw6CaZOdHy9O97xdLJTuUGukfFG7fU E18eDhBKchl23D/fi8RtvYF3qxudf0kJFAnEK+WGlUSvcGVZGfe5hEwS82OspRmlux/e15 +54Zk7l5CyZg60Qjh28vSoIKJbpiBksQ8o8ZOaAfsJZyOjeK8H06fBCUVOZFGsf3uZ8gW4 zNxC5yyw= License Agreement: CLOVER VERSION 1 (ONE) SOFTWARE LICENSE AGREEMENT 1. Licenses and Software Cortex eBusiness Pty Ltd, an Australian Proprietary Limited Company ("CENQUA") hereby grants to the purchaser (the "LICENSEE") a limited, revocable, worldwide, non-exclusive, non-transferable, non-sublicensable license to use the Clover version 1 (one) software (the "Software"), including any minor upgrades thereof during the Term (hereinafter defined) up to, but not including the next major version of the Software. The licensee shall not, or knowingly allow others to, reverse engineer, decompile, disassemble, modify, adapt, create derivative works from or otherwise attempt to derive source code from the Software provided. And, in accordance with the terms and conditions of this Software License Agreement (the "Agreement"), the Software shall be used solely by the licensed users in accordance with the following edition specific conditions: a) Server Edition A Server Edition license entitles the Licensee to execute one instance of Clover Server Edition on one (1) machine for the purposes of instrumenting source code and generating reports. There are no limitations on the use of the instrumented source code or generated reports produced by Server Edition. b) Workstation Edition A Workstation Edition license entitles the licensee to use Clover Workstation Edition on one (1) machine by one (1) individual end user. Workstation Edition does not permit the generation of reports for distribution. c) Team Edition A Team Edition license entitles the licensee to use Clover Team edition on any number of machines solely by the licensed number of users. Reports generated by Clover Team Edition are strictly for use only by the licensed number of individual end users. 2. License Fee In exchange for the License(s), the Licensee shall pay to Cenqua a one-time, up front, non-refundable license fee. At the sole discretion of Cenqua this fee will be waived for non-commercial projects. Notwithstanding the Licensee's payment of the License Fee, Cenqua reserves the right to terminate the License if Cenqua discovers that the Licensee and/or the Licensee's use of the Software is in breach of this Agreement. 3. Proprietary Rights Cenqua will retain all right, title and interest in and to the Software, all copies thereof, and Cenqua website(s), software, and other intellectual property, including, but not limited to, ownership of all copyrights, look and feel, trademark rights, design rights, trade secret rights and any and all other intellectual property and other proprietary rights therein. The Licensee will not directly or indirectly obtain or attempt to obtain at any time, any right, title or interest by registration or otherwise in or to the trademarks, service marks, copyrights, trade names, symbols, logos or designations or other intellectual property rights owned or used by Cenqua. All technical manuals or other information provided by Cenqua to the Licensee shall be the sole property of Cenqua. 4. Term and Termination Subject to the other provisions hereof, this Agreement shall commence upon the Licensee's opting into this Agreement and continue until the Licensee discontinues use of the Software or the Agreement terminates automatically upon the Licensee's breach of any term or condition of this Agreement (the "Term"). Upon any such termination, the Licensee will delete the Software immediately. 5. Copying & Transfer The Licensee may copy the Software for back-up purposes only. The Licensee may not assign or otherwise transfer the Software to any third party. 6. Specific Disclaimer of Warranty and Limitation of Liability THE SOFTWARE IS PROVIDED WITHOUT WARRANTY OF ANY KIND. CENQUA DISCLAIMS ALL WARRANTIES, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. CENQUA WILL NOT BE LIABLE FOR ANY DAMAGES ASSOCIATED WITH THE SOFTWARE, INCLUDING, WITHOUT LIMITATION, ORDINARY, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES OF ANY KIND, INCLUDING BUT NOT LIMITED TO DAMAGES RELATING TO LOST DATA OR LOST PROFITS, EVEN IF CENQUA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. Warranties and Representations Licensee Indemnification. CENQUA agrees to indemnify, defend and hold the Licensee harmless from and against any and all liabilities, damages, losses, claims, costs, and expenses (including reasonable legal fees) arising out of or resulting from the Software or the use thereof infringing upon, misappropriating or violating any patents, copyrights, trademarks, or trade secret rights or other proprietary rights of persons, firms or entities who are not parties to this Agreement. CENQUA Indemnification. The Licensee warrants and represents that the Licensee's actions with regard to the Software will be in compliance with all applicable laws; and the Licensee agrees to indemnify, defend, and hold CENQUA harmless from and against any and all liabilities, damages, losses, claims, costs, and expenses (including reasonable legal fees) arising out of or resulting from the Licensee's failure to observe the use restrictions set forth herein. 8. Publicity The Licensee grants permission for CENQUA to use Licensee's name solely in customer lists. CENQUA shall not, without prior consent in writing, use the Licensee's name, or that of its affiliates, in any form with the specific exception of customer lists. CENQUA agrees to remove Licensee's name from any and all materials within 7 days if notified by the Licensee in writing. 9. Governing Law This Agreement shall be governed by the laws of New South Wales, Australia. 10. Independent Contractors The parties are independent contractors with respect to each other, and nothing in this Agreement shall be construed as creating an employer-employee relationship, a partnership, agency relationship or a joint venture between the parties. 11. Assignment This Agreement is not assignable or transferable by the Licensee. CENQUA in its sole discretion may transfer a license to a third party at the written request of the Licensee. 12. Entire Agreement This Agreement constitutes the entire agreement between the parties concerning the Licensee's use of the Software. This Agreement supersedes any prior verbal understanding between the parties and any Licensee purchase order or other ordering document, regardless of whether such document is received by CENQUA before or after execution of this Agreement. This Agreement may be amended only in writing by CENQUA. jenkins-dom4j-1.6.1-hudson-3/pom.xml0000644000175000017500000001621111332657403016127 0ustar chuckchuck 4.0.0 org.jvnet.hudson.dom4j dom4j dom4j 1.6.1-hudson-3 dom4j: the flexible XML framework for Java http://dom4j.org http://sourceforge.net/tracker/?group_id=16035
dom4j-dev@lists.sourceforge.net
2001 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 carnold Curt Arnold carnold@users.sourceforge.net ddlucas David Lucas ddlucas@users.sourceforge.net drwhite David White drwhite@users.sourceforge.net jjenkov Jakob Jenkov jjenkov@users.sourceforge.net jstrachan James Strachan jstrachan@apache.org SpiritSoft, Inc. laramiec Laramie Crocker laramiec@users.sourceforge.net maartenc Maarten Coene maartenc@users.sourceforge.net Cronos mskells Michael Skells mskells@users.sourceforge.net nicksanderson Nick Sanderson nicksanderson@users.sourceforge.net slehmann Steen Lehmann slehmann@users.sourceforge.net tradem Tobias Rademacher tradem@users.sourceforge.net werken Bob McWhirter werken@users.sourceforge.net wolfftw Todd Wolff wolfftw@users.sourceforge.net yeekee OuYang Chen yeekee@users.sourceforge.net yruan2 Yuxin Ruan yruan2@users.sourceforge.net MetaStuff Ltd. http://sourceforge.net/projects/dom4j org.jvnet.maven-antrun-extended-plugin maven-antrun-extended-plugin package run org.jvnet.wagon-svn wagon-svn 1.9 jaxme jaxme-api 0.3 true jaxen jaxen 1.1-beta-6 true msv xsdlib 20030807 true msv relaxngDatatype 20030807 true pull-parser pull-parser 2 true xpp3 xpp3 1.1.3.3 true stax stax-api 1.0 true java.net-m2-repository java-net:/maven2-repository/trunk/repository/ maven2-repository.dev.java.net Java.net Repository for Maven http://download.java.net/maven/2/ maven2-repository.dev.java.net Java.net Repository for Maven http://download.java.net/maven/2/
jenkins-dom4j-1.6.1-hudson-3/LICENSE.txt0000644000175000017500000000352611332657403016442 0ustar chuckchuckCopyright 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. jenkins-dom4j-1.6.1-hudson-3/xdocs/0000755000175000017500000000000011332657403015731 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xdocs/download.xml0000644000175000017500000000401311332657403020260 0ustar chuckchuck 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
        
jenkins-dom4j-1.6.1-hudson-3/xdocs/goals.xml0000644000175000017500000000545111332657403017565 0ustar chuckchuck 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.

jenkins-dom4j-1.6.1-hudson-3/xdocs/compare.xml0000644000175000017500000001033211332657403020100 0ustar chuckchuck 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.

jenkins-dom4j-1.6.1-hudson-3/xdocs/benchmarks/0000755000175000017500000000000011332657403020046 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xdocs/benchmarks/xpath/0000755000175000017500000000000011332657403021172 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xdocs/benchmarks/xpath/index.html0000644000175000017500000012647311332657403023204 0ustar chuckchuck Dom4J performance versus Xerces

Dom4J performance versus Xerces / Xalan

Martin Böhm, 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

 

 

jenkins-dom4j-1.6.1-hudson-3/xdocs/benchmarks/xpath/PerfDOM4JAttr.java0000644000175000017500000002402711332657403024327 0ustar chuckchuck 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); } } jenkins-dom4j-1.6.1-hudson-3/xdocs/benchmarks/xpath/PerfW3C.java0000644000175000017500000002035111332657403023247 0ustar chuckchuck 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); } } jenkins-dom4j-1.6.1-hudson-3/xdocs/benchmarks/xpath/PerfDOM4J.java0000644000175000017500000002156211332657403023475 0ustar chuckchuck 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); } } jenkins-dom4j-1.6.1-hudson-3/xdocs/benchmarks/xpath/w3c_100.xml0000644000175000017500000041566611332657403023012 0ustar chuckchuck 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 jenkins-dom4j-1.6.1-hudson-3/xdocs/benchmarks/xpath/item.xslt0000644000175000017500000000173511332657403023052 0ustar chuckchuck
jenkins-dom4j-1.6.1-hudson-3/xdocs/navigation.xml0000644000175000017500000000355711332657403020624 0ustar chuckchuck dom4j dom4j --> jenkins-dom4j-1.6.1-hudson-3/xdocs/images/0000755000175000017500000000000011332657403017176 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/xdocs/images/logo.gif0000644000175000017500000000206411332657403020627 0ustar chuckchuckGIF89a–ÕÿffÿÌ333ÿ???¿¿¿¿¿ÿß_ÒL™™ÿ¯¯¯òÌ¿OOÿÿÌÌÿfff™™™ßßß첟ÿå™ÿÙe?ßßÿ¯¯ÿ??ÿ333ÿOOOõÙÏffÿÌÌÌÏ?ÜrOfffÕY/ùåßé¥ï¿¯ÿÿÿ!ù,,–ÿ@–pH,Ljg¹D:ŸÐ¨t*T2=ªvûD¾_®xŒ4iÎgÑÑ  Èp*¯o„¼Þ±n»í€}m„Hzˆ|Fs_o…„Œ“,"%ˆ{Gœœ”F)[‘ „) ˜™\£„N` ~š`ŽF É o»DÍÏPzx‰EÊÝ ŸD!u!ãã¤G~ðaE ïñÐàD¹` õmB@ĈC6˜ ±gLÈu>L3ჺ ^µ³¯ˆŽ` dÉׯ<86²B ·aju ¤˜’bÀ¬ÿq 8ìD²Áä—%)} éå§€£ŠèIõ A"–ò”Ø“ÕÂx+‰L01ã“X 4ˆò±Í|Lé yöEä¶`lã¡zðŠ!a2C‘(XuÍ£°ˆŸ°EHHHk®H²ã0jŒbÒCSBâ~ÑK„n€¨C¦¸ÊBtkw•ÑFÃÅÏl¹æM vRø èP)‘`ÍBà n²Y¨á˜7æ,Tè1A·î¯`z#{±Áu6OqŸæª=~œº õÝá¯ËîŠâ8Ì„HЧE “£Sã”C{òè÷œt|-" „ûT—ßr²´Ê†2×ÿ±üD BôDÁEÁ $ó=Ÿ„Ö 1…bø †r¨Û„O\v‘YFTô£zF\à‡{,0‡W†á>3âWã{æ˜ãŽ1"!ʉ:AD ’W‹r±`dH. Á^_Üçá6–‰£•J §!¢7ˆ²à”"Lº·âøÁZ&±å› aç„wf9„êHP[ªS‹G~@ ÎÀCÄ’Tƒ@?G²€›Bðè(Á# âddäm*Q íZÕªRÙh£Ñ=Z§³Šc\!$ppÄ=PlIqĪŒÂÚIìƒOÄŠ¬¤,4°Ö)í˜M¯n@QX<@¶h«’¾z„·Ã’«Å`üŒDEÈ$ƒ’öÂÁ¬lp+ê{ð GÁÉH[RÃW,æIglq$`°¦ñÇsœi —|ð&ž;jenkins-dom4j-1.6.1-hudson-3/xdocs/license.xml0000644000175000017500000000440111332657403020074 0ustar chuckchuck 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.

jenkins-dom4j-1.6.1-hudson-3/xdocs/index.xml0000644000175000017500000002046711332657403017573 0ustar chuckchuck 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

jenkins-dom4j-1.6.1-hudson-3/xdocs/faq.fml0000644000175000017500000005215111332657403017204 0ustar chuckchuck 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" );
jenkins-dom4j-1.6.1-hudson-3/xdocs/guide.xml0000644000175000017500000002003111332657403017544 0ustar chuckchuck 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;
    }
}
jenkins-dom4j-1.6.1-hudson-3/xdocs/changes.xml0000644000175000017500000003673211332657403020076 0ustar chuckchuck 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. jenkins-dom4j-1.6.1-hudson-3/xdocs/status.xml0000644000175000017500000016017511332657403020010 0ustar chuckchuck 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
jenkins-dom4j-1.6.1-hudson-3/checkstyle.xml0000644000175000017500000002157611332657403017504 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/project.properties0000644000175000017500000000454011332657403020400 0ustar chuckchuck# ------------------------------------------------------------------- # 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/**jenkins-dom4j-1.6.1-hudson-3/build.xml0000644000175000017500000006452011332657403016441 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/readme.html0000644000175000017500000000620711332657403016741 0ustar chuckchuck <dom4j> the flexible XML framework for Java
<dom4j> The flexible XML framework for Java
 

Introduction

Thank you for downloading DOM4J we hope you find it useful.

DOM4J is an open source framework for processing XML which is integrated with XPath and fully supports DOM, SAX, JAXP and the Java platform such as Java 2 Collections.

 

Building instructions

The build process in DOM4J uses Ant. The prerequisites for running the Ant build system included with this release are that:-

  • You have a JDK installed on your machine such that the java executable is in your PATH

  • You have the JAVA_HOME environment variable defined to point to the directory in which the JDK is installed. For example on Windows this might be C:\jdk1.3 or on Unix it might be /usr/local/jdk1.3.

In the root directory of this distribution there should be a script which runs on most popular operating systems to build a supplied target using Ant. 

Choose the most suitable script for your platform from the scripts below and typing in the command line expression on the right hand side should display a list of available targets in the Ant build system.

Operating System Script Command line
Windows (NT, 2000) build.bat build usage
Unixes (Linux, Solaris etc). build.sh ./build.sh usage

 

Running the example programs

There are a collection of sample programs that come with the DOM4J distribution. To run any of them you should first build the examples using Ant.

Operating System Command line
Windows (NT, 2000) build samples
Unixes (Linux, Solaris etc). ./build.sh samples

Once that is done there is a run script to run a sample program which sets up the CLASSPATH correctly.

Operating System Command line Example
Windows (NT, 2000) run <className> <arguments> run SAXDemo xml\web.xml
Unixes (Linux, Solaris etc). ./run.sh <className> <arguments> ./run.sh SAXDemo xml/web.xml
jenkins-dom4j-1.6.1-hudson-3/maven.xml0000644000175000017500000000344111332657403016443 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/src/0000755000175000017500000000000011332657403015400 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/test/0000755000175000017500000000000011332657403016357 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/test/org/0000755000175000017500000000000011332657403017146 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/0000755000175000017500000000000011332657403020163 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/ContentTest.java0000644000175000017500000002165111332657403023305 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/CloneTest.java0000644000175000017500000001466711332657403022744 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/dom/0000755000175000017500000000000011332657403020742 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/dom/DOMTest.java0000644000175000017500000002012511332657403023064 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/rule/0000755000175000017500000000000011332657403021132 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/rule/RuleTest.java0000644000175000017500000001210711332657403023545 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/rule/PriorityTest.java0000644000175000017500000000643111332657403024462 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/rule/StylesheetTest.java0000644000175000017500000001342611332657403024774 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/XPathTest.java0000644000175000017500000001363711332657403022724 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/XMLWriterTest.java0000644000175000017500000005053411332657403023532 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/io/0000755000175000017500000000000011332657403020572 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/io/DocumentSourceTest.java0000644000175000017500000000650511332657403025242 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/io/WriteUnmergedTextTest.java0000644000175000017500000001511311332657403025724 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/io/DispatchHandlerTest.java0000644000175000017500000000616311332657403025340 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/io/StaxTest.java0000644000175000017500000001007711332657403023221 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/io/XPP3ReaderTest.java0000644000175000017500000000741411332657403024160 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/io/SAXReaderTest.java0000644000175000017500000001250011332657403024051 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/io/DOMReaderTest.java0000644000175000017500000000706411332657403024046 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/io/DTDTest.java0000644000175000017500000004577111332657403022726 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/io/DOMWriterTest.java0000644000175000017500000001035611332657403024116 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/GetQNamesTest.java0000644000175000017500000000706611332657403023523 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/EmbeddedHandlerTest.java0000644000175000017500000001375211332657403024665 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/0000755000175000017500000000000011332657403021307 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/TextTest.java0000644000175000017500000000732611332657403023746 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/SubstringTest.java0000644000175000017500000000750411332657403025000 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/BooleanTest.java0000644000175000017500000000733611332657403024402 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/SortByTest.java0000644000175000017500000000627611332657403024247 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/SelectSingleNodeTest.java0000644000175000017500000001011211332657403026174 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/AttributeTest.java0000644000175000017500000001005111332657403024752 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/GetPathTest.java0000644000175000017500000001627011332657403024354 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/VariableTest.java0000644000175000017500000001016111332657403024536 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/PrefixTest.java0000644000175000017500000000760211332657403024254 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/NamespaceTest.java0000644000175000017500000001057111332657403024712 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/ObjectTest.java0000644000175000017500000000631511332657403024225 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/FilterTest.java0000644000175000017500000000725211332657403024245 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/ValueOfTest.java0000644000175000017500000001032211332657403024351 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/UriMapTest.java0000644000175000017500000000654411332657403024220 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/MatrixConcatTest.java0000644000175000017500000000757311332657403025422 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/NumberTest.java0000644000175000017500000001031311332657403024240 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/xpath/BadPathTest.java0000644000175000017500000000643011332657403024320 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/util/0000755000175000017500000000000011332657403021140 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/util/PerThreadSingletonTest.java0000644000175000017500000001246411332657403026413 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/util/SimpleSingletonTest.java0000644000175000017500000000774211332657403025771 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/AttributeDetachTest.java0000644000175000017500000000737411332657403024755 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/AddNodeTest.java0000644000175000017500000001020611332657403023163 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/DetachTest.java0000644000175000017500000000763711332657403023073 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/MergeTextTest.java0000644000175000017500000000761211332657403023600 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/GetXMLEncodingTest.java0000644000175000017500000000735111332657403024443 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/HTMLWriterTest.java0000644000175000017500000001470411332657403023635 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/XPathExamplesTest.java0000644000175000017500000002022111332657403024406 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/dtd/0000755000175000017500000000000011332657403020736 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/dtd/InternalEntityDeclTest.java0000644000175000017500000001253611332657403026211 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/dtd/ElementDeclTest.java0000644000175000017500000000705511332657403024631 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/dtd/AttributeDeclTest.java0000644000175000017500000002215511332657403025201 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/dtd/ExternalEntityDeclTest.java0000644000175000017500000001232311332657403026211 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/NamespacesTest.java0000644000175000017500000003320611332657403023751 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/SAXContentHandlerTest.java0000644000175000017500000001053311332657403025154 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/ParseTextTest.java0000644000175000017500000000672311332657403023615 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/MakeElementTest.java0000644000175000017500000001040311332657403024053 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/SetTextTest.java0000644000175000017500000000676011332657403023277 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/ProcessingInstructionTest.java0000644000175000017500000000610111332657403026242 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/NormalizeTest.java0000644000175000017500000000633611332657403023636 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/AbstractTestCase.java0000644000175000017500000002446011332657403024233 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/NamespaceTest.java0000644000175000017500000001410211332657403023560 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/IndexedElementTest.java0000644000175000017500000000745711332657403024575 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/XPathBugTest.java0000644000175000017500000001362611332657403023360 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/ElementByIDTest.java0000644000175000017500000000662111332657403023774 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/XMLResultTest.java0000644000175000017500000001001511332657403023522 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/DocTypeTest.java0000644000175000017500000000706611332657403023246 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/IteratorTest.java0000644000175000017500000001535711332657403023472 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/LineFeedTest.java0000644000175000017500000001037411332657403023346 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/XMLSpaceAttributeTest.java0000644000175000017500000002511111332657403025166 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/AddAttributeTest.java0000644000175000017500000000711311332657403024244 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/datatype/0000755000175000017500000000000011332657403021776 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/datatype/ManualSchemaTest.java0000644000175000017500000000602711332657403026044 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/datatype/AbstractDataTypeTestCase.java0000644000175000017500000000733511332657403027504 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/datatype/AutoSchemaTest.java0000644000175000017500000000765211332657403025544 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/datatype/Datatype2Test.java0000644000175000017500000002614111332657403025342 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/datatype/ManualSchemaPrefixTest.java0000644000175000017500000000577411332657403027232 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/datatype/SetDataTest.java0000644000175000017500000001530011332657403025025 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/datatype/SchemaParseTest.java0000644000175000017500000000604611332657403025702 0ustar chuckchuck/* * Copyright 2001-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 Peña Sánchez * * @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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/datatype/DataTypesTest.java0000644000175000017500000001400311332657403025375 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/BackedListTest.java0000644000175000017500000001207411332657403023677 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/ValidationTest.java0000644000175000017500000000550711332657403023767 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/ParentTest.java0000644000175000017500000001064711332657403023127 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/bean/0000755000175000017500000000000011332657403021070 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/bean/BeansTest.java0000644000175000017500000000530611332657403023627 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/SetContentTest.java0000644000175000017500000001223111332657403023753 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/UserDataTest.java0000644000175000017500000001327511332657403023406 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/tree/0000755000175000017500000000000011332657403021122 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/tree/DefaultDocumentTest.java0000644000175000017500000001305511332657403025714 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/tree/DefaultElementTest.java0000644000175000017500000001462611332657403025534 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/tree/NamespaceCacheTest.java0000644000175000017500000001167011332657403025452 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/tree/CDataTest.java0000644000175000017500000000543111332657403023604 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/XSLTTest.java0000644000175000017500000001012311332657403022455 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/CopyTest.java0000644000175000017500000001063211332657403022602 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/swing/0000755000175000017500000000000011332657403021312 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/swing/TableModelTest.java0000644000175000017500000001240411332657403025026 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/IsTextOnlyTest.java0000644000175000017500000000575011332657403023757 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/NullAttributesTest.java0000644000175000017500000001047511332657403024656 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/RoundTripTest.java0000644000175000017500000001776011332657403023627 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/NodeTypeNameTest.java0000644000175000017500000001245311332657403024223 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/SerializeTest.java0000644000175000017500000001313611332657403023621 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/test/org/dom4j/ThreadingTest.java0000644000175000017500000002765111332657403023606 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/docbook/0000755000175000017500000000000011332657403017020 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/docbook/cookbook.xml0000644000175000017500000020166711332657403021364 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/src/samples/0000755000175000017500000000000011332657403017044 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/samples/org/0000755000175000017500000000000011332657403017633 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/0000755000175000017500000000000011332657403020650 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/0000755000175000017500000000000011332657403022314 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/CreateXMLDemo.java0000644000175000017500000001021611332657403025550 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/jaxp/0000755000175000017500000000000011332657403023256 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/jaxp/WriterDemo.java0000644000175000017500000000706211332657403026207 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/jaxp/PrettyPrintDemo.java0000644000175000017500000000743311332657403027241 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/jaxp/RoundTripDemo.java0000644000175000017500000001114111332657403026652 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/XPathDemo.java0000644000175000017500000000672511332657403025022 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/dom/0000755000175000017500000000000011332657403023073 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/dom/XSLTNativeDOMDemo.java0000644000175000017500000001032411332657403027044 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/dom/SAXDOMDemo.java0000644000175000017500000001035711332657403025544 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/dom/RoundTripDemo.java0000644000175000017500000000662111332657403026476 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/dom/NativeDOMDemo.java0000644000175000017500000000717411332657403026342 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/dom/DOMDemo.java0000644000175000017500000000704111332657403025164 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/rule/0000755000175000017500000000000011332657403023263 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/rule/Songs.xml0000644000175000017500000000624111332657403025101 0ustar chuckchuck 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 jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/rule/SongFilter.xsl0000644000175000017500000000527011332657403026073 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/rule/SongFilter.java0000644000175000017500000001177411332657403026214 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/performance/0000755000175000017500000000000011332657403024615 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/performance/Timer.java0000644000175000017500000001325011332657403026541 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/performance/ParseTest.java0000644000175000017500000000717011332657403027377 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/performance/PerformanceSupport.java0000644000175000017500000000673411332657403031330 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/performance/ParseLoop.java0000644000175000017500000000747511332657403027401 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/performance/PullParseTest.java0000644000175000017500000000723511332657403030236 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/performance/ToTextTest.java0000644000175000017500000000676611332657403027566 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/performance/Task.java0000644000175000017500000000472011332657403026365 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/XPathValueOf.java0000644000175000017500000000735711332657403025501 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/XPathTool.java0000644000175000017500000001276411332657403025053 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/LargeDocumentDemo2.java0000644000175000017500000001104311332657403026576 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/CountDemo.java0000644000175000017500000001022111332657403025050 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/DatatypeDemo.java0000644000175000017500000000600211332657403025535 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/VisitorDemo.java0000644000175000017500000001016011332657403025421 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/validate/0000755000175000017500000000000011332657403024105 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/validate/JARVDemo.java0000644000175000017500000001224311332657403026321 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/validate/XercesDemo.java0000644000175000017500000000741111332657403027011 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/validate/SAXValidatorDemo.java0000644000175000017500000001246311332657403030064 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/validate/JARVDemo2.java0000644000175000017500000001227411332657403026407 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/SAXDemo.java0000644000175000017500000000541211332657403024421 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/JTidyDemo.java0000644000175000017500000000661311332657403025015 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/XPathGrep.java0000644000175000017500000001054711332657403025030 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/VisitorDemo2.java0000644000175000017500000001024211332657403025504 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/LinkChecker.java0000644000175000017500000000617011332657403025345 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/applets/0000755000175000017500000000000011332657403023764 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/applets/SimpleAppletDemo.html0000644000175000017500000000041611332657403030057 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/applets/SimpleAppletDemo.java0000644000175000017500000001035411332657403030036 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/PullParserDemo.java0000644000175000017500000000550211332657403026057 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/RoundTripDemo.java0000644000175000017500000000673311332657403025723 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/AbstractDemo.java0000644000175000017500000001162011332657403025527 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/jaxb/0000755000175000017500000000000011332657403023240 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/jaxb/PurchaseOrderDateModifier.java0000644000175000017500000000551011332657403031127 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/jaxb/JAXBDemo.java0000644000175000017500000002212711332657403025440 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/jaxb/PurchaseOrderHandler.java0000644000175000017500000000553211332657403030154 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/sax/0000755000175000017500000000000011332657403023107 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/sax/TrimXMLFilter.java0000644000175000017500000000616711332657403026426 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/sax/FilterDemo.java0000644000175000017500000000557611332657403026021 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/LargeDocumentDemo.java0000644000175000017500000001040311332657403026513 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/bean/0000755000175000017500000000000011332657403023221 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/bean/BeanDemo.java0000644000175000017500000001023211332657403025534 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/XSLTDemo.java0000644000175000017500000001006511332657403024560 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/swing/0000755000175000017500000000000011332657403023443 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/swing/JTableTool.java0000644000175000017500000001050711332657403026310 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/swing/JTableDemo.java0000644000175000017500000000771611332657403026267 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/swing/JTreeDemo.java0000644000175000017500000000640211332657403026126 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/samples/org/dom4j/samples/HTMLWriterDemo.java0000644000175000017500000000567011332657403025735 0ustar chuckchuck/* * 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 $ */ jenkins-dom4j-1.6.1-hudson-3/src/java/0000755000175000017500000000000011332657403016321 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/java/org/0000755000175000017500000000000011332657403017110 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/0000755000175000017500000000000011332657403020125 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/Text.java0000644000175000017500000000445311332657403021722 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/ElementHandler.java0000644000175000017500000000600711332657403023662 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/CharacterData.java0000644000175000017500000000545111332657403023463 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/XPath.java0000644000175000017500000002660411332657403022024 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/ProcessingInstruction.java0000644000175000017500000000710311332657403025347 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/xpp/0000755000175000017500000000000011332657403020734 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/xpp/package.html0000644000175000017500000000036511332657403023221 0ustar chuckchuck org.dom4j.xpp :: package.html

Provides implementation classes to cleanly integrate dom4j with the XML Pull Parser XPP

jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/xpp/ProxyXmlStartTag.java0000644000175000017500000002326211332657403025060 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/DocumentException.java0000644000175000017500000001022311332657403024423 0ustar chuckchuck/* * Copyright 2001-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; } // on JDK 1.4 and above this helps exception chaining public Throwable getCause() { 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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/Branch.java0000644000175000017500000003004211332657403022164 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/Comment.java0000644000175000017500000000447711332657403022406 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/InvalidXPathException.java0000644000175000017500000000552111332657403025205 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/QName.java0000644000175000017500000002165511332657403022002 0ustar chuckchuck/* * Copyright 2001-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. */jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dom/0000755000175000017500000000000011332657403020704 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dom/DOMAttribute.java0000644000175000017500000001564711332657403024067 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dom/DOMCDATA.java0000644000175000017500000002063411332657403022730 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dom/DOMProcessingInstruction.java0000644000175000017500000001565111332657403026475 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dom/DOMNamespace.java0000644000175000017500000001342511332657403024010 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dom/DOMAttributeNodeMap.java0000644000175000017500000001076011332657403025322 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dom/DOMNodeHelper.java0000644000175000017500000004352211332657403024142 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dom/DOMEntityReference.java0000644000175000017500000001510711332657403025206 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dom/package.html0000644000175000017500000000022111332657403023160 0ustar chuckchuck

An implementation of the dom4j API which also supports the W3C object model.

jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dom/DOMElement.java0000644000175000017500000003252011332657403023502 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dom/DOMDocumentFactory.java0000644000175000017500000001623111332657403025220 0ustar chuckchuck/* * Copyright 2001-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. */jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dom/DOMComment.java0000644000175000017500000001614011332657403023513 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dom/DOMDocumentType.java0000644000175000017500000001506311332657403024534 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dom/DOMDocument.java0000644000175000017500000002553411332657403023676 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dom/DOMText.java0000644000175000017500000002056011332657403023036 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/rule/0000755000175000017500000000000011332657403021074 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/rule/NullAction.java0000644000175000017500000000477011332657403024017 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/rule/RuleSet.java0000644000175000017500000001060211332657403023321 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/rule/pattern/0000755000175000017500000000000011332657403022551 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/rule/pattern/DefaultPattern.java0000644000175000017500000000636711332657403026352 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/rule/pattern/NodeTypePattern.java0000644000175000017500000000760611332657403026512 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/rule/Action.java0000644000175000017500000000466411332657403023166 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/rule/package.html0000644000175000017500000000057511332657403023364 0ustar chuckchuck

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.

jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/rule/Rule.java0000644000175000017500000002202711332657403022651 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/rule/RuleManager.java0000644000175000017500000001627111332657403024150 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/rule/Stylesheet.java0000644000175000017500000002465711332657403024106 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/rule/Mode.java0000644000175000017500000002256411332657403022634 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/rule/Pattern.java0000644000175000017500000001066711332657403023366 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/DocumentHelper.java0000644000175000017500000003254711332657403023721 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/Namespace.java0000644000175000017500000001701311332657403022666 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/NodeFilter.java0000644000175000017500000000526711332657403023035 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/Element.java0000644000175000017500000006713211332657403022372 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/0000755000175000017500000000000011332657403020534 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/STAXEventWriter.java0000644000175000017500000005171511332657403024366 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/SAXModifyReader.java0000644000175000017500000001023011332657403024321 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/ElementModifier.java0000644000175000017500000000635111332657403024454 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/SAXWriter.java0000644000175000017500000007062611332657403023242 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/HTMLWriter.java0000644000175000017500000007110311332657403023342 0ustar chuckchuck/* * Copyright 2001-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; private boolean disabled = false; 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 boolean isEnabled() { return !disabled; } /** * Enable/disable HTML handling. If set to false, behave as plain XMLWriter * (useful if Content-Type is set to something other than text/html). */ public void setEnabled(boolean enabled) { disabled = !enabled; } public void startCDATA() throws SAXException { if (disabled) super.startCDATA(); } public void endCDATA() throws SAXException { if (disabled) super.startCDATA(); } // 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 (disabled || getOutputFormat().isXHTML()) { super.writeCDATA(text); } else { writer.write(text); } lastOutputNodeType = Node.CDATA_SECTION_NODE; } protected void writeEntity(Entity entity) throws IOException { if (disabled) super.writeEntity(entity); else { writer.write(entity.getText()); lastOutputNodeType = Node.ENTITY_REFERENCE_NODE; } } protected void writeDeclaration() throws IOException { if (disabled) super.writeDeclaration(); } protected void writeString(String text) throws IOException { if (disabled) super.writeString(text); else { /* * 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 (disabled || !omitElementClose(qualifiedName)) { super.writeClose(qualifiedName); } } protected void writeEmptyElementClose(String qualifiedName) throws IOException { if (disabled || !omitElementClose(qualifiedName)) { super.writeEmptyElementClose(qualifiedName); } else { if (getOutputFormat().isXHTML()) { // 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 { // it was a special omit tag, do it the old html way: "
". writer.write(">"); } } } 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("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", "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 static 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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/OutputFormat.java0000644000175000017500000004521711332657403024061 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/SAXModifyContentHandler.java0000644000175000017500000002166211332657403026042 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/DOMReader.java0000644000175000017500000002443111332657403023145 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/DocumentSource.java0000644000175000017500000001353411332657403024344 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/DocumentResult.java0000644000175000017500000000712111332657403024355 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/PruningElementStack.java0000644000175000017500000001251611332657403025326 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/XMLResult.java0000644000175000017500000000727511332657403023251 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/SAXContentHandler.java0000644000175000017500000007634611332657403024703 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/SAXEventRecorder.java0000644000175000017500000004747211332657403024540 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/JAXPHelper.java0000644000175000017500000000752611332657403023313 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/package.html0000644000175000017500000000025411332657403023016 0ustar chuckchuck

Provides input and output via SAX and DOM together with writing dom4j objects to streams as XML text.

jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/SAXModifyElementHandler.java0000644000175000017500000001265211332657403026020 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/SAXModifier.java0000644000175000017500000003576411332657403023530 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/ElementStack.java0000644000175000017500000001423411332657403023762 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/DOMWriter.java0000644000175000017500000003465111332657403023224 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/XPP3Reader.java0000644000175000017500000004235611332657403023266 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/PruningDispatchHandler.java0000644000175000017500000000507411332657403026005 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/STAXEventReader.java0000644000175000017500000005737311332657403024322 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/SAXValidator.java0000644000175000017500000001460711332657403023710 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/SAXHelper.java0000644000175000017500000001500711332657403023175 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/SAXReader.java0000644000175000017500000010034611332657403023161 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/DispatchHandler.java0000644000175000017500000002073611332657403024444 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/XPPReader.java0000644000175000017500000003560411332657403023201 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/DocumentInputSource.java0000644000175000017500000001154711332657403025366 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/SAXModifyException.java0000644000175000017500000000505511332657403025066 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/io/XMLWriter.java0000644000175000017500000015771111332657403023250 0ustar chuckchuck/* * Copyright 2001-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.Stack; 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 any content was written in each tag */ private Stack/**/ hadContent = new Stack/**/(); /** 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 { hadContent.clear(); 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; if (!hadContent.isEmpty() && !((Boolean)hadContent.peek()).booleanValue()) { writer.write('>'); hadContent.pop(); hadContent.push(Boolean.TRUE); } writePrintln(); indent(); writer.write('<'); writer.write(qName); writeNamespaces(); writeAttributes(attributes); ++indentLevel; hadContent.push(Boolean.FALSE); 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(); } if (hadContent.isEmpty()) { throw new SAXException("Empty stack; endElement without matching startElement?"); } if (((Boolean)hadContent.pop()).booleanValue()) { 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 { if (!hadContent.isEmpty() && !((Boolean)hadContent.peek()).booleanValue()) { writer.write('>'); hadContent.pop(); hadContent.push(Boolean.TRUE); } /* * 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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/Document.java0000644000175000017500000001402211332657403022545 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/xpath/0000755000175000017500000000000011332657403021251 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/xpath/DefaultXPath.java0000644000175000017500000002663511332657403024461 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/xpath/DefaultNamespaceContext.java0000644000175000017500000000707511332657403026673 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/xpath/package.html0000644000175000017500000000024011332657403023526 0ustar chuckchuck org.dom4j.xpath :: package.html

Provides the core tools needed to use the XPath library

jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/xpath/overview.html0000644000175000017500000000031711332657403024006 0ustar chuckchuck

This XPath implementation attempts to be a fully-compliant implementation of the W3C XPath specification.

jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/xpath/XPathPattern.java0000644000175000017500000001236411332657403024504 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/Visitor.java0000644000175000017500000001162511332657403022434 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/util/0000755000175000017500000000000011332657403021102 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/util/PerThreadSingleton.java0000644000175000017500000000777311332657403025524 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/util/SimpleSingleton.java0000644000175000017500000000672211332657403025070 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/util/UserDataAttribute.java0000644000175000017500000000600211332657403025337 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/util/NonLazyDocumentFactory.java0000644000175000017500000000631211332657403026370 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/util/NonLazyElement.java0000644000175000017500000000620111332657403024650 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/util/package.html0000644000175000017500000000016411332657403023364 0ustar chuckchuck

A collection of utility classes for the dom4j API.

jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/util/UserDataElement.java0000644000175000017500000001030711332657403024770 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/util/SingletonStrategy.java0000644000175000017500000000613111332657403025433 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/util/IndexedDocumentFactory.java0000644000175000017500000000644411332657403026364 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/util/AttributeHelper.java0000644000175000017500000000627011332657403025055 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/util/UserDataDocumentFactory.java0000644000175000017500000000674311332657403026516 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/util/XMLErrorHandler.java0000644000175000017500000001301011332657403024710 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/util/IndexedElement.java0000644000175000017500000002262311332657403024644 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/util/ProxyDocumentFactory.java0000644000175000017500000001532511332657403026123 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/util/NodeComparator.java0000644000175000017500000002506311332657403024670 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/DocumentFactory.java0000644000175000017500000003443711332657403024111 0ustar chuckchuck/* * Copyright 2001-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. */jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/ElementPath.java0000644000175000017500000000766711332657403023216 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dtd/0000755000175000017500000000000011332657403020700 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dtd/ElementDecl.java0000644000175000017500000000656211332657403023735 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dtd/AttributeDecl.java0000644000175000017500000001332711332657403024304 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dtd/package.html0000644000175000017500000000025011332657403023156 0ustar chuckchuck

Classes to represent the DTD declarations. They are used inside the {@link org.dom4j.DocumentType} interface.

jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dtd/ExternalEntityDecl.java0000644000175000017500000001123311332657403025312 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/dtd/InternalEntityDecl.java0000644000175000017500000001134211332657403025305 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/CDATA.java0000644000175000017500000000446111332657403021611 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/IllegalAddException.java0000644000175000017500000000560411332657403024636 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/Node.java0000644000175000017500000004711511332657403021665 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/package.html0000644000175000017500000000023311332657403022404 0ustar chuckchuck

Defines the XML Document Object Model in Java interfaces together with some helper classes.

jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/XPathException.java0000644000175000017500000000613411332657403023677 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/VisitorSupport.java0000644000175000017500000000573411332657403024035 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/DocumentType.java0000644000175000017500000000741311332657403023415 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/datatype/0000755000175000017500000000000011332657403021740 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/datatype/DatatypeAttribute.java0000644000175000017500000001611011332657403026241 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/datatype/DatatypeElementFactory.java0000644000175000017500000001307711332657403027230 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/datatype/DatatypeDocumentFactory.java0000644000175000017500000002027611332657403027414 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/datatype/SchemaParser.java0000644000175000017500000004774711332657403025203 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/datatype/DatatypeElement.java0000644000175000017500000001505011332657403025671 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/datatype/InvalidSchemaException.java0000644000175000017500000000460111332657403027172 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/datatype/package.html0000644000175000017500000000032111332657403024215 0ustar chuckchuck

An implementation of the dom4j API which supports the XML Schema Data Types specification.

jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/datatype/NamedTypeResolver.java0000644000175000017500000001112111332657403026207 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/jaxb/0000755000175000017500000000000011332657403021051 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/jaxb/JAXBSupport.java0000644000175000017500000001145211332657403024040 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/jaxb/JAXBWriter.java0000644000175000017500000002532511332657403023644 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/jaxb/JAXBModifier.java0000644000175000017500000004217411332657403024127 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/jaxb/JAXBObjectModifier.java0000644000175000017500000000614511332657403025254 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/jaxb/JAXBRuntimeException.java0000644000175000017500000000505511332657403025670 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/jaxb/JAXBObjectHandler.java0000644000175000017500000000557011332657403025074 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/jaxb/JAXBReader.java0000644000175000017500000003253111332657403023567 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/Attribute.java0000644000175000017500000001277311332657403022745 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/bean/0000755000175000017500000000000011332657403021032 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/bean/BeanMetaData.java0000644000175000017500000001470711332657403024154 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/bean/BeanAttribute.java0000644000175000017500000000645411332657403024437 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/bean/BeanElement.java0000644000175000017500000001425411332657403024062 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/bean/package.html0000644000175000017500000000030011332657403023304 0ustar chuckchuck

An implementation of the dom4j API which allows JavaBeans to be used to store and retrieve attribute values from Element.

jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/bean/BeanDocumentFactory.java0000644000175000017500000001064611332657403025600 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/bean/BeanAttributeList.java0000644000175000017500000001347411332657403025273 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/0000755000175000017500000000000011332657403021064 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/FlyweightComment.java0000644000175000017500000000600711332657403025217 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/AbstractText.java0000644000175000017500000000567211332657403024351 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/DefaultCDATA.java0000644000175000017500000000642111332657403024053 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/DefaultDocument.java0000644000175000017500000002502211332657403025013 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/AbstractAttribute.java0000644000175000017500000001335511332657403025365 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/DefaultProcessingInstruction.java0000644000175000017500000001065411332657403027620 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/AbstractEntity.java0000644000175000017500000000727411332657403024701 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/QNameCache.java0000644000175000017500000002141411332657403023656 0ustar chuckchuck/* * Copyright 2001-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. */jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/BaseElement.java0000644000175000017500000001305111332657403024113 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/AbstractCharacterData.java0000644000175000017500000000605011332657403026102 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/FlyweightEntity.java0000644000175000017500000001104611332657403025070 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/DefaultNamespace.java0000644000175000017500000001064011332657403025131 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/DefaultComment.java0000644000175000017500000000644111332657403024643 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/FlyweightProcessingInstruction.java0000644000175000017500000001102211332657403030164 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/AbstractCDATA.java0000644000175000017500000000646711332657403024244 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/AbstractBranch.java0000644000175000017500000003254211332657403024616 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/AbstractComment.java0000644000175000017500000000701411332657403025017 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/FilterIterator.java0000644000175000017500000001005311332657403024665 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/AbstractElement.java0000644000175000017500000013102211332657403025003 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/DefaultAttribute.java0000644000175000017500000001103011332657403025172 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/DefaultElement.java0000644000175000017500000007221311332657403024632 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/AbstractNode.java0000644000175000017500000001733311332657403024307 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/DefaultEntity.java0000644000175000017500000000752711332657403024523 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/ContentListFacade.java0000644000175000017500000001420211332657403025260 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/AbstractDocument.java0000644000175000017500000002046211332657403025175 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/FlyweightAttribute.java0000644000175000017500000000770111332657403025562 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/DefaultDocumentType.java0000644000175000017500000001227211332657403025660 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/package.html0000644000175000017500000000037111332657403023346 0ustar chuckchuck

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.

jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/ElementIterator.java0000644000175000017500000000560411332657403025037 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/AbstractProcessingInstruction.java0000644000175000017500000001563411332657403030002 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/FlyweightCDATA.java0000644000175000017500000000576311332657403024441 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/BackedList.java0000644000175000017500000001476211332657403023746 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/ElementNameIterator.java0000644000175000017500000000617611332657403025645 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/NamespaceCache.java0000644000175000017500000001565611332657403024564 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/SingleIterator.java0000644000175000017500000000554011332657403024666 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/NamespaceStack.java0000644000175000017500000003403211332657403024613 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/DefaultText.java0000644000175000017500000000641111332657403024162 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/AbstractDocumentType.java0000644000175000017500000001367011332657403026042 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/FlyweightText.java0000644000175000017500000000575111332657403024546 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/tree/ElementQNameIterator.java0000644000175000017500000000632011332657403025755 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/Entity.java0000644000175000017500000000444311332657403022251 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/swing/0000755000175000017500000000000011332657403021254 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/swing/DocumentTreeModel.java0000644000175000017500000000642511332657403025505 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/swing/XMLTableDefinition.java0000644000175000017500000002327311332657403025547 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/swing/LeafTreeNode.java0000644000175000017500000001036211332657403024416 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/swing/XMLTableColumnDefinition.java0000644000175000017500000001500111332657403026713 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/swing/package.html0000644000175000017500000000027111332657403023535 0ustar chuckchuck

A collection of adapters to allow easy integration with dom4j XML documents and Swing such as TreeModels and TableModels.

jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/swing/XMLTableModel.java0000644000175000017500000001410611332657403024512 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/java/org/dom4j/swing/BranchTreeNode.java0000644000175000017500000001336511332657403024752 0ustar chuckchuck/* * Copyright 2001-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. */ jenkins-dom4j-1.6.1-hudson-3/src/conf/0000755000175000017500000000000011332657403016325 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/conf/MANIFEST.MF0000644000175000017500000000040311332657403017754 0ustar chuckchuckManifest-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 jenkins-dom4j-1.6.1-hudson-3/src/conf/repository.dtd0000644000175000017500000000152111332657403021240 0ustar chuckchuck jenkins-dom4j-1.6.1-hudson-3/src/conf/repository.xml0000644000175000017500000000177011332657403021273 0ustar chuckchuck dom4j: the flexible XML framework for Java http://dom4j.org production dom4j-1.0.jar current CVS HEAD dom4j-daily.jar jenkins-dom4j-1.6.1-hudson-3/src/conf/xsa.xml0000644000175000017500000000135311332657403017644 0ustar chuckchuck 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. jenkins-dom4j-1.6.1-hudson-3/src/doc/0000755000175000017500000000000011332657403016145 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/doc/style/0000755000175000017500000000000011332657403017305 5ustar chuckchuckjenkins-dom4j-1.6.1-hudson-3/src/doc/style/javadoc.css0000644000175000017500000000231111332657403021423 0ustar chuckchuck/* 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 */