libxml-java-1.1.6/0000755000175000017500000000000011636144637012404 5ustar renerenelibxml-java-1.1.6/libxml.iml0000644000175000017500000001667211365606150014402 0ustar renerene libxml-java-1.1.6/common_build.xml0000644000175000017500000020225611365606150015574 0ustar renerene ------------------------------------------------------------------------------- Common Build file provides tasks needed to perform a project build. It is typically not used directly but imported by each project's build.xml file. The build.xml file can override tasks when customization is required. MAIN TARGETS ============ * clean / clean-all : remove all artifacts of the build, clean-all adds the removal of any library or jar dependencies downloaded as part of the build * resolve : download/refresh library or jar dependencies needed for the build (uses Apache IVY) * compile : run javac on the project's source * jar : creates a jar file * dist : creates all project distributables * test : runs JUnit tests from your project's test source SPECIAL TARGETS ============ * publish-local : builds a jar for your project and registers it with the local artifact repository isolated to your machine at $HOME/.ivy2/local. Further executions of the the resolve target by this or other projects will find your published jar. * ivy-clean* : this family of targets helps reset your IVY environment in the event that you are having difficulty resolving dependencies TYPICAL TARGET SEQUENCE ============ * clean-all resolve dist : a good start to build all project distributables from scratch. Note that jar dependencies will not be downloaded unless you explicitly run the resolve target. We made the resolution and retrieval completely discretionary since there are many situations in which you will not want to get or refresh dependencies, e.g. if you are offline with no Internet access. In such case, you could just run "dist" if the set of jars you already have are sufficient. libxml-java-1.1.6/.project0000644000175000017500000000057611365606150014053 0ustar renerene libxml org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature libxml-java-1.1.6/ChangeLog.txt0000644000175000017500000001164711365606150014775 0ustar renerene--------------- 1. WHAT's NEW --------------- A list of changes in recent versions: 0.99.0: (30-May-2008) * [BUG] AbstractReadHandlerFactory must not reset the default handler if the current configuration does not provide one. * Switched from JCommon to LibBase. All version information is now contained in the manifest. The Project-Info implementation reads the version numbers from the Jar's Manifest or the compiler-output-directory. * Various cleanups in the API. * AttributeMap no longer throws a CloneNotSupportedException, like all Collections. * [BUG] DefaultTagDescription assumed that undefined elements were safe to have indentions. This created beautiful documents, but sadly the added spaces broke many of these generated documents. A empty configuration passed into the configure() method no longer causes the tag-description to treat all elements as indentable. * Added better logging to assist the user in case of parsing errors. The current parse-position is now always logged along with the error. * Performance: - AttributeMap is no longer synchronized, as synchronization has to happen in a larger context most of the time. - Added streaming writer methods so that attribute values can be normalized while being sent to the stream instead of having to create temporary strings. 0.9.11: (02-Nov-2007) * Upgraded to jcommon-1.0.12 0.9.10: (29-Oct-2007) * Performance Update * [BUG] XML-writer without encoding produced invalid xml-header. DefaultTagDescription can now be configured using Java-Calls AttributeList.setAttribute() with null-value is now the same as removeAttribute 0.9.9: (16-Oct-2007) * The build-system now uses the modular build again. By default the compile operation returns a automatic-monolithic build that automatically strips all classes that have unresolved dependencies. * Automatic fixes as reported by IntelliJ-IDEA's inspections * Updated the copyright header on all java-files 0.9.8: (24-Sep-2007) * All releases are now built with JDK 1.4. However, we are still compatible with JDK 1.2.2 and all releases run and compile under that release. * [BUG] The XmlWriter's static normalize() method was a cause of synchronization and thread contention issues. 0.9.7: (30-Jul-2007) * [BUG] AttributeList#getAttribute() did not work. * Added common namespace URIs to the LibXmlInfo class, as these namespaces are used in most XML and XHTML processing applications. * Modified the build system so that the build.xml file is now in the root of the project directory. 0.9.6: (24-Jun-2007) * [BUG] CharacterEntities for newline and linefeed characters were wrong. 0.9.5: (27-May-2007) * Added an HTML-Compatibility mode, so that short empty tags have a space before close-marker. 0.9.4: (21-May-2007) * Added support for streaming large Chunks of character-data using a java.io.Reader. This avoids the creation of temporary strings and reduces the memory footprint in some cases. * Added a way to directly parse an XML document without the need to go through LibLoader's interfaces. 0.9.3: (27-Apr-2007) * [BUG] AttributeList.removeAttribute(..) did not work at all. 0.9.2: (01-Apr-2007) * Improved the ability to create XML-Snipplets and to embed the XMLWriter's output in other content. 0.9.1: (07-Mar-2007) * LibLoader's new resource-key system required some change. 0.9.0: (25-Jan-2007) * LibXML is feature complete. Both the parser and writer classes are doing what they should and adding anything else would add extra code for no real value. * The XMLWriterSupport does no longer define the namespaces on a per-document basis. Namespaces are declared using attributes and are inherited to all child-elements. Namespaces can be redefined on each element, if needed. * The parser now follows the Namespace standard and accepts namespace declarations on all elements. * Some first source-code documentation has been added. 0.2.1: (22-Dec-2006) * Improved the parsing of xml files that have a DTD. A handler can now map the DTD into a default namespace. All elements for that document type will have the namespace asigned. 0.2.0: (03-Dec-2006) * Added the XMLWriterSupport and better tag managment. * Each LibXml parser has now access the LibLoader-ResourceKey that was used to load the Xml-Document. 0.1.1: (30-Jul-2006) * More changes to the parser. 0.1.0: (29-Jun-2006) * Initial release of LibXML libxml-java-1.1.6/devresource/0000755000175000017500000000000011365606150014722 5ustar renerenelibxml-java-1.1.6/devresource/META-INF/0000755000175000017500000000000011365606150016062 5ustar renerenelibxml-java-1.1.6/devresource/META-INF/MANIFEST.MF0000644000175000017500000000032211365606150017511 0ustar renereneImplementation-Title: LibXml Implementation-Vendor: Pentaho Corporation Implementation-ProductID: libxml Release-Major-Number: 1 Release-Minor-Number: 0 Release-Milestone-Number: 0 Release-Candidate-Token: dev libxml-java-1.1.6/ivysettings.xml0000644000175000017500000000174311365606150015513 0ustar renerene libxml-java-1.1.6/build.properties0000644000175000017500000000037411365606150015615 0ustar renereneproject.revision=1.1-SNAPSHOT ivy.artifact.group=pentaho-library ivy.artifact.id=libxml impl.title=LibXml impl.productID=libxml src.dir=${basedir}/source dependency.libbase.revision=1.1.6 dependency.libloader.revision=1.1.6 testsrc.dir=${basedir}/test libxml-java-1.1.6/ant/0000755000175000017500000000000011365606150013156 5ustar renerenelibxml-java-1.1.6/ant/build-lib.xml0000644000175000017500000006224211365606150015551 0ustar renerene libxml-java-1.1.6/dev-lib/0000755000175000017500000000000011365606152013720 5ustar renerenelibxml-java-1.1.6/licence-LGPL.txt0000644000175000017500000006605011365606150015302 0ustar renerene GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS As a special exception, the copyright holders of JFreeReport give you permission to extend JFreeReport with independent modules that communicate with JFreeReport solely through the "Expression" or the "Function" interface, regardless of the license terms of these independent modules, and to copy and distribute the resulting combined work under terms of your choice, provided that every copy of the combined work is accompanied by a complete copy of the source code of JFreeReport (the version of JFreeReport used to produce the combined work), being distributed under the terms of the GNU Lesser General Public License plus this exception. An independent module is a module which is not derived from or based on JFreeReport. This exception applies to the Java interfaces "Expression" and "Function" and the classes "AbstractExpression" and "AbstractFunction". Note that people who make modified versions of JFreeReport are not obligated to grant this special exception for their modified versions; it is their choice whether to do so. The GNU Lesser General Public License gives permission to release a modified version without this exception; this exception also makes it possible to release a modified version which carries forward this exception. How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! libxml-java-1.1.6/source/0000755000175000017500000000000011365606150013674 5ustar renerenelibxml-java-1.1.6/source/loader.properties0000644000175000017500000000047111365606146017267 0ustar renerene# # This file registers the loader-factories defined in JFreeReport. Do not # modify it, unless you really want to *remove* support for one of the created # types. org.pentaho.reporting.libraries.resourceloader.factory.type.org.w3c.dom.Document=org.pentaho.reporting.libraries.xmlns.parser.DomTreeResourceFactory libxml-java-1.1.6/source/org/0000755000175000017500000000000011365606146014470 5ustar renerenelibxml-java-1.1.6/source/org/pentaho/0000755000175000017500000000000011365606146016126 5ustar renerenelibxml-java-1.1.6/source/org/pentaho/reporting/0000755000175000017500000000000011365606146020137 5ustar renerenelibxml-java-1.1.6/source/org/pentaho/reporting/libraries/0000755000175000017500000000000011365606146022113 5ustar renerenelibxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/0000755000175000017500000000000011365606150023247 5ustar renerenelibxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/LibXmlBoot.java0000644000175000017500000000460011365606150026125 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns; import org.pentaho.reporting.libraries.base.boot.AbstractBoot; import org.pentaho.reporting.libraries.base.config.Configuration; import org.pentaho.reporting.libraries.base.versioning.ProjectInformation; /** * The LibXmlBoot class is used to initialize the library before it is * first used. This loads all configurations and initializes all factories. *

* Without booting, basic services like logging and the global configuration * will not be availble. * * @author Thomas Morgner */ public class LibXmlBoot extends AbstractBoot { private static LibXmlBoot singleton; /** * Returns the singleton instance of the boot-class. * * @return the singleton booter. */ public static synchronized LibXmlBoot getInstance() { if (singleton == null) { singleton = new LibXmlBoot(); } return singleton; } /** * Private constructor prevents object creation. */ private LibXmlBoot() { } /** * Returns the project info. * * @return The project info. */ protected ProjectInformation getProjectInfo() { return LibXmlInfo.getInstance(); } /** * Loads the configuration. * * @return The configuration. */ protected Configuration loadConfiguration() { return createDefaultHierarchicalConfiguration ("/org/pentaho/reporting/libraries/xmls/libxml.properties", "/libxml.properties", true, LibXmlBoot.class); } /** * Performs the boot. */ protected void performBoot() { } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/common/0000755000175000017500000000000011365606150024537 5ustar renerenelibxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/common/AttributeList.java0000644000175000017500000002423711365606150030211 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.common; import java.util.Iterator; import java.util.Arrays; import org.pentaho.reporting.libraries.base.util.ObjectUtilities; import org.pentaho.reporting.libraries.base.util.LinkedMap; /** * The attribute list is used by a writer to specify the attributes of an XML * element in a certain order. * * @author Thomas Morgner */ public class AttributeList { /** * A constant containing the XML-Namespace namespace identifier. */ public static final String XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/"; /** * A constant containing the XML namespace identifier. */ public static final String XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace"; /** * A name/value pair of the attribute list. */ public static class AttributeEntry { /** * The namespace of the attribute entry. */ private String namespace; /** * The name of the attribute entry. */ private String name; /** * The value of the attribute entry. */ private String value; /** * Creates a new attribute entry for the given name and value. * * @param namespace the namespace of the attribute. * @param name the attribute name (null not permitted). * @param value the attribute value (null not permitted). */ public AttributeEntry(final String namespace, final String name, final String value) { if (name == null) { throw new NullPointerException("Name must not be null. [" + name + ", " + value + ']'); } if (value == null) { throw new NullPointerException("Value must not be null. [" + name + ", " + value + ']'); } this.namespace = namespace; this.name = name; this.value = value; } /** * Returns the attribute name. * * @return the name. */ public String getName() { return this.name; } /** * Returns the value of this attribute entry. * * @return the value of the entry. */ public String getValue() { return this.value; } /** * Returns the attribute namespace (which can be null). * * @return the namespace. */ public String getNamespace() { return namespace; } /** * Compares this attribute entry for equality with an other object. * * @param o the other object. * @return true, if this object is equal, false otherwise. */ public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final AttributeEntry that = (AttributeEntry) o; if (!name.equals(that.name)) { return false; } if (namespace != null ? !namespace.equals(that.namespace) : that.namespace != null) { return false; } return true; } /** * Computes a hashcode for this attribute entry. * * @return the attribute entry's hashcode. */ public int hashCode() { int result = (namespace != null ? namespace.hashCode() : 0); result = 29 * result + name.hashCode(); return result; } protected void update(final String namespace, final String name, final String value) { if (name == null) { throw new NullPointerException("Name must not be null. [" + name + ", " + value + ']'); } if (value == null) { throw new NullPointerException("Value must not be null. [" + name + ", " + value + ']'); } this.namespace = namespace; this.name = name; this.value = value; } } /** * The storage for all entries of this list. */ private LinkedMap entryList; private AttributeEntry lookupKey; private transient AttributeEntry[] arrayCache; /** * Creates an empty attribute list with no default values. */ public AttributeList() { this.entryList = new LinkedMap(); this.lookupKey = new AttributeEntry(null, "lookup", "value"); } /** * Returns an iterator over the entry list. The iterator returns * AttributeList.AttributeEntry objects. * * @return the iterator over the entries contained in this list. * @deprecated use toArray instead. */ public Iterator iterator() { return Arrays.asList(entryList.values()).iterator(); } public AttributeEntry[] toArray() { if (arrayCache == null) { arrayCache = (AttributeEntry[]) entryList.values(new AttributeEntry[entryList.size()]); } return (AttributeEntry[]) arrayCache.clone(); } /** * Defines an attribute. * * @param namespace the namespace of the attribute. * @param name the name of the attribute to be defined * @param value the value of the attribute. */ public void setAttribute(final String namespace, final String name, final String value) { if (value == null) { removeAttribute(namespace, name); return; } final AttributeEntry entry = new AttributeEntry(namespace, name, value); this.arrayCache = null; this.entryList.put(entry, entry); } /** * Returns the attribute value for the given attribute name or null, if the * attribute is not defined in this list. * * @param namespace the namespace of the attribute. * @param name the name of the attribute * @return the attribute value or null. */ public String getAttribute(final String namespace, final String name) { return getAttribute(namespace, name, null); } /** * Returns the attribute value for the given attribute name or the given * defaultvalue, if the attribute is not defined in this list. * * @param namespace the namespace of the attribute. * @param name the name of the attribute. * @param defaultValue the default value. * @return the attribute value or the defaultValue. */ public String getAttribute(final String namespace, final String name, final String defaultValue) { lookupKey.update(namespace, name, ""); final AttributeEntry entry = (AttributeEntry) this.entryList.get(lookupKey); if (entry != null) { return entry.getValue(); } return defaultValue; } /** * Removes the attribute with the given name from the list. * * @param namespace the namespace of the attribute that should be removed. * @param name the name of the attribute which should be removed.. */ public void removeAttribute(final String namespace, final String name) { lookupKey.update(namespace, name, ""); entryList.remove(lookupKey); this.arrayCache = null; } /** * Checks, whether this list is empty. * * @return true, if the list is empty, false otherwise. */ public boolean isEmpty() { return this.entryList.isEmpty(); } /** * Adds a namespace declaration. In XML, Namespaces are declared by * using a special attribute-syntax. As this syntax is confusing and * complicated, this method encapsulates this and make defining * namespaces less confusing. * * @param prefix the desired namespace prefix (can be null or empty to * define the default namespace. * @param namespaceUri the URI of the namespace. */ public void addNamespaceDeclaration(final String prefix, final String namespaceUri) { if (namespaceUri == null) { throw new NullPointerException(); } if (prefix == null || "".equals(prefix)) { setAttribute(AttributeList.XMLNS_NAMESPACE, "", namespaceUri); } else { setAttribute(AttributeList.XMLNS_NAMESPACE, prefix, namespaceUri); } } /** * Removes a namespace declaration from this attribute list. * * @param prefix the declared namespace prefix. */ public void removeNamespaceDeclaration(final String prefix) { if (prefix == null || "".equals(prefix)) { removeAttribute(AttributeList.XMLNS_NAMESPACE, ""); } else { removeAttribute(AttributeList.XMLNS_NAMESPACE, prefix); } } /** * Checks, whether the given prefix is defined. * * @param prefix the namespace prefix. * @return true, if the prefix is defined, false otherwise. */ public boolean isNamespacePrefixDefined(final String prefix) { return getAttribute(AttributeList.XMLNS_NAMESPACE, prefix) != null; } /** * Checks, whether the given namespace URI has a defined prefix. * * @param uri the uri. * @return true, if there is at least one namespace declaration matching * the given URI, false otherwise. */ public boolean isNamespaceUriDefined(final String uri) { if (this.entryList.isEmpty()) { return false; } final AttributeEntry[] objects = toArray(); for (int i = 0; i < objects.length; i++) { final AttributeEntry ae = objects[i]; if (ObjectUtilities.equal(ae.getValue(), uri) && AttributeList.XMLNS_NAMESPACE.equals(ae.getNamespace())) { return true; } } return false; } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/common/ParserUtil.java0000644000175000017500000002051111365606150027473 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.common; import org.pentaho.reporting.libraries.xmlns.parser.ParseException; import org.pentaho.reporting.libraries.xmlns.LibXmlBoot; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Basic helper functions to ease up the process of parsing. * * @author Thomas Morgner */ public class ParserUtil { private static final Log logger = LogFactory.getLog(ParserUtil.class); private static boolean strictParsing; static { strictParsing = "true".equals(LibXmlBoot.getInstance().getGlobalConfig().getConfigProperty ("org.pentaho.reporting.libraries.xmlns.StrictParseMode")); } /** * Private constructors prevent initializations of utility classes. */ private ParserUtil() { } /** * Parses the string text into an int. If text is null or does * not contain a parsable value, the message given in message * is used to throw a SAXException. * * @param text the text to parse. * @param message the error message if parsing fails. * @param locator the SAX locator to print meaningfull error messages. * @return the int value. * @throws SAXException if there is a problem with the parsing. */ public static int parseInt(final String text, final String message, final Locator locator) throws SAXException { if (text == null) { throw new SAXException(message); } try { return Integer.parseInt(text); } catch (NumberFormatException nfe) { throw new ParseException("NumberFormatError: " + message, locator); } } /** * Parses the string text into an int. If text is null or does * not contain a parsable value, the message given in message * is used to throw a SAXException. * * @param text the text to parse. * @param message the error message if parsing fails. * @return the int value. * @throws SAXException if there is a problem with the parsing. */ public static int parseInt(final String text, final String message) throws SAXException { if (text == null) { throw new SAXException(message); } try { return Integer.parseInt(text); } catch (NumberFormatException nfe) { throw new SAXException("NumberFormatError: " + message); } } /** * Parses an integer. * * @param text the text to parse. * @param defaultVal the default value. * @return the integer. */ public static int parseInt(final String text, final int defaultVal) { if (text == null) { return defaultVal; } try { return Integer.parseInt(text); } catch (NumberFormatException nfe) { return defaultVal; } } /** * Parses the string text into an float. If text is null or * does not contain a parsable value, the message given in * message is used to throw a SAXException. * * @param text the text to parse. * @param message the error message if parsing fails. * @param locator the SAX locator to print meaningfull error messages. * @return the float value. * @throws ParseException if the text is no valid float number. */ public static float parseFloat(final String text, final String message, final Locator locator) throws ParseException { if (text == null) { throw new ParseException(message, locator); } try { return Float.parseFloat(text); } catch (NumberFormatException nfe) { throw new ParseException("NumberFormatError: " + message, locator); } } /** * Parses the string text into an float. If text is null or * does not contain a parsable value, the message given in * message is used to throw a SAXException. * * @param text the text to parse. * @param message the error message if parsing fails. * @return the float value. * @throws SAXException if there is a problem with the parsing. */ public static float parseFloat(final String text, final String message) throws SAXException { if (text == null) { throw new SAXException(message); } try { return Float.parseFloat(text); } catch (NumberFormatException nfe) { throw new SAXException("NumberFormatError: " + message); } } /** * Parses the string text into an float. If text is null or * does not contain a parsable value, the message given in * message is used to throw a SAXException. * * @param text the text to parse. * @param defaultVal the defaultValue returned if parsing fails. * @return the float value. */ public static float parseFloat(final String text, final float defaultVal) { if (text == null) { return defaultVal; } try { return Float.parseFloat(text); } catch (NumberFormatException nfe) { return defaultVal; } } /** * Parses a boolean. If the string text contains the value of * "true", the true value is returned, else false is returned. * * @param text the text to parse. * @param defaultVal the default value. * @return a boolean. */ public static boolean parseBoolean(final String text, final boolean defaultVal) { if (text == null) { return defaultVal; } if (strictParsing) { return "true".equals(text); } else { if (text.equals("true")) { return true; } else if (text.equals("false")) { return false; } logger.warn("Invalid value encountered: Expected 'true' or 'false', but got '" + text + "'"); return "true".equalsIgnoreCase(text); } } /** * Translates an boolean string ("true" or "false") into the corresponding Boolean * object. * * @param value the string that represents the boolean. * @param locator the SAX locator to print meaningfull error messages. * @return Boolean.TRUE or Boolean.FALSE * @throws ParseException if an parse error occured or the string is not * 'true' or 'false'. */ public static Boolean parseBoolean(final String value, final Locator locator) throws ParseException { if (value == null) { return null; } if ("true".equals(value)) { return Boolean.TRUE; } else if ("false".equals(value)) { return Boolean.FALSE; } if (strictParsing) { throw new ParseException("Failed to parse: Expected 'true' or 'false'", locator); } if (locator == null) { logger.warn("Invalid value encountered for boolean attribute."); } else { logger.warn("Invalid value encountered for boolean attribute. [Line: " + locator.getLineNumber() + " Column: " + locator.getColumnNumber() + "]"); } return Boolean.FALSE; } /** * Parses a string. If the text is null, defaultval is * returned. * * @param text the text to parse. * @param defaultVal the default value. * @return a string. */ public static String parseString(final String text, final String defaultVal) { if (text == null) { return defaultVal; } return text; } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/common/AttributeMap.java0000644000175000017500000002675011365606150030015 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.common; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.pentaho.reporting.libraries.base.util.Empty; /** * A attribute map holding <namspace;name>-value pairs. * * @author Thomas Morgner */ public class AttributeMap implements Serializable, Cloneable { private static final String[] EMPTY_NAMESPACES = new String[0]; private static final long serialVersionUID = -7442871030874215436L; private HashMap namespaces; private String singletonNamespace; private HashMap singletonContent; /** * Default constructor. */ public AttributeMap() { } /** * Creates a new attibute map using the given parameter as source for the initial values. * * @param copy the attribute map that should be copied. */ public AttributeMap(final AttributeMap copy) { if (copy == null) { return; } if (copy.singletonNamespace != null) { singletonNamespace = copy.singletonNamespace; singletonContent = (HashMap) copy.singletonContent.clone(); } if (copy.namespaces == null) { return; } namespaces = (HashMap) copy.namespaces.clone(); final Iterator entries = namespaces.entrySet().iterator(); while (entries.hasNext()) { final Map.Entry entry = (Map.Entry) entries.next(); final HashMap value = (HashMap) entry.getValue(); entry.setValue(value.clone()); } } /** * Creates a copy of this map. * * @return the clone. * @noinspection CloneDoesntDeclareCloneNotSupportedException */ public Object clone() { try { final AttributeMap map = (AttributeMap) super.clone(); if (singletonNamespace != null) { map.singletonContent = (HashMap) singletonContent.clone(); } if (namespaces != null) { map.namespaces = (HashMap) namespaces.clone(); final Iterator entries = map.namespaces.entrySet().iterator(); while (entries.hasNext()) { final Map.Entry entry = (Map.Entry) entries.next(); final HashMap value = (HashMap) entry.getValue(); entry.setValue(value.clone()); } } return map; } catch (final CloneNotSupportedException cne) { // ignored throw new IllegalStateException("Cannot happen: Clone not supported exception"); } } /** * Defines the attribute for the given namespace and attribute name. * * @param namespace the namespace under which the value should be stored. * @param attribute the attribute name under which the value should be stored within the namespace. * @param value the value. * @return the previously stored value at that position. */ public Object setAttribute(final String namespace, final String attribute, final Object value) { if (namespace == null) { throw new NullPointerException("Attribute namespace must not be null"); } if (attribute == null) { throw new NullPointerException("Attribute name must not be null"); } if (singletonNamespace == null) { singletonNamespace = namespace; singletonContent = new HashMap(); singletonContent.put(attribute, value); return null; } if (namespace.equals(singletonNamespace)) { return singletonContent.put(attribute, value); } if (namespaces == null) { namespaces = new HashMap(); } final HashMap attrs = (HashMap) namespaces.get(namespace); if (attrs == null) { if (value == null) { return null; } final HashMap newAtts = new HashMap(); newAtts.put(attribute, value); namespaces.put(namespace, newAtts); return null; } else { if (value == null) { final Object retval = attrs.remove(attribute); if (attrs.isEmpty()) { namespaces.remove(namespace); } return retval; } else { return attrs.put(attribute, value); } } } /** * Returns the attribute value for the given namespace and attribute-name. * * @param namespace the namespace. * @param attribute the attribute name. * @return the value or null, if there is no such namespace/attribute name combination. */ public Object getAttribute(final String namespace, final String attribute) { if (namespace == null) { throw new NullPointerException("Attribute namespace must not be null"); } if (attribute == null) { throw new NullPointerException("Attribute name must not be null"); } if (singletonNamespace == null) { return null; } if (namespace.equals(singletonNamespace)) { return singletonContent.get(attribute); } if (namespaces == null) { return null; } final HashMap attrs = (HashMap) namespaces.get(namespace); if (attrs == null) { return null; } else { return attrs.get(attribute); } } /** * Looks up all namespaces and returns the value from the first namespace that has this attribute defined. As the * order of the namespaces is not defined, this returns a random value and the namespace used is undefined if more * than one namespace contains the same attribute. * * @param attribute the the attribute name. * @return the object from the first namespace that carries this attribute or null, if none of the namespaces has such * an attribute defined. */ public Object getFirstAttribute(final String attribute) { if (attribute == null) { throw new NullPointerException("Attribute name must not be null"); } if (singletonContent != null) { final Object val = singletonContent.get(attribute); if (val != null) { return val; } } if (namespaces == null) { return null; } final Iterator entries = namespaces.entrySet().iterator(); while (entries.hasNext()) { final Map.Entry entry = (Map.Entry) entries.next(); final HashMap map = (HashMap) entry.getValue(); final Object val = map.get(attribute); if (val != null) { return val; } } return null; } /** * Returns all attributes of the given namespace as unmodifable map. * * @param namespace the namespace for which the attributes should be returned. * @return the map, never null. */ public Map getAttributes(final String namespace) { if (namespace == null) { throw new NullPointerException("Attribute namespace must not be null"); } if (namespace.equals(singletonNamespace)) { return Collections.unmodifiableMap(singletonContent); } if (namespaces == null) { return Empty.MAP; } final HashMap attrs = (HashMap) namespaces.get(namespace); if (attrs == null) { return Empty.MAP; } else { return Collections.unmodifiableMap(attrs); } } /** * Returns all names for the given namespace that have values in this map. * * @param namespace the namespace for which known attribute names should be looked up. * @return the names stored for the given namespace. */ public String[] getNames(final String namespace) { if (namespace == null) { throw new NullPointerException("Attribute namespace must not be null"); } if (namespace.equals(singletonNamespace)) { return (String[]) singletonContent.keySet().toArray(new String[singletonContent.size()]); } if (namespaces == null) { return AttributeMap.EMPTY_NAMESPACES; } final HashMap attrs = (HashMap) namespaces.get(namespace); if (attrs == null) { return AttributeMap.EMPTY_NAMESPACES; } else { return (String[]) attrs.keySet().toArray(new String[attrs.size()]); } } /** * Returns all namespaces that have values in this map. * * @return the namespaces stored in this map. */ public String[] getNameSpaces() { if (namespaces == null) { if (singletonContent != null) { return new String[]{singletonNamespace}; } return AttributeMap.EMPTY_NAMESPACES; } final String[] strings = (String[]) namespaces.keySet().toArray(new String[namespaces.size() + 1]); strings[strings.length - 1] = singletonNamespace; return strings; } public void putAll(final AttributeMap attributeMap) { final String[] namespaces = attributeMap.getNameSpaces(); if (namespaces.length == 0) { return; } final boolean dontCopySingleton; if (this.singletonNamespace == null) { dontCopySingleton = true; this.singletonNamespace = attributeMap.singletonNamespace; this.singletonContent = (HashMap) attributeMap.singletonContent.clone(); } else { if (this.singletonNamespace.equals(attributeMap.singletonNamespace)) { dontCopySingleton = true; this.singletonContent.putAll(attributeMap.singletonContent); } else { dontCopySingleton = false; } } for (int i = 0; i < namespaces.length; i++) { final String namespace = namespaces[i]; final Map sourceMap = attributeMap.getAttributes(namespace); if (dontCopySingleton && singletonNamespace.equals(namespace)) { continue; } final HashMap targetMap = (HashMap) this.namespaces.get(namespace); if (targetMap == null) { this.namespaces.put(namespace, new HashMap(sourceMap)); } else { targetMap.putAll(sourceMap); } } } public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final AttributeMap that = (AttributeMap) o; if (singletonNamespace != null ? !singletonNamespace.equals(that.singletonNamespace) : that.singletonNamespace != null) { return false; } if (singletonContent != null ? !singletonContent.equals(that.singletonContent) : that.singletonContent != null) { return false; } if (namespaces != null ? !namespaces.equals(that.namespaces) : that.namespaces != null) { return false; } return true; } public int hashCode() { int result = namespaces != null ? namespaces.hashCode() : 0; result = 31 * result + (singletonNamespace != null ? singletonNamespace.hashCode() : 0); result = 31 * result + (singletonContent != null ? singletonContent.hashCode() : 0); return result; } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/libxml.properties0000644000175000017500000000053111365606150026653 0ustar renerene# # Defines, whether the parser will validate boolean and alignment attributes using a strict algorithm. # To parse reports created in ancient versions, this attributee can be set to true, but we always set # it to false as default to encourage users to write clean report definitions. org.pentaho.reporting.libraries.xmlns.StrictParseMode=true libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/0000755000175000017500000000000011365606150024543 5ustar renerenelibxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/XmlFactoryModule.java0000644000175000017500000000560411365606150030651 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; /** * The XmlFactoryModule is the base of a plugin-structure to allow * parser-multiplexing. In that case, the actual implementation of the * parser will be selected according to the DTD, Namespace or root-tag * of the document. * * @author Thomas Morgner */ public interface XmlFactoryModule { /** * A constant declaring that the content has been recognized by the * declared namespace. */ public static final int RECOGNIZED_BY_NAMESPACE = 4000; /** * A constant declaring that the content has been recognized by the * declared Document Type Declaration (DTD). */ public static final int RECOGNIZED_BY_DTD = 2000; /** * A constant declaring that the content has been recognized by the * tagname of the root-element of the XML-document. */ public static final int RECOGNIZED_BY_TAGNAME = 1000; /** * A constant declaring that the content has NOT been recognized by any mean. */ public static final int NOT_RECOGNIZED = -1; /** * Checks the given document data to compute the propability of whether this * factory module would be able to handle the given data. * * @param documentInfo the document information collection. * @return an integer value indicating how good the document matches the * factories requirements. */ public int getDocumentSupport(XmlDocumentInfo documentInfo); /** * Creates an XmlReadHandler for the root-tag based on the given document * information. * * @param documentInfo the document information that has been extracted from * the parser. * @return the root handler or null. */ public XmlReadHandler createReadHandler(XmlDocumentInfo documentInfo); /** * Returns the default namespace for a document with the characteristics * given in the XmlDocumentInfo. * * @param documentInfo the document information. * @return the default namespace uri for the document. */ public String getDefaultNamespace(XmlDocumentInfo documentInfo); } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/AbstractXmlResourceFactory.javalibxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/AbstractXmlResourceFactory.jav0000644000175000017500000003607711365606150032546 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import java.io.IOException; import java.net.URL; import java.util.Iterator; import java.util.Map; import java.util.ArrayList; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.reporting.libraries.resourceloader.CompoundResource; import org.pentaho.reporting.libraries.resourceloader.FactoryParameterKey; import org.pentaho.reporting.libraries.resourceloader.Resource; import org.pentaho.reporting.libraries.resourceloader.ResourceCreationException; import org.pentaho.reporting.libraries.resourceloader.ResourceData; import org.pentaho.reporting.libraries.resourceloader.ResourceFactory; import org.pentaho.reporting.libraries.resourceloader.ResourceKey; import org.pentaho.reporting.libraries.resourceloader.ResourceKeyCreationException; import org.pentaho.reporting.libraries.resourceloader.ResourceLoadingException; import org.pentaho.reporting.libraries.resourceloader.ResourceManager; import org.pentaho.reporting.libraries.resourceloader.loader.raw.RawResourceData; import org.pentaho.reporting.libraries.base.config.Configuration; import org.pentaho.reporting.libraries.base.config.DefaultConfiguration; import org.pentaho.reporting.libraries.base.util.ObjectUtilities; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * A base-class for resource-factories that load their resources from XML files. This class provides a multiplexing * option. For this, the parser looks at the root-element of the document to be parsed and selects the most suitable * XmlFactoryModule implementation registered. * * @author Thomas Morgner */ public abstract class AbstractXmlResourceFactory implements ResourceFactory { private static final Log logger = LogFactory.getLog(AbstractXmlResourceFactory.class); /** * A key for the content base. */ public static final String CONTENTBASE_KEY = "content-base"; private static final byte[] EMPTY_DATA = new byte[0]; private ArrayList modules; private SAXParserFactory factory; /** * Default-Constructor. */ protected AbstractXmlResourceFactory() { modules = new ArrayList(); } /** * Returns a SAX parser. * * @return a SAXParser. * @throws ParserConfigurationException if there is a problem configuring the * parser. * @throws SAXException if there is a problem with the parser * initialisation */ protected SAXParser getParser() throws ParserConfigurationException, SAXException { if (this.factory == null) { this.factory = SAXParserFactory.newInstance(); } return this.factory.newSAXParser(); } /** * Configures the xml reader. Use this to set features or properties before * the documents get parsed. * * @param handler the parser implementation that will handle the * SAX-Callbacks. * @param reader the xml reader that should be configured. */ protected void configureReader(final XMLReader reader, final MultiplexRootElementHandler handler) { try { reader.setProperty ("http://xml.org/sax/properties/lexical-handler", handler.getCommentHandler()); } catch (SAXException se) { logger.debug("Comments are not supported by this SAX implementation."); } try { reader.setFeature("http://xml.org/sax/features/xmlns-uris", true); } catch (SAXException e) { handler.setXmlnsUrisNotAvailable(true); } try { reader.setFeature("http://xml.org/sax/features/namespaces", true); reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); } catch (SAXException e) { logger.warn("No Namespace features will be available. (Yes, this is serious)"); } } /** * Creates a resource by interpreting the data given in the resource-data object. If additional datastreams need to * be parsed, the provided resource manager should be used. This method parses the given resource-data as XML stream. * * @param manager the resource manager used for all resource loading. * @param data the resource-data from where the binary data is read. * @param context the resource context used to resolve relative resource paths. * @return the parsed result, never null. * @throws ResourceCreationException if the resource could not be parsed due to syntaxctial or logical errors in the data. * @throws ResourceLoadingException if the resource could not be accessed from the physical storage. */ public Resource create(final ResourceManager manager, final ResourceData data, final ResourceKey context) throws ResourceCreationException, ResourceLoadingException { try { final SAXParser parser = getParser(); final XMLReader reader = parser.getXMLReader(); final XmlFactoryModule[] rootHandlers = getModules(); if (rootHandlers.length == 0) { throw new ResourceCreationException("There are no root-handlers registered for the factory for type " + getFactoryType()); } final ResourceDataInputSource input = new ResourceDataInputSource(data, manager); final ResourceKey contextKey; final long version; final ResourceKey targetKey = data.getKey(); if (context == null) { contextKey = targetKey; version = data.getVersion(manager); } else { contextKey = context; version = -1; } final MultiplexRootElementHandler handler = new MultiplexRootElementHandler(manager, targetKey, contextKey, version, rootHandlers); final DefaultConfiguration parserConfiguration = handler.getParserConfiguration(); final URL value = manager.toURL(contextKey); if (value != null) { parserConfiguration.setConfigProperty(CONTENTBASE_KEY, value.toExternalForm()); } configureReader(reader, handler); reader.setContentHandler(handler); reader.setDTDHandler(handler); reader.setEntityResolver(handler.getEntityResolver()); reader.setErrorHandler(getErrorHandler()); final Map parameters = targetKey.getFactoryParameters(); final Iterator it = parameters.keySet().iterator(); while (it.hasNext()) { final Object o = it.next(); if (o instanceof FactoryParameterKey) { final FactoryParameterKey fpk = (FactoryParameterKey) o; handler.setHelperObject(fpk.getName(), parameters.get(fpk)); } } reader.parse(input); final Object createdProduct = finishResult (handler.getResult(), manager, data, contextKey); handler.getDependencyCollector().add(targetKey, data.getVersion(manager)); return createResource(targetKey, handler, createdProduct, getFactoryType()); } catch (ParserConfigurationException e) { throw new ResourceCreationException("Unable to initialize the XML-Parser", e); } catch (SAXException e) { throw new ResourceCreationException("Unable to parse the document: " + data.getKey(), e); } catch (IOException e) { throw new ResourceLoadingException("Unable to read the stream from document: " + data.getKey(), e); } } /** * A method to allow to invoke the parsing without accessing the LibLoader layer. The data to be parsed is held in * the given InputSource object. * * @param manager the resource manager used for all resource loading. * @param input the raw-data given as SAX-InputSource. * @param context the resource context used to resolve relative resource paths. * @param parameters the parse parameters. * @return the parsed result, never null. * @throws ResourceCreationException if the resource could not be parsed due to syntaxctial or logical errors in the data. * @throws ResourceLoadingException if the resource could not be accessed from the physical storage. * @throws ResourceKeyCreationException if creating the context key failed. */ public Object parseDirectly(final ResourceManager manager, final InputSource input, final ResourceKey context, final Map parameters) throws ResourceKeyCreationException, ResourceCreationException, ResourceLoadingException { try { final SAXParser parser = getParser(); final XMLReader reader = parser.getXMLReader(); final XmlFactoryModule[] rootHandlers = getModules(); final ResourceKey targetKey = manager.createKey(EMPTY_DATA); final ResourceKey contextKey; if (context == null) { contextKey = targetKey; } else { contextKey = context; } final MultiplexRootElementHandler handler = new MultiplexRootElementHandler(manager, targetKey, contextKey, -1, rootHandlers); final DefaultConfiguration parserConfiguration = handler.getParserConfiguration(); final URL value = manager.toURL(contextKey); if (value != null) { parserConfiguration.setConfigProperty(CONTENTBASE_KEY, value.toExternalForm()); } configureReader(reader, handler); reader.setContentHandler(handler); reader.setDTDHandler(handler); reader.setEntityResolver(handler.getEntityResolver()); reader.setErrorHandler(getErrorHandler()); final Iterator it = parameters.keySet().iterator(); while (it.hasNext()) { final Object o = it.next(); if (o instanceof FactoryParameterKey) { final FactoryParameterKey fpk = (FactoryParameterKey) o; handler.setHelperObject(fpk.getName(), parameters.get(fpk)); } } reader.parse(input); return finishResult(handler.getResult(), manager, new RawResourceData(targetKey), contextKey); } catch (ParserConfigurationException e) { throw new ResourceCreationException ("Unable to initialize the XML-Parser", e); } catch (SAXException e) { throw new ResourceCreationException("Unable to parse the document", e); } catch (IOException e) { throw new ResourceLoadingException("Unable to read the stream", e); } } /** * Returns the registered XmlFactoryModules as array. * * @return the modules as array. */ private XmlFactoryModule[] getModules() { return (XmlFactoryModule[]) modules.toArray(new XmlFactoryModule[modules.size()]); } /** * Creates a Resource object for the given product. By default this returns a compound-resource that holds * all the key that identify the resources used during the content production. * * @param targetKey the target key. * @param handler the root handler used for the parsing. * @param createdProduct the created product. * @return the product wrapped into a resource object. */ protected Resource createResource(final ResourceKey targetKey, final MultiplexRootElementHandler handler, final Object createdProduct, final Class createdType) { return new CompoundResource (targetKey, handler.getDependencyCollector(), createdProduct, createdType); } /** * Finishes up the result. This can be used for general clean up and post-parse initializaion of the result. * The default implementation does nothing and just returns the object itself. * * @param res the parsed resource. * @param manager the resource manager that was used to load the resource. * @param data the data object from where the resource is loaded. * @param context the context that resolves relative resource paths. * @return the parsed resource. * @throws ResourceCreationException if the post initialization fails. * @throws ResourceLoadingException if loading external resources failed with an IO error. */ protected Object finishResult(final Object res, final ResourceManager manager, final ResourceData data, final ResourceKey context) throws ResourceCreationException, ResourceLoadingException { return res; } /** * Returns the configuration that should be used to initialize this factory. * * @return the configuration for initializing the factory. */ protected abstract Configuration getConfiguration(); /** * Loads all XmlFactoryModule-implementations from the given configuration. * * @see #getConfiguration() */ public void initializeDefaults() { final String type = getFactoryType().getName(); final String prefix = ResourceFactory.CONFIG_PREFIX + type; final Configuration config = getConfiguration(); final Iterator itType = config.findPropertyKeys(prefix); while (itType.hasNext()) { final String key = (String) itType.next(); final String modClass = config.getConfigProperty(key); final Object maybeFactory = ObjectUtilities.loadAndInstantiate (modClass, AbstractXmlResourceFactory.class, XmlFactoryModule.class); if (maybeFactory instanceof XmlFactoryModule == false) { continue; } registerModule((XmlFactoryModule) maybeFactory); } } /** * Registers a factory module for being used during the parsing. If the factory module does not return a * result that matches the factory's type, the parsing will always fail. * * @param factoryModule the factory module. * @throws NullPointerException if the module given is null. */ public void registerModule(final XmlFactoryModule factoryModule) { if (factoryModule == null) { throw new NullPointerException(); } modules.add(factoryModule); } /** * Returns the XML-Error handler that should be registered with the XML parser. By default, this returns * a logger. * * @return the error handler. */ protected ErrorHandler getErrorHandler() { return new LoggingErrorHandler(); } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/LoggingErrorHandler.java0000644000175000017500000001443111365606150031307 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * A SAX-Error handler that logs all incomming errors to the given log context. * * @author Thomas Morgner */ public class LoggingErrorHandler implements ErrorHandler { private static final Log defaultLogContext = LogFactory.getLog(LoggingErrorHandler.class); /** @noinspection NonConstantLogger*/ private Log logContext; /** * Default-Constructor. Logs to a logger configured with this class name as category. */ public LoggingErrorHandler() { logContext = defaultLogContext; } /** * Creates a new LoggingErrorHandler with the given (non-null) logcontext as log-target. * * @param logContext the logger that should receive the messages. */ public LoggingErrorHandler(final Log logContext) { if (logContext == null) { throw new NullPointerException(); } this.logContext = logContext; } /** * Receive notification of a warning. *

*

SAX parsers will use this method to report conditions that are not * errors or fatal errors as defined by the XML recommendation. The default * behaviour is to take no action.

*

*

The SAX parser must continue to provide normal parsing events after * invoking this method: it should still be possible for the application to * process the document through to the end.

*

*

Filters may use this method to report other, non-XML warnings as * well.

* * @param exception The warning information encapsulated in a SAX parse * exception. * @throws org.xml.sax.SAXException Any SAX exception, possibly wrapping * another exception. * @see org.xml.sax.SAXParseException */ public void warning(final SAXParseException exception) throws SAXException { if (logContext.isDebugEnabled()) { if (exception.getMessage().startsWith("URI was not reported to parser for entity")) { // ignore that one. It is stupid! We do not use DTDs but old parsers like // the GNU thing complain about it .. return; } logContext.debug("Parser-Warning", exception); } } /** * Receive notification of a recoverable error. *

*

This corresponds to the definition of "error" in section 1.2 of the W3C * XML 1.0 Recommendation. For example, a validating parser would use this * callback to report the violation of a validity constraint. The default * behaviour is to take no action.

*

*

The SAX parser must continue to provide normal parsing events after * invoking this method: it should still be possible for the application to * process the document through to the end. If the application cannot do so, * then the parser should report a fatal error even if the XML recommendation * does not require it to do so.

*

*

Filters may use this method to report other, non-XML errors as * well.

* * @param exception The error information encapsulated in a SAX parse * exception. * @throws org.xml.sax.SAXException Any SAX exception, possibly wrapping * another exception. * @see org.xml.sax.SAXParseException */ public void error(final SAXParseException exception) throws SAXException { if (logContext.isWarnEnabled()) { if (logContext.isDebugEnabled()) { logContext.warn("Recoverable Parser-Error", exception); } else { logContext.warn("Recoverable Parser-Error:" + exception.getMessage()); } } } /** * Receive notification of a non-recoverable error. *

*

There is an apparent contradiction between the documentation for * this method and the documentation for {@link org.xml.sax.ContentHandler#endDocument}. * Until this ambiguity is resolved in a future major release, clients should * make no assumptions about whether endDocument() will or will not be invoked * when the parser has reported a fatalError() or thrown an * exception.

*

*

This corresponds to the definition of "fatal error" in section 1.2 of * the W3C XML 1.0 Recommendation. For example, a parser would use this * callback to report the violation of a well-formedness constraint.

*

*

The application must assume that the document is unusable after the * parser has invoked this method, and should continue (if at all) only for * the sake of collecting additional error messages: in fact, SAX parsers are * free to stop reporting any other events once this method has been * invoked.

* * @param exception The error information encapsulated in a SAX parse * exception. * @throws org.xml.sax.SAXException Any SAX exception, possibly wrapping * another exception. * @see org.xml.sax.SAXParseException */ public void fatalError(final SAXParseException exception) throws SAXException { if (logContext.isErrorEnabled()) { if (logContext.isDebugEnabled()) { logContext.error("Fatal Parser-Error", exception); } else { logContext.error("Fatal Parser-Error:" + exception.getMessage()); } } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/AbstractReadHandlerFactory.javalibxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/AbstractReadHandlerFactory.jav0000644000175000017500000002035011365606150032432 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import java.util.HashMap; import java.util.Iterator; import org.pentaho.reporting.libraries.base.config.Configuration; import org.pentaho.reporting.libraries.base.util.ObjectUtilities; /** * The AbstractReadHandlerFactory provides a base implementation for all * read-handler factories. A read-handler factory decouples the tag-handlers * of a SAX parser and allows to configure alternate parser configuations * at runtime, resulting in a more flexible parsing process. * * @author Thomas Morgner */ public abstract class AbstractReadHandlerFactory { /** * The TagDefinitionKey is a compund key to lookup handler implementations * using a namespace and tagname. */ private static class TagDefinitionKey { private String namespace; private String tagName; /** * Creates a new key. * * @param namespace the namespace (can be null for undefined). * @param tagName the tagname (can be null for undefined). */ private TagDefinitionKey(final String namespace, final String tagName) { this.namespace = namespace; this.tagName = tagName; } /** * Compares this key for equality with an other object. * * @param o the other object. * @return true, if this key is the same as the given object, false otherwise. */ public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final TagDefinitionKey that = (TagDefinitionKey) o; if (namespace != null ? !namespace.equals(that.namespace) : that.namespace != null) { return false; } if (tagName != null ? !tagName.equals(that.tagName) : that.tagName != null) { return false; } return true; } /** * Computes the hashcode for this key. * * @return the hashcode. */ public int hashCode() { int result = (namespace != null ? namespace.hashCode() : 0); result = 29 * result + (tagName != null ? tagName.hashCode() : 0); return result; } } private HashMap defaultDefinitions; private HashMap tagData; private String defaultNamespace; /** * A default-constructor. */ protected AbstractReadHandlerFactory() { defaultDefinitions = new HashMap(); tagData = new HashMap(); } /** * Configures this factory from the given configuration using the speoified * prefix as filter. * * @param conf the configuration. * @param prefix the key-prefix. * @noinspection ObjectAllocationInLoop as this method configures the factory. */ public void configure(final Configuration conf, final String prefix) { final HashMap knownNamespaces = new HashMap(); final String nsConfPrefix = prefix + "namespace."; final Iterator namespaces = conf.findPropertyKeys(nsConfPrefix); while (namespaces.hasNext()) { final String key = (String) namespaces.next(); final String nsPrefix = key.substring(nsConfPrefix.length()); final String nsUri = conf.getConfigProperty(key); knownNamespaces.put(nsPrefix, nsUri); } defaultNamespace = (String) knownNamespaces.get (conf.getConfigProperty(prefix + "namespace")); final String globalDefaultKey = prefix + "default"; final String globalValue = conf.getConfigProperty(globalDefaultKey); if (isValidHandler(globalValue)) { defaultDefinitions.put(null, globalValue); } else { // let the loading fail .. if (defaultDefinitions.containsKey(null) == false) { defaultDefinitions.put(null, ""); } } final String nsDefaultPrefix = prefix + "default."; final Iterator defaults = conf.findPropertyKeys(nsDefaultPrefix); while (defaults.hasNext()) { final String key = (String) defaults.next(); final String nsPrefix = key.substring(nsDefaultPrefix.length()); final String nsUri = (String) knownNamespaces.get(nsPrefix); if (nsUri == null) { continue; } final String tagData = conf.getConfigProperty(key); if (tagData == null) { continue; } if (isValidHandler(tagData)) { defaultDefinitions.put(nsUri, tagData); } else { // let the loading fail .. to indicate we want no parsing .. defaultDefinitions.put(nsUri, ""); } } final String nsTagsPrefix = prefix + "tag."; final Iterator tags = conf.findPropertyKeys(nsTagsPrefix); while (tags.hasNext()) { final String key = (String) tags.next(); final String tagDef = key.substring(nsTagsPrefix.length()); final String tagData = conf.getConfigProperty(key); if (tagData == null) { continue; } if (isValidHandler(tagData) == false) { continue; } final int delim = tagDef.indexOf('.'); if (delim == -1) { this.tagData.put(new TagDefinitionKey(null, tagDef), tagData); } else { final String nsPrefix = tagDef.substring(0, delim); final String nsUri = (String) knownNamespaces.get(nsPrefix); if (nsUri == null) { continue; } final String tagName = tagDef.substring(delim + 1); this.tagData.put(new TagDefinitionKey(nsUri, tagName), tagData); } } } /** * Checks, whether the given handler classname can be instantiated * and is in fact an object of the required target-type. * * @param className the classname that should be checked. * @return true, if the handler is valid, false otherwise. */ private boolean isValidHandler(final String className) { if (className == null) { return false; } final Object o = ObjectUtilities.loadAndInstantiate (className, getClass(), getTargetClass()); return o != null; } /** * Returns the implementation class for this read-handler factory. * * @return the implementation class. */ protected abstract Class getTargetClass(); /** * The returned handler can be null, in case no handler is registered. * * @param namespace the namespace of the xml-tag for which a handler should be returned. * @param tagname the tagname of the xml-tag. * @return the instantiated read handler, or null if there is no handler registered. */ public XmlReadHandler getHandler(String namespace, final String tagname) { if (namespace == null) { namespace = defaultNamespace; } final TagDefinitionKey key = new TagDefinitionKey(namespace, tagname); final String tagVal = (String) tagData.get(key); if (tagVal != null) { final Object o = ObjectUtilities.loadAndInstantiate (tagVal, getClass(), getTargetClass()); return (XmlReadHandler) o; } final String className = (String) defaultDefinitions.get(namespace); if (className != null) { final Object o = ObjectUtilities.loadAndInstantiate (className, getClass(), getTargetClass()); return (XmlReadHandler) o; } final String fallbackName = (String) defaultDefinitions.get(null); final Object fallbackValue = ObjectUtilities.loadAndInstantiate (fallbackName, getClass(), getTargetClass()); if (fallbackValue != null) { return (XmlReadHandler) fallbackValue; } return null; } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/DomTreeResourceFactory.java0000644000175000017500000001135711365606150032014 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2009 Pentaho Corporation. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.reporting.libraries.resourceloader.Resource; import org.pentaho.reporting.libraries.resourceloader.ResourceCreationException; import org.pentaho.reporting.libraries.resourceloader.ResourceData; import org.pentaho.reporting.libraries.resourceloader.ResourceFactory; import org.pentaho.reporting.libraries.resourceloader.ResourceKey; import org.pentaho.reporting.libraries.resourceloader.ResourceLoadingException; import org.pentaho.reporting.libraries.resourceloader.ResourceManager; import org.pentaho.reporting.libraries.resourceloader.SimpleResource; import org.w3c.dom.Document; import org.xml.sax.SAXException; /** * Todo: Document me! *

* Date: 10.08.2009 * Time: 11:23:50 * * @author Thomas Morgner. */ public class DomTreeResourceFactory implements ResourceFactory { private static class DomResource extends SimpleResource { public DomResource(final ResourceKey resourceKey, final Document document, final long version) { super(resourceKey, document, Document.class, version); } public Object getResource() { final Document resource = (Document) super.getResource(); return resource.cloneNode(true); } } private static final Log logger = LogFactory.getLog(DomTreeResourceFactory.class); /** * Creates a resource by interpreting the data given in the resource-data object. If additional datastreams need to * be parsed, the provided resource manager should be used. * * @param manager the resource manager used for all resource loading. * @param data the resource-data from where the binary data is read. * @param context the resource context used to resolve relative resource paths. * @return the parsed result, never null. * @throws org.pentaho.reporting.libraries.resourceloader.ResourceCreationException * if the resource could not be parsed due to syntaxctial or logical errors in the data. * @throws org.pentaho.reporting.libraries.resourceloader.ResourceLoadingException * if the resource could not be accessed from the physical storage. */ public Resource create(final ResourceManager manager, final ResourceData data, final ResourceKey context) throws ResourceCreationException, ResourceLoadingException { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(false); try { final DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(ParserEntityResolver.getDefaultResolver()); db.setErrorHandler(new LoggingErrorHandler()); final ResourceDataInputSource input = new ResourceDataInputSource(data, manager); return new DomResource(data.getKey(), db.parse(input), data.getVersion(manager)); } catch (ParserConfigurationException e) { throw new ResourceCreationException("Unable to initialize the XML-Parser", e); } catch (SAXException e) { throw new ResourceCreationException("Unable to parse the document: " + data.getKey(), e); } catch (IOException e) { throw new ResourceLoadingException("Unable to read the stream from document: " + data.getKey(), e); } } /** * Initializes the resource factory. This usually loads all system resources from the environment and maybe sets up * and initializes any factories needed during the parsing. */ public void initializeDefaults() { } /** * Returns the expected result type. * * @return the result type. */ public Class getFactoryType() { return Document.class; } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/PropertiesReadHandler.java0000644000175000017500000000674311365606150031646 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import java.util.ArrayList; import java.util.Properties; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A read handler that creates property-structures (name-value-pairs) and returns the properties as java.util.Properties * collection. * * @author Thomas Morgner */ public class PropertiesReadHandler extends AbstractXmlReadHandler { private ArrayList propertyHandlers; private String propertyTagName; private Properties result; /** * Creates a properties read-handler using "property" as child-tagname. */ public PropertiesReadHandler() { this("property"); } /** * Creates a properties read-handler using the specified propertyTagName as child-tagname. * * @param propertyTagName the tag name for the child elements that define the properties. */ public PropertiesReadHandler(final String propertyTagName) { if (propertyTagName == null) { throw new NullPointerException(); } this.propertyHandlers = new ArrayList(); this.propertyTagName = propertyTagName; } /** * Returns the handler for a child element. * * @param tagName the tag name. * @param atts the attributes. * @return the handler or null, if the tagname is invalid. * @throws SAXException if there is a parsing error. */ protected XmlReadHandler getHandlerForChild(final String uri, final String tagName, final Attributes atts) throws SAXException { if (isSameNamespace(uri) == false) { return null; } if (tagName.equals(propertyTagName)) { final PropertyReadHandler prh = new PropertyReadHandler(); propertyHandlers.add(prh); return prh; } return null; } /** * Done parsing. * * @throws SAXException if there is a parsing error. */ protected void doneParsing() throws SAXException { result = new Properties(); for (int i = 0; i < propertyHandlers.size(); i++) { final PropertyReadHandler handler = (PropertyReadHandler) propertyHandlers.get(i); result.setProperty(handler.getName(), handler.getResult()); } } /** * Returns the resulting properties collection, never null. * * @return the properties. */ public Properties getResult() { return result; } /** * Returns the resulting properties collection, never null. * * @return the properties. * @throws SAXException if there is a parsing error. */ public Object getObject() throws SAXException { return result; } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/ParserEntityResolver.java0000644000175000017500000001523111365606150031563 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; /** * Resolves the JFreeReport DTD specification and routes the parser to a local copy. * * @author Thomas Morgner */ public final class ParserEntityResolver implements EntityResolver { private static final Log logger = LogFactory.getLog(ParserEntityResolver.class); /** * The hashtable for the known entities (deprecated DTDs). */ private final HashMap deprecatedDTDs; /** * The hashtable for the known entities. */ private final HashMap dtds; /** * The singleton instance of this entity resolver. */ private static ParserEntityResolver singleton; /** * Creates a new, uninitialized ParserEntityResolver. */ private ParserEntityResolver() { dtds = new HashMap(); deprecatedDTDs = new HashMap(); } /** * Defines a DTD used to validate the report definition. Your XMLParser must be a * validating parser for this feature to work. * * @param publicID the public ID. * @param location the URL. * @return A boolean. */ public boolean setDTDLocation(final String publicID, final URL location) { if (isValid(location)) { this.dtds.put(publicID, location); return true; } else { logger.warn("Validate location failed for " + publicID + " location: " + location); return false; } } /** * Defines a DTD used to validate the report definition. Your XMLParser must be a * validating parser for this feature to work. * * @param systemId the system ID for the DTD. * @param publicID the public ID. * @param location the URL. * @return A boolean. */ public boolean setDTDLocation(final String publicID, final String systemId, final URL location) { if (isValid(location)) { this.dtds.put(publicID, location); this.dtds.put(systemId, location); return true; } else { logger.warn("Validate location failed for " + publicID + " location: " + location); return false; } } /** * Sets the location of the DTD. This is used for validating XML parsers to validate the * structure of the report definition. * * @param publicID the id. * @return the URL for the DTD. */ public URL getDTDLocation(final String publicID) { return (URL) dtds.get(publicID); } /** * Checks whether the speficied URL is readable. * * @param reportDtd the url pointing to the local DTD copy. * @return true, if the URL can be read, false otherwise. */ private boolean isValid(final URL reportDtd) { if (reportDtd == null) { return false; } try { final InputStream uc = reportDtd.openStream(); uc.close(); return true; } catch (IOException ioe) { return false; } } /** * Allow the application to resolve external entities. *

* Resolves the DTD definition to point to a local copy, if the specified public ID is * known to this resolver. * * @param publicId the public ID. * @param systemId the system ID. * @return The input source. */ public InputSource resolveEntity(final String publicId, final String systemId) { try { // cannot validate without public id ... if (publicId == null) { //Log.debug ("No PUBLIC ID, cannot continue"); if (systemId != null) { final URL location = getDTDLocation(systemId); if (location != null) { final InputSource inputSource = new InputSource(location.openStream()); inputSource.setSystemId(systemId); return inputSource; } } return null; } final URL location = getDTDLocation(publicId); if (location != null) { final InputSource inputSource = new InputSource(location.openStream()); inputSource.setSystemId(systemId); inputSource.setPublicId(publicId); return inputSource; } final String message = getDeprecatedDTDMessage(publicId); if (message != null) { logger.info(message); } else { logger.info("A public ID was given for the document, but it was unknown or invalid."); } return null; } catch (IOException ioe) { logger.warn("Unable to open specified DTD", ioe); } return null; } /** * Returns a default resolver, which is initialized to redirect the parser to a local * copy of the JFreeReport DTDs. * * @return the default entity resolver. */ public static synchronized ParserEntityResolver getDefaultResolver() { if (singleton == null) { singleton = new ParserEntityResolver(); } return singleton; } /** * Defines that the given public ID should be deprecated and provides a log-message along with the deprecation. * * @param publicID the public id that should be considered deprecated. * @param message the message to present to the user to warn them about their use of deprecated DTDs. */ public void setDeprecatedDTDMessage(final String publicID, final String message) { deprecatedDTDs.put(publicID, message); } /** * Returns deprecation message for the given public ID. * * @param publicID the public id that should be considered deprecated. * @return the deprecation message or null if the ID is not considered deprecated. */ public String getDeprecatedDTDMessage(final String publicID) { return (String) deprecatedDTDs.get(publicID); } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/XmlReadHandler.java0000644000175000017500000000511211365606150030237 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A handler for reading an XML element. * * @author Thomas Morgner */ public interface XmlReadHandler { /** * This method is called at the start of an element. * * @param uri the namespace uri. * @param tagName the tag name. * @param attrs the attributes. * @throws SAXException if there is a parsing error. */ public void startElement(String uri, String tagName, Attributes attrs) throws SAXException; /** * This method is called to process the character data between element tags. * * @param ch the character buffer. * @param start the start index. * @param length the length. * @throws SAXException if there is a parsing error. */ public void characters(char[] ch, int start, int length) throws SAXException; /** * This method is called at the end of an element. * * @param uri the namespace uri. * @param tagName the tag name. * @throws SAXException if there is a parsing error. */ public void endElement(String uri, String tagName) throws SAXException; /** * Returns the object for this element or null, if this element does * not create an object. * * @return the object. * @throws SAXException if an parser error occured. */ public Object getObject() throws SAXException; /** * Initialise. * * @param rootHandler the root handler. * @param uri the namespace uri. * @param tagName the tag name. * @throws SAXException if an parser-error occured. */ public void init(RootXmlReadHandler rootHandler, String uri, String tagName) throws SAXException; } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/XmlDocumentInfo.java0000644000175000017500000000377411365606150030474 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import org.xml.sax.Attributes; /** * The XmlDocumentInfo class collects basic information about the document * that should be parsed. * * @author Thomas Morgner */ public interface XmlDocumentInfo { /** * Returns the tag name of the root-level element. * * @return the root-tag-name. */ public String getRootElement(); /** * Returns the namespace URI for the root-element of the document. * * @return the namespace of the root-element. */ public String getRootElementNameSpace(); public Attributes getRootElementAttributes(); /** * Returns the Public-ID of the Document's DTD (if there's any). * * @return the public id. */ public String getPublicDTDId(); /** * Returns the System-ID of the document's DTD. * * @return the system-id. */ public String getSystemDTDId(); /** * Returns the default-namespace declared on the root-element. It is * not guaranteed that this information is filled until a XmlFactoryModule * has been selected. * * @return the default-namespace. */ public String getDefaultNameSpace(); } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/StringReadHandler.java0000644000175000017500000000506611365606150030755 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A XmlReadHandler that reads character-data for the given element. * * @author Thomas Morgner */ public class StringReadHandler extends AbstractXmlReadHandler { /** * A buffer containing the characters read so far. */ private StringBuffer buffer; /** * The string under construction. */ private String result; /** * Creates a new handler. */ public StringReadHandler() { super(); } /** * Starts parsing. * * @param attrs the attributes. * @throws SAXException if there is a parsing error. */ protected void startParsing(final Attributes attrs) throws SAXException { this.buffer = new StringBuffer(); } /** * This method is called to process the character data between element tags. * * @param ch the character buffer. * @param start the start index. * @param length the length. * @throws SAXException if there is a parsing error. */ public void characters(final char[] ch, final int start, final int length) throws SAXException { this.buffer.append(ch, start, length); } /** * Done parsing. * * @throws SAXException if there is a parsing error. */ protected void doneParsing() throws SAXException { this.result = this.buffer.toString(); this.buffer = null; } /** * Returns the result as string. * * @return the parse-result as string. */ public String getResult() { return result; } /** * Returns the object for this element. * * @return the object. */ public Object getObject() { return this.result; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/MultiplexRootElementHandler.javalibxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/MultiplexRootElementHandler.ja0000644000175000017500000002222611365606150032522 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import java.io.IOException; import org.pentaho.reporting.libraries.resourceloader.ResourceKey; import org.pentaho.reporting.libraries.resourceloader.ResourceManager; import org.xml.sax.Attributes; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * A root-handler that intercepts the first call to startElement to select a XmlReadHandler based on the * XmlDocumentInfo provided by the parser. * * @author Thomas Morgner */ public class MultiplexRootElementHandler extends RootXmlReadHandler { /** * A entity resolver that collects information about the DTD used in the document while the underlying parser * tries to resolve the DTD into a local InputSource. */ private static class RootEntityResolver implements EntityResolver { private ParserEntityResolver entityResolver; private String publicId; private String systemId; /** * DefaultConstructor. */ private RootEntityResolver() { entityResolver = ParserEntityResolver.getDefaultResolver(); } /** * Collects the public and System-ID from the call for later use in the XmlDocumentInfo and then forwards * the resolver to the default resolver. * * @param publicId The public identifier of the external entity * being referenced, or null if none was supplied. * @param systemId The system identifier of the external entity * being referenced. * @return An InputSource object describing the new input source, * or null to request that the parser open a regular * URI connection to the system identifier. * @exception org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * @exception java.io.IOException A Java-specific IO exception, * possibly the result of creating a new InputStream * or Reader for the InputSource. * @see org.xml.sax.InputSource */ public InputSource resolveEntity(final String publicId, final String systemId) throws SAXException, IOException { this.publicId = publicId; this.systemId = systemId; return entityResolver.resolveEntity(publicId, systemId); } /** * Returns the public ID of the document or null, if the document does not use DTDs. * * @return the public ID of the documents DTD. */ public String getPublicId() { return publicId; } /** * Returns the system ID of the document or null, if the document does not use DTDs. * * @return the system ID of the documents DTD. */ public String getSystemId() { return systemId; } /** * Returns the entity resolver used by this class. * * @return the entity resolver. */ public ParserEntityResolver getEntityResolver() { return entityResolver; } } private XmlFactoryModule[] rootHandlers; private RootEntityResolver entityResolver; private boolean xmlnsUrisNotAvailable; private XmlFactoryModule selectedRootHandler; /** * Creates a new MultiplexRootElementHandler for the given root handler selection. * * @param manager the resource manager that loaded this xml-file. * @param source the source-key that idenfies from where the file was loaded. * @param context the key that should be used to resolve relative paths. * @param version the versioning information for the root-file. * @param rootHandlers the roothandlers, never null. */ public MultiplexRootElementHandler (final ResourceManager manager, final ResourceKey source, final ResourceKey context, final long version, final XmlFactoryModule[] rootHandlers) { super(manager, source, context, version); this.entityResolver = new RootEntityResolver(); this.rootHandlers = (XmlFactoryModule[]) rootHandlers.clone(); } /** * Returns, whether the parser resolves namespace-URIs. * * @return true, if the parser will *NOT* resolve namespaces, false otherwise. */ public boolean isXmlnsUrisNotAvailable() { return xmlnsUrisNotAvailable; } /** * Sets a hint that the parser will not be able to return URIs for XML-Namespaces. You should not see this * nowadays, as all the common JAXP-parser implementations seem to work fine with namespaces. * * @param xmlnsUrisNotAvailable a flag indicating that the XML parser has troubles resolving namespaces. */ public void setXmlnsUrisNotAvailable(final boolean xmlnsUrisNotAvailable) { this.xmlnsUrisNotAvailable = xmlnsUrisNotAvailable; } /** * Returns the entity resolver used in this handler. * * @return the entity resolver. */ public EntityResolver getEntityResolver() { return entityResolver; } /** * Returns the parent entity resolver used in the element handler. This returns the modifiable entity-resolver * backend. * * @return the entity resolver. */ public ParserEntityResolver getParserEntityResolver() { return entityResolver.getEntityResolver(); } /** * Returns all known roothandlers. * * @return the known root handlers. */ protected XmlFactoryModule[] getRootHandlers() { return (XmlFactoryModule[]) rootHandlers.clone(); } /** * Starts processing an element. * * @param originalUri the URI. * @param localName the local name. * @param qName the qName. * @param attributes the attributes. * @throws SAXException if there is a parsing problem. */ protected void interceptFirstStartElement(final String originalUri, final String localName, final String qName, Attributes attributes) throws SAXException { // build the document info and select the root handler that will // deal with the document content. final DefaultXmlDocumentInfo documentInfo = new DefaultXmlDocumentInfo(); documentInfo.setPublicDTDId(entityResolver.getPublicId()); documentInfo.setSystemDTDId(entityResolver.getSystemId()); documentInfo.setRootElement(localName); documentInfo.setRootElementNameSpace(originalUri); documentInfo.setRootElementAttributes(attributes); final String nsuri = attributes.getValue("xmlns"); if (nsuri != null) { documentInfo.setDefaultNameSpace(nsuri); } else { documentInfo.setDefaultNameSpace(""); } // ok, now find the best root handler and start parsing ... XmlFactoryModule bestRootHandler = null; int bestRootHandlerWeight = -1; for (int i = 0; i < rootHandlers.length; i++) { final XmlFactoryModule rootHandler = rootHandlers[i]; final int weight = rootHandler.getDocumentSupport(documentInfo); if (weight > bestRootHandlerWeight) { bestRootHandler = rootHandler; bestRootHandlerWeight = weight; } } if (bestRootHandlerWeight < 0 || bestRootHandler == null) { throw new NoRootHandlerException("No suitable root handler known for this document: " + documentInfo); } final XmlReadHandler readHandler = bestRootHandler.createReadHandler(documentInfo); if (readHandler == null) { throw new NoRootHandlerException("Unable to create the root handler. " + bestRootHandler); } this.selectedRootHandler = bestRootHandler; String defaultNamespace = documentInfo.getDefaultNameSpace(); if (defaultNamespace == null || "".equals(defaultNamespace)) { // Now correct the namespace .. defaultNamespace = bestRootHandler.getDefaultNamespace(documentInfo); if (defaultNamespace != null && "".equals(defaultNamespace) == false) { documentInfo.setRootElementNameSpace(defaultNamespace); } } pushDefaultNamespace(defaultNamespace); final String uri; if ((originalUri == null || "".equals(originalUri)) && defaultNamespace != null) { uri = defaultNamespace; } else { uri = originalUri; } attributes = new FixNamespaceUriAttributes(uri, attributes); installRootHandler(readHandler, uri, localName, wrapAttributes(attributes)); } public XmlFactoryModule getSelectedRootHandler() { return selectedRootHandler; } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/RootXmlReadHandler.java0000644000175000017500000004073611365606150031116 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import java.util.HashMap; import org.pentaho.reporting.libraries.resourceloader.DependencyCollector; import org.pentaho.reporting.libraries.resourceloader.ResourceKey; import org.pentaho.reporting.libraries.resourceloader.ResourceManager; import org.pentaho.reporting.libraries.base.config.DefaultConfiguration; import org.pentaho.reporting.libraries.base.util.FastStack; import org.pentaho.reporting.libraries.base.util.DebugLog; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * A base root SAX handler. * * @author Peter Becker * @author Thomas Morgner */ public class RootXmlReadHandler extends DefaultHandler { /** * Storage for the parser configuration. */ private DefaultConfiguration parserConfiguration; /** * The DocumentLocator can be used to resolve the current parse position. */ private Locator documentLocator; /** * The current handlers. */ private FastStack currentHandlers; /** * The list of parent handlers. */ private FastStack outerScopes; /** * The root handler. */ private XmlReadHandler rootHandler; /** * The object registry. */ private HashMap objectRegistry; /** * A flag indicating whether this handler has initialized the root-element. */ private boolean rootHandlerInitialized; /** * The current comment handler used to receive xml comments. */ private CommentHandler commentHandler; private DependencyCollector dependencyCollector; private ResourceKey source; private ResourceKey context; private ResourceManager manager; private FastStack namespaces; private boolean firstCall; /** * Creates a new root-handler using the given versioning information and * resource-manager. * * @param manager the resource manager that loaded this xml-file. * @param source the source-key that idenfies from where the file was loaded. * @param version the versioning information for the root-file. */ public RootXmlReadHandler(final ResourceManager manager, final ResourceKey source, final long version) { this(manager, source, source, version); } /** * Creates a new root-handler using the given versioning information and * resource-manager. * * @param manager the resource manager that loaded this xml-file. * @param source the source-key that idenfies from where the file was loaded. * @param context the key that should be used to resolve relative paths. * @param version the versioning information for the root-file. */ public RootXmlReadHandler(final ResourceManager manager, final ResourceKey source, final ResourceKey context, final long version) { if (manager == null) { throw new NullPointerException(); } if (source == null) { throw new NullPointerException(); } this.firstCall = true; this.manager = manager; this.source = source; this.context = context; this.dependencyCollector = new DependencyCollector(source, version); this.objectRegistry = new HashMap(); this.parserConfiguration = new DefaultConfiguration(); this.commentHandler = new CommentHandler(); this.namespaces = new FastStack(); } /** * Returns the context key. This key may specity a base context for loading * resources. (It behaves like the 'base-url' setting of HTML and allows to * reference external resources as relative paths without being bound to the * original location of the xml file.) * * @return the context. */ public ResourceKey getContext() { return context; } /** * Returns the resource-manager that is used to load external resources. * * @return the resource-manager. */ public ResourceManager getResourceManager() { return manager; } /** * Checks, whether this is the first call to the handler. * * @return true, if this is the first call, false otherwise. */ public boolean isFirstCall() { return firstCall; } /** * Returns the source key. This key points to the file or stream that is * currently parsed. * * @return the source key. */ public ResourceKey getSource() { return source; } /** * Returns the current dependency collector for this parse-operation. * The Collector allows to check compound-keys for changes. * * @return the dependency collector. */ public DependencyCollector getDependencyCollector() { return dependencyCollector; } /** * Returns the comment handler that is used to collect comments. * * @return the comment handler. */ public CommentHandler getCommentHandler() { return this.commentHandler; } /** * Returns the parser-configuration. This can be use to configure * the parsing process. * * @return the parser's configuration. */ public DefaultConfiguration getParserConfiguration() { return parserConfiguration; } /** * Receive an object for locating the origin of SAX document events. *

* The documentLocator allows the application to determine the end position of * any document-related event, even if the parser is not reporting an error. * Typically, the application will use this information for reporting its own * errors (such as character content that does not match an application's * business rules). The information returned by the documentLocator is * probably not sufficient for use with a search engine. * * @param locator the documentLocator. */ public void setDocumentLocator(final Locator locator) { this.documentLocator = locator; } /** * Returns the current documentLocator. * * @return the documentLocator. */ public Locator getDocumentLocator() { return this.documentLocator; } /** * Adds an object to the registry. * * @param key the key. * @param value the object. */ public void setHelperObject(final String key, final Object value) { if (value == null) { this.objectRegistry.remove(key); } else { this.objectRegistry.put(key, value); } } /** * Returns an object from the registry. * * @param key the key. * @return The object. */ public Object getHelperObject(final String key) { return this.objectRegistry.get(key); } /** * Returns the array of all currently registered helper-objects. Helper * objects are used as simple communication process between the various * handler implementations. * * @return the helper object names. */ public String[] getHelperObjectNames() { return (String[]) this.objectRegistry.keySet().toArray (new String[objectRegistry.size()]); } /** * Sets the root SAX handler. * * @param handler the SAX handler. */ protected void setRootHandler(final XmlReadHandler handler) { if (handler == null) { throw new NullPointerException(); } this.rootHandler = handler; this.rootHandlerInitialized = false; } /** * Returns the root SAX handler. * * @return the root SAX handler. */ protected XmlReadHandler getRootHandler() { return this.rootHandler; } /** * Start a new handler stack and delegate to another handler. * * @param handler the handler. * @param uri the namespace uri of the current tag. * @param tagName the tag name. * @param attrs the attributes. * @throws SAXException if there is a problem with the parser. */ public void recurse(final XmlReadHandler handler, final String uri, final String tagName, final Attributes attrs) throws SAXException { if (handler == null) { throw new NullPointerException(); } this.outerScopes.push(this.currentHandlers); this.currentHandlers = new FastStack(); this.currentHandlers.push(handler); handler.startElement(uri, tagName, attrs); } /** * Delegate to another handler. * * @param handler the new handler. * @param tagName the tag name. * @param uri the namespace uri of the current tag. * @param attrs the attributes. * @throws SAXException if there is a problem with the parser. */ public void delegate(final XmlReadHandler handler, final String uri, final String tagName, final Attributes attrs) throws SAXException { if (handler == null) { throw new NullPointerException(); } this.currentHandlers.push(handler); handler.init(this, uri, tagName); handler.startElement(uri, tagName, attrs); } /** * Hand control back to the previous handler. * * @param tagName the tagname. * @param uri the namespace uri of the current tag. * @throws SAXException if there is a problem with the parser. */ public void unwind(final String uri, final String tagName) throws SAXException { // remove current handler from stack .. this.currentHandlers.pop(); if (this.currentHandlers.isEmpty() && !this.outerScopes.isEmpty()) { // if empty, but "recurse" had been called, then restore the old handler stack .. // but do not end the recursed element .. this.currentHandlers = (FastStack) this.outerScopes.pop(); } else if (!this.currentHandlers.isEmpty()) { // if there are some handlers open, close them too (these handlers must be delegates).. getCurrentHandler().endElement(uri, tagName); } } /** * Returns the current handler. * * @return The current handler. */ protected XmlReadHandler getCurrentHandler() { return (XmlReadHandler) this.currentHandlers.peek(); } /** * Starts processing a document. * * @throws SAXException not in this implementation. */ public void startDocument() throws SAXException { this.outerScopes = new FastStack(); this.currentHandlers = new FastStack(); if (rootHandler != null) { // When dealing with the multiplexing beast, we cant define a // root handler unless we've seen the first element and all its // namespace declarations ... this.currentHandlers.push(this.rootHandler); } } /** * Starts processing an element. * * @param originalUri the URI. * @param localName the local name. * @param qName the qName. * @param attributes the attributes. * @throws SAXException if there is a parsing problem. */ public final void startElement(final String originalUri, final String localName, final String qName, final Attributes attributes) throws SAXException { // Check the default-namespace .. if (firstCall) { firstCall = false; interceptFirstStartElement(originalUri, localName, qName, attributes); return; } final String defaultNamespace; final String nsuri = attributes.getValue("xmlns"); if (nsuri != null) { defaultNamespace = nsuri; } else if (namespaces.isEmpty()) { defaultNamespace = ""; } else { defaultNamespace = (String) namespaces.peek(); } pushDefaultNamespace(defaultNamespace); final String uri; if ((originalUri == null || "".equals(originalUri)) && defaultNamespace != null) { uri = defaultNamespace; } else { uri = originalUri; } if (rootHandlerInitialized == false) { rootHandler.init(this, uri, localName); rootHandlerInitialized = true; } final XmlReadHandler currentHandler = getCurrentHandler(); currentHandler.startElement(uri, localName, wrapAttributes(new FixNamespaceUriAttributes(uri, attributes))); } protected Attributes wrapAttributes(final Attributes attributes) { return attributes; } /** * A helper call that allows to override the first call to the startElememt * method. This allows the implementation of an multiplexing parser, which * requires the information from the root-level elements. * * @param uri the namespace uri of the current tag. * @param localName the unqualified tag-name. * @param qName the qualified tag-name. * @param attributes the attributes of the current element. * @throws SAXException if something goes wrong. */ protected void interceptFirstStartElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { startElement(uri, localName, qName, attributes); } /** * Updates the current default namespace. * * @param nsuri the uri of the current namespace. */ protected final void pushDefaultNamespace(final String nsuri) { namespaces.push(nsuri); } /** * Sets and configures the root handle for the given root-level element. * * @param handler the read handler for the root element. * @param uri the uri of the root elements namespace. * @param localName the local tagname of the root element. * @param attributes the attributes of the root element. * @throws SAXException if something goes wrong. */ protected void installRootHandler(final XmlReadHandler handler, final String uri, final String localName, final Attributes attributes) throws SAXException { if (handler == null) { throw new NullPointerException(); } this.rootHandler = handler; this.rootHandler.init(this, uri, localName); this.currentHandlers.push(handler); this.rootHandlerInitialized = true; this.rootHandler.startElement(uri, localName, attributes); } /** * Process character data. * * @param ch the character buffer. * @param start the start index. * @param length the length of the character data. * @throws SAXException if there is a parsing error. */ public void characters(final char[] ch, final int start, final int length) throws SAXException { try { getCurrentHandler().characters(ch, start, length); } catch (SAXException se) { throw se; } catch (Exception e) { throw new ParseException ("Failed at handling character data", e, getDocumentLocator()); } } /** * Finish processing an element. * * @param originalUri the URI. * @param localName the local name. * @param qName the qName. * @throws SAXException if there is a parsing error. */ public final void endElement(final String originalUri, final String localName, final String qName) throws SAXException { final String defaultNamespace = (String) namespaces.pop(); final String uri; if ((originalUri == null || "".equals(originalUri)) && defaultNamespace != null) { uri = defaultNamespace; } else { uri = originalUri; } final XmlReadHandler currentHandler = getCurrentHandler(); currentHandler.endElement(uri, localName); } /** * Tries to return the parse-result of the selected root-handler. * * @return the parse-result. * @throws SAXException if an error occurs. */ public Object getResult() throws SAXException { if (this.rootHandler != null) { return this.rootHandler.getObject(); } return null; } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/NoRootHandlerException.java0000644000175000017500000000513411365606150032006 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import org.xml.sax.Locator; /** * Todo: Document Me * * @author Thomas Morgner */ public class NoRootHandlerException extends ParseException { /** * Creates a new ParseException with the given message. * * @param message the message */ public NoRootHandlerException(final String message) { super(message); } /** * Creates a new ParseException with the given root exception. * * @param e the exception */ public NoRootHandlerException(final Exception e) { super(e); } /** * Creates a new ParseException with the given message and root exception. * * @param message the message * @param e the exception */ public NoRootHandlerException(final String message, final Exception e) { super(message, e); } /** * Creates a new ParseException with the given message and the locator. * * @param message the message * @param locator the locator of the parser */ public NoRootHandlerException(final String message, final Locator locator) { super(message, locator); } /** * Creates a new ParseException with the given root exception and the * locator. * * @param e the exception * @param locator the locator of the parser */ public NoRootHandlerException(final Exception e, final Locator locator) { super(e, locator); } /** * Creates a new ParseException with the given message, root exception and * the locator. * * @param message the message * @param e the exception * @param locator the locator of the parser */ public NoRootHandlerException(final String message, final Exception e, final Locator locator) { super(message, e, locator); } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/Base64.java0000644000175000017500000002404511365606150026437 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; /** * Provides encoding of raw bytes to base64-encoded characters, and decoding of * base64 characters to raw bytes. date: 06 August 1998 modified: 14 February * 2000 modified: 22 September 2000 * * @author Kevin Kelley (kelley@ruralnet.net) * @version 1.3 */ public class Base64 { /** * Private constructor prevents object creation. */ private Base64() { } /** * returns an array of base64-encoded characters to represent the passed * data array. * * @param data the array of bytes to encode * @return base64-coded character array. */ public static char[] encode(final byte[] data) { final char[] out = new char[((data.length + 2) / 3) * 4]; // // 3 bytes encode to 4 chars. Output is always an even // multiple of 4 characters. // for (int i = 0, index = 0; i < data.length; i += 3, index += 4) { int val = (0xFF & data[i]); val <<= 8; boolean trip = false; if ((i + 1) < data.length) { val |= (0xFF & data[i + 1]); trip = true; } val <<= 8; boolean quad = false; if ((i + 2) < data.length) { val |= (0xFF & data[i + 2]); quad = true; } out[index + 3] = Base64.ALPHABET[(quad ? (val & 0x3F) : 64)]; val >>= 6; out[index + 2] = Base64.ALPHABET[(trip ? (val & 0x3F) : 64)]; val >>= 6; out[index + 1] = Base64.ALPHABET[val & 0x3F]; val >>= 6; out[index] = Base64.ALPHABET[val & 0x3F]; } return out; } /** * Decodes a BASE-64 encoded stream to recover the original data. White * space before and after will be trimmed away, but no other manipulation of * the input will be performed. *

* As of version 1.2 this method will properly handle input containing junk * characters (newlines and the like) rather than throwing an error. It does * this by pre-parsing the input and generating from that a count of VALID * input characters. * * @param data the character data. * @return The decoded data. */ public static byte[] decode(final char[] data) { // as our input could contain non-BASE64 data (newlines, // whitespace of any sort, whatever) we must first adjust // our count of USABLE data so that... // (a) we don't misallocate the output array, and // (b) think that we miscalculated our data length // just because of extraneous throw-away junk int tempLen = data.length; for (int ix = 0; ix < data.length; ix++) { if ((data[ix] > 255) || Base64.CODES[data[ix]] < 0) { --tempLen; // ignore non-valid chars and padding } } // calculate required length: // -- 3 bytes for every 4 valid base64 chars // -- plus 2 bytes if there are 3 extra base64 chars, // or plus 1 byte if there are 2 extra. int len = (tempLen / 4) * 3; if ((tempLen % 4) == 3) { len += 2; } if ((tempLen % 4) == 2) { len += 1; } final byte[] out = new byte[len]; int shift = 0; // # of excess bits stored in accum int accum = 0; // excess bits int index = 0; // we now go through the entire array (NOT using the 'tempLen' value) for (int ix = 0; ix < data.length; ix++) { final int value = (data[ix] > 255) ? -1 : Base64.CODES[data[ix]]; if (value >= 0) { // skip over non-code accum <<= 6; // bits shift up by 6 each time thru shift += 6; // loop, with new bits being put in accum |= value; // at the bottom. if (shift >= 8) { // whenever there are 8 or more shifted in, shift -= 8; // write them out (from the top, leaving any out[index] = // excess at the bottom for next iteration. (byte) ((accum >> shift) & 0xff); index += 1; } } // we will also have skipped processing a padding null byte ('=') here; // these are used ONLY for padding to an even length and do not legally // occur as encoded data. for this reason we can ignore the fact that // no index++ operation occurs in that special case: the out[] array is // initialized to all-zero bytes to start with and that works to our // advantage in this combination. } // if there is STILL something wrong we just have to throw up now! if (index != out.length) { throw new Error("Miscalculated data length (wrote " + index + " instead of " + out.length + ')'); } return out; } // // code characters for values 0..63 // private static final char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray(); // // lookup table for converting base64 characters to value in range 0..63 // private static final byte[] CODES = new byte[256]; static { for (int i = 0; i < 256; i++) { Base64.CODES[i] = -1; } for (int i = 'A'; i <= 'Z'; i++) { Base64.CODES[i] = (byte) (i - 'A'); } for (int i = 'a'; i <= 'z'; i++) { Base64.CODES[i] = (byte) (26 + i - 'a'); } for (int i = '0'; i <= '9'; i++) { Base64.CODES[i] = (byte) (52 + i - '0'); } Base64.CODES['+'] = 62; Base64.CODES['/'] = 63; } // // // /////////////////////////////////////////////////// // // remainder (main method and helper functions) is // // for testing purposes only, feel free to clip it. // /////////////////////////////////////////////////// // // /** // * Entry point. // * // * @param args the command line arguments. // */ // public static void main(final String[] args) { // boolean decode = false; // // if (args.length == 0) { // System.out.println("usage: java Base64 [-d[ecode]] filename"); // System.exit(0); // } // for (int i = 0; i < args.length; i++) { // if ("-decode".equalsIgnoreCase(args[i])) { // decode = true; // } // else if ("-d".equalsIgnoreCase(args[i])) { // decode = true; // } // } // // final String filename = args[args.length - 1]; // final File file = new File(filename); // if (!file.exists()) { // System.out.println("Error: file '" + filename + "' doesn't exist!"); // System.exit(0); // } // // if (decode) { // final char[] encoded = org.pentaho.reporting.libraries.xmls.parser.Base64.readChars(file); // final byte[] decoded = org.pentaho.reporting.libraries.xmls.parser.Base64.decode(encoded); // org.pentaho.reporting.libraries.xmls.parser.Base64.writeBytes(file, decoded); // } // else { // final byte[] decoded = org.pentaho.reporting.libraries.xmls.parser.Base64.readBytes(file); // final char[] encoded = org.pentaho.reporting.libraries.xmls.parser.Base64.encode(decoded); // org.pentaho.reporting.libraries.xmls.parser.Base64.writeChars(file, encoded); // } // } // // private static byte[] readBytes(final File file) { // final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // try { // final InputStream fis = new FileInputStream(file); // final InputStream is = new BufferedInputStream(fis); // // int count; // final byte[] buf = new byte[16384]; // while ((count = is.read(buf)) != -1) { // if (count > 0) { // baos.write(buf, 0, count); // } // } // is.close(); // } // catch (Exception e) { // e.printStackTrace(); // } // // return baos.toByteArray(); // } // // private static char[] readChars(final File file) { // final CharArrayWriter caw = new CharArrayWriter(); // try { // final Reader fr = new FileReader(file); // final Reader in = new BufferedReader(fr); // int count; // final char[] buf = new char[16384]; // while ((count = in.read(buf)) != -1) { // if (count > 0) { // caw.write(buf, 0, count); // } // } // in.close(); // } // catch (Exception e) { // e.printStackTrace(); // } // // return caw.toCharArray(); // } // // private static void writeBytes(final File file, final byte[] data) { // try { // final OutputStream fos = new FileOutputStream(file); // final OutputStream os = new BufferedOutputStream(fos); // os.write(data); // os.close(); // } // catch (Exception e) { // e.printStackTrace(); // } // } // // private static void writeChars(final File file, final char[] data) { // try { // final Writer fos = new FileWriter(file); // final Writer os = new BufferedWriter(fos); // os.write(data); // os.close(); // } // catch (Exception e) { // e.printStackTrace(); // } // } // /////////////////////////////////////////////////// // // end of test code. // /////////////////////////////////////////////////// // } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/ParseException.java0000644000175000017500000001370211365606150030342 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import java.io.PrintStream; import java.io.PrintWriter; import org.xml.sax.Locator; import org.xml.sax.SAXException; /** * A parse exception. This does the same as the SAXParseException, but it * also prints the parent exception. * * @author Thomas Morgner */ public class ParseException extends SAXException { /** * The line, where the error occured. */ private int line; /** * The column, where the error occured. */ private int column; private boolean noOwnMessage; private static final long serialVersionUID = 1188118105409903580L; /** * Creates a new ParseException with the given message. * * @param message the message */ public ParseException(final String message) { super(message); fillLocation(null); noOwnMessage = (message == null); } /** * Creates a new ParseException with the given root exception. * * @param e the exception */ public ParseException(final Exception e) { super(e); fillLocation(null); noOwnMessage = true; } /** * Creates a new ParseException with the given message and root exception. * * @param message the message * @param e the exception */ public ParseException(final String message, final Exception e) { super(message, e); fillLocation(null); noOwnMessage = (message == null); } /** * Creates a new ParseException with the given message and the locator. * * @param message the message * @param locator the locator of the parser */ public ParseException(final String message, final Locator locator) { super(message); fillLocation(locator); noOwnMessage = (message == null); } /** * Creates a new ParseException with the given root exception and the * locator. * * @param e the exception * @param locator the locator of the parser */ public ParseException(final Exception e, final Locator locator) { super(e); fillLocation(locator); noOwnMessage = true; } /** * Creates a new ParseException with the given message, root exception and * the locator. * * @param message the message * @param e the exception * @param locator the locator of the parser */ public ParseException(final String message, final Exception e, final Locator locator) { super(message, e); fillLocation(locator); noOwnMessage = (message == null); } /** * Modifies the message to give more detailed location information. * * @return the modified exception message. */ public String getMessage() { if (noOwnMessage) { final Exception parentEx = getException(); if (parentEx instanceof ParseException) { return parentEx.getMessage(); } else { final StringBuffer message = new StringBuffer (String.valueOf(parentEx.getMessage())); message.append(" [Location: Line="); message.append(this.line); message.append(" Column="); message.append(this.column); message.append("] "); return message.toString(); } } else { final StringBuffer message = new StringBuffer (String.valueOf(super.getMessage())); message.append(" [Location: Line="); message.append(this.line); message.append(" Column="); message.append(this.column); message.append("] "); return message.toString(); } } /** * Fills the location with the given locator. * * @param locator the locator or null. */ protected void fillLocation(final Locator locator) { if (locator == null) { this.line = -1; this.column = -1; } else { this.line = locator.getLineNumber(); this.column = locator.getColumnNumber(); } } /** * Returns the line of the parse position where the error occured. * * @return the line number or -1 if not known. */ public int getLine() { return this.line; } /** * Returns the column of the parse position where the error occured. * * @return the column number or -1 if not known. */ public int getColumn() { return this.column; } /** * Prints the stack trace to the specified stream. * * @param stream the output stream. */ public void printStackTrace(final PrintStream stream) { super.printStackTrace(stream); if (getException() != null) { stream.println("ParentException: "); getException().printStackTrace(stream); } } /** * Override toString to pick up any embedded exception. * * @return A string representation of this exception. */ public String toString() { return getClass().getName() + ": " + getMessage(); } /** * Prints the stack trace to the specified writer. * * @param writer the writer. */ public void printStackTrace(final PrintWriter writer) { super.printStackTrace(writer); if (getException() != null) { writer.println("ParentException: "); getException().printStackTrace(writer); } } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/ResourceDataInputSource.java0000644000175000017500000000750311365606150032175 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import java.io.InputStream; import java.net.URL; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.reporting.libraries.resourceloader.ResourceData; import org.pentaho.reporting.libraries.resourceloader.ResourceLoadingException; import org.pentaho.reporting.libraries.resourceloader.ResourceManager; import org.xml.sax.InputSource; /** * A SAX InputSource implementation that reads its data from a LibLoader ResourceData object. * * @author Thomas Morgner */ public class ResourceDataInputSource extends InputSource { private static final Log logger = LogFactory.getLog(ResourceDataInputSource.class); private ResourceData data; private long version; private ResourceManager caller; /** * Creates a new InputSource using the given resource-data and resource-manager as source. * * @param data the resource-data object holding the raw-data. * @param caller the resource manager that is loading the current resource. * @throws ResourceLoadingException if an error occurs. * @see #setPublicId * @see #setSystemId * @see #setByteStream * @see #setCharacterStream * @see #setEncoding */ public ResourceDataInputSource(final ResourceData data, final ResourceManager caller) throws ResourceLoadingException { if (data == null) { throw new NullPointerException("Data must not be null"); } if (caller == null) { throw new NullPointerException("ResourceManager must not be null"); } this.data = data; this.version = data.getVersion(caller); this.caller = caller; final URL url = caller.toURL(data.getKey()); if (url != null) { setSystemId(url.toExternalForm()); } } /** * Set the byte stream for this input source. * * @param byteStream A byte stream containing an XML document or * other entity. */ public void setByteStream(final InputStream byteStream) { throw new UnsupportedOperationException(); } /** * Get the byte stream for this input source. * *

The getEncoding method will return the character * encoding for this byte stream, or null if unknown.

* * @return The byte stream, or null if none was supplied. * @see #getEncoding * @see #setByteStream */ public InputStream getByteStream() { try { return data.getResourceAsStream(caller); } catch (ResourceLoadingException e) { logger.error("Unable to create byte-stream: " + data.getKey()); return null; } } /** * Returns the resource-data object that provides the raw-data. * * @return the resource-data object. */ public ResourceData getData() { return data; } /** * Returns the version (changetracker) of this input source. * * @return the version (changetracker) of the input source. */ public long getVersion() { return version; } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/CommentHandler.java0000644000175000017500000001302711365606150030311 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import java.util.ArrayList; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; /** * The comment handler is used to collect all XML comments from the * SAX parser. The parser implementation must support comments to make * this feature work. * * @author Thomas Morgner */ public class CommentHandler implements LexicalHandler { /** * A constant marking a comment on the opening tag. */ public static final String OPEN_TAG_COMMENT = "parser.comment.open"; /** * A constant marking a comment on the closing tag. */ public static final String CLOSE_TAG_COMMENT = "parser.comment.close"; /** * A list containing all collected comments. */ private final ArrayList comment; /** * a flag marking whether the SAX parser is currently working in the DTD. */ private boolean inDTD; private static final String[] EMPTY_COMMENTS = new String[0]; /** * DefaultConstructor. */ public CommentHandler() { this.comment = new ArrayList(); } /** * Report the start of DTD declarations, if any. *

*

This method is empty.

* * @param name The document type name. * @param publicId The declared public identifier for the * external DTD subset, or null if none was declared. * @param systemId The declared system identifier for the * external DTD subset, or null if none was declared. * @throws org.xml.sax.SAXException The application may raise an * exception. * @see #endDTD() * @see #startEntity(String) */ public void startDTD(final String name, final String publicId, final String systemId) throws SAXException { this.inDTD = true; } /** * Report the end of DTD declarations. *

*

This method is empty.

* * @throws SAXException The application may raise an exception. */ public void endDTD() throws SAXException { this.inDTD = false; } /** * Report the beginning of some internal and external XML entities. *

*

This method is empty.

* * @param name The name of the entity. If it is a parameter * entity, the name will begin with '%', and if it is the * external DTD subset, it will be "[dtd]". * @throws SAXException The application may raise an exception. * @see #endEntity(String) * @see org.xml.sax.ext.DeclHandler#internalEntityDecl * @see org.xml.sax.ext.DeclHandler#externalEntityDecl */ public void startEntity(final String name) throws SAXException { // do nothing } /** * Report the end of an entity. *

*

This method is empty.

* * @param name The name of the entity that is ending. * @throws SAXException The application may raise an exception. * @see #startEntity(String) */ public void endEntity(final String name) throws SAXException { // do nothing } /** * Report the start of a CDATA section. *

*

This method is empty.

* * @throws SAXException The application may raise an exception. * @see #endCDATA() */ public void startCDATA() throws SAXException { // do nothing } /** * Report the end of a CDATA section. *

*

This method is empty.

* * @throws SAXException The application may raise an exception. * @see #startCDATA() */ public void endCDATA() throws SAXException { // do nothing } /** * Report an XML comment anywhere in the document. *

*

This callback will be used for comments inside or outside the * document element, including comments in the external DTD * subset (if read). Comments in the DTD must be properly * nested inside start/endDTD and start/endEntity events (if * used).

* * @param ch An array holding the characters in the comment. * @param start The starting position in the array. * @param length The number of characters to use from the array. * @throws SAXException The application may raise an exception. */ public void comment(final char[] ch, final int start, final int length) throws SAXException { if (!this.inDTD) { this.comment.add(new String(ch, start, length)); } } /** * Returns all collected comments as string array. * * @return the array containing all comments. */ public String[] getComments() { if (this.comment.isEmpty()) { return EMPTY_COMMENTS; } return (String[]) this.comment.toArray(new String[this.comment.size()]); } /** * Clears all comments. */ public void clearComments() { this.comment.clear(); } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/PropertyReadHandler.java0000644000175000017500000000357411365606150031335 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * The Property-ReadHandler reads character data from an element along with * a 'name' attribute. This way, this class is most suitable for creating * name-value-pairs. * * @author Thomas Morgner */ public class PropertyReadHandler extends StringReadHandler { private String name; /** * The Default-Constructor. */ public PropertyReadHandler() { } /** * Starts parsing. * * @param attrs the attributes. * @throws SAXException if there is a parsing error. */ protected void startParsing(final Attributes attrs) throws SAXException { super.startParsing(attrs); name = attrs.getValue(getUri(), "name"); if (name == null) { throw new ParseException("Required attribute 'name' missing", getLocator()); } } /** * Returns the declared property-name. * * @return the property name. */ public String getName() { return name; } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/DefaultXmlDocumentInfo.java0000644000175000017500000001122311365606150031765 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import org.xml.sax.Attributes; /** * A data class that holds all relevant information about a XML document to make a decision on what parser * to use to interpret the XML content. * * @author Thomas Morgner */ public class DefaultXmlDocumentInfo implements XmlDocumentInfo { private String rootElement; private String rootElementNameSpace; private String publicDTDId; private String systemDTDId; private String defaultNameSpace; private Attributes rootElementAttributes; /** * Default-Constructor. */ public DefaultXmlDocumentInfo() { } /** * Returns the tag name of the root-level element. * * @return the root-tag-name. */ public String getRootElement() { return rootElement; } /** * Defines the tag name of the root-level element. * * @param rootElement the root-tag-name. */ public void setRootElement(final String rootElement) { this.rootElement = rootElement; } /** * Returns the namespace URI for the root-element of the document. * * @return the namespace of the root-element. */ public String getRootElementNameSpace() { return rootElementNameSpace; } /** * Defines the namespace URI for the root-element of the document. * * @param rootElementNameSpace the namespace of the root-element. */ public void setRootElementNameSpace(final String rootElementNameSpace) { this.rootElementNameSpace = rootElementNameSpace; } public Attributes getRootElementAttributes() { return rootElementAttributes; } public void setRootElementAttributes(final Attributes rootElementAttributes) { this.rootElementAttributes = rootElementAttributes; } /** * Returns the Public-ID of the Document's DTD (if there's any). * * @return the public id. */ public String getPublicDTDId() { return publicDTDId; } /** * Defines the Public-ID of the Document's DTD (if there's any). * * @param publicDTDId the public id. */ public void setPublicDTDId(final String publicDTDId) { this.publicDTDId = publicDTDId; } /** * Returns the System-ID of the document's DTD. * * @return the system-id. */ public String getSystemDTDId() { return systemDTDId; } /** * Defines the System-ID of the document's DTD. * * @param systemDTDId the system-id. */ public void setSystemDTDId(final String systemDTDId) { this.systemDTDId = systemDTDId; } /** * Returns a string representation of the document info. This is for debugging purposes only. * * @return the string version of the document info. */ public String toString() { final StringBuffer buffer = new StringBuffer(120); buffer.append("XmlDocumentInfo={rootElementTag="); buffer.append(rootElement); buffer.append(", rootElementNS="); buffer.append(rootElementNameSpace); buffer.append(", SystemDTD-ID="); buffer.append(systemDTDId); buffer.append(", PublicDTD-ID="); buffer.append(publicDTDId); buffer.append(", defaultnamespace="); buffer.append(defaultNameSpace); buffer.append('}'); return buffer.toString(); } /** * Returns the default-namespace declared on the root-element. It is * not guaranteed that this information is filled until a XmlFactoryModule * has been selected. * * @return the default-namespace. */ public String getDefaultNameSpace() { return defaultNameSpace; } /** * Defines the default-namespace declared on the root-element. It is * not guaranteed that this information is filled until a XmlFactoryModule * has been selected. * * @param defaultNameSpace the default-namespace. */ public void setDefaultNameSpace(final String defaultNameSpace) { this.defaultNameSpace = defaultNameSpace; } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/FixNamespaceUriAttributes.java0000644000175000017500000002275611365606150032514 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import org.xml.sax.Attributes; /** * A SAX-Attributes implementation that fixes missing namespace-URIs. Attributes that define no namespace URIs on * their own will receive the defined default namespace. * * @author Thomas Morgner */ public class FixNamespaceUriAttributes implements Attributes { private Attributes attributes; private String defaultNSUri; /** * Creates a new FixNamespaceUriAttributes wrapper. * * @param defaultNSUri the default namespace that is used if no explicit namespace is defined for an attribute. * @param attributes the original attributes. */ public FixNamespaceUriAttributes(final String defaultNSUri, final Attributes attributes) { this.attributes = attributes; this.defaultNSUri = defaultNSUri; } /** * Return the number of attributes in the list. *

*

Once you know the number of attributes, you can iterate through the * list.

* * @return The number of attributes in the list. * @see #getURI(int) * @see #getLocalName(int) * @see #getQName(int) * @see #getType(int) * @see #getValue(int) */ public int getLength() { return attributes.getLength(); } /** * Look up an attribute's Namespace URI by index. * * @param index The attribute index (zero-based). * @return The Namespace URI, or the empty string if none is available, or * null if the index is out of range. * @see #getLength */ public String getURI(final int index) { final String uri = attributes.getURI(index); if (uri == null || "".equals(uri)) { return defaultNSUri; } return uri; } /** * Look up an attribute's local name by index. * * @param index The attribute index (zero-based). * @return The local name, or the empty string if Namespace processing is not * being performed, or null if the index is out of range. * @see #getLength */ public String getLocalName(final int index) { final String name = attributes.getLocalName(index); if (name == null || "".equals(name)) { return attributes.getQName(index); } return name; } /** * Look up an attribute's XML qualified (prefixed) name by index. * * @param index The attribute index (zero-based). * @return The XML qualified name, or the empty string if none is available, * or null if the index is out of range. * @see #getLength */ public String getQName(final int index) { return attributes.getQName(index); } /** * Look up an attribute's type by index. *

*

The attribute type is one of the strings "CDATA", "ID", "IDREF", * "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", or "NOTATION" * (always in upper case).

*

*

If the parser has not read a declaration for the attribute, or if the * parser does not report attribute types, then it must return the value * "CDATA" as stated in the XML 1.0 Recommendation (clause 3.3.3, * "Attribute-Value Normalization").

*

*

For an enumerated attribute that is not a notation, the parser will * report the type as "NMTOKEN".

* * @param index The attribute index (zero-based). * @return The attribute's type as a string, or null if the index is out of * range. * @see #getLength */ public String getType(final int index) { return attributes.getType(index); } /** * Look up an attribute's value by index. *

*

If the attribute value is a list of tokens (IDREFS, ENTITIES, or * NMTOKENS), the tokens will be concatenated into a single string with each * token separated by a single space.

* * @param index The attribute index (zero-based). * @return The attribute's value as a string, or null if the index is out of * range. * @see #getLength */ public String getValue(final int index) { return attributes.getValue(index); } /** * Look up the index of an attribute by Namespace name. * * @param uri The Namespace URI, or the empty string if the name has no * Namespace URI. * @param localName The attribute's local name. * @return The index of the attribute, or -1 if it does not appear in the * list. */ public int getIndex(final String uri, final String localName) { final int idx = attributes.getIndex(uri, localName); if (idx >= 0) { return idx; } if (defaultNSUri.equals(uri)) { final int index = attributes.getIndex("", localName); if (index != -1) { return index; } try { final int value2 = attributes.getIndex(null, localName); if (value2 != -1) { return value2; } } catch (Exception e) { // ignore. Heck, Xerces breaks the SAX-Specs so we have to take weird steps to mess around their mess. } return attributes.getIndex(localName); } return -1; } /** * Look up the index of an attribute by XML qualified (prefixed) name. * * @param qName The qualified (prefixed) name. * @return The index of the attribute, or -1 if it does not appear in the * list. */ public int getIndex(final String qName) { return attributes.getIndex(qName); } /** * Look up an attribute's type by Namespace name. *

*

See {@link #getType(int) getType(int)} for a description of the possible * types.

* * @param uri The Namespace URI, or the empty String if the name has no * Namespace URI. * @param localName The local name of the attribute. * @return The attribute type as a string, or null if the attribute is not in * the list or if Namespace processing is not being performed. */ public String getType(final String uri, final String localName) { final String type = attributes.getType(uri, localName); if (type != null) { return type; } if (defaultNSUri.equals(uri)) { final String type1 = attributes.getType("", localName); if (type1 != null) { return type1; } try { final String value2 = attributes.getType(null, localName); if (value2 != null) { return value2; } } catch (Exception e) { // ignore. Heck, Xerces breaks the SAX-Specs so we have to take weird steps to mess around their mess. } return attributes.getType(localName); } return null; } /** * Look up an attribute's type by XML qualified (prefixed) name. *

*

See {@link #getType(int) getType(int)} for a description of the possible * types.

* * @param qName The XML qualified name. * @return The attribute type as a string, or null if the attribute is not in * the list or if qualified names are not available. */ public String getType(final String qName) { return attributes.getType(qName); } /** * Look up an attribute's value by Namespace name. *

*

See {@link #getValue(int) getValue(int)} for a description of the * possible values.

* * @param uri The Namespace URI, or the empty String if the name has no * Namespace URI. * @param localName The local name of the attribute. * @return The attribute value as a string, or null if the attribute is not in * the list. */ public String getValue(final String uri, final String localName) { final String value = attributes.getValue(uri, localName); if (value != null) { return value; } if (defaultNSUri.equals(uri)) { final String value1 = attributes.getValue("", localName); if (value1 != null) { return value1; } try { final String value2 = attributes.getValue(null, localName); if (value2 != null) { return value2; } } catch (Exception e) { // ignore. Heck, Xerces breaks the SAX-Specs so we have to take weird steps to mess around their mess. } return attributes.getValue(localName); } return null; } /** * Look up an attribute's value by XML qualified (prefixed) name. *

*

See {@link #getValue(int) getValue(int)} for a description of the * possible values.

* * @param qName The XML qualified name. * @return The attribute value as a string, or null if the attribute is not in * the list or if qualified names are not available. */ public String getValue(final String qName) { return attributes.getValue(qName); } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/IgnoreAnyChildReadHandler.java0000644000175000017500000000376111365606150032346 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A read-handler that silently ignores all childs. This readhandler produces no output. * * @author Thomas Morgner */ public class IgnoreAnyChildReadHandler extends AbstractXmlReadHandler { /** * Default Constructor. */ public IgnoreAnyChildReadHandler() { } /** * Returns the handler for a child element. * * @param tagName the tag name. * @param atts the attributes. * @return the handler or null, if the tagname is invalid. * @throws org.xml.sax.SAXException if there is a parsing error. */ protected XmlReadHandler getHandlerForChild(final String uri, final String tagName, final Attributes atts) throws SAXException { return new IgnoreAnyChildReadHandler(); } /** * Returns the object for this element or null, if this element does not * create an object. * * @return the object. */ public Object getObject() throws SAXException { return null; } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/parser/AbstractXmlReadHandler.java0000644000175000017500000002571611365606150031737 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.parser; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.reporting.libraries.resourceloader.DependencyCollector; import org.pentaho.reporting.libraries.resourceloader.FactoryParameterKey; import org.pentaho.reporting.libraries.resourceloader.Resource; import org.pentaho.reporting.libraries.resourceloader.ResourceException; import org.pentaho.reporting.libraries.resourceloader.ResourceKey; import org.pentaho.reporting.libraries.resourceloader.ResourceLoadingException; import org.pentaho.reporting.libraries.resourceloader.ResourceManager; import org.pentaho.reporting.libraries.base.util.ObjectUtilities; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; /** * A base class for implementing an {@link org.pentaho.reporting.libraries.xmlns.parser.XmlReadHandler}. * This class takes care of all the delegation management. */ public abstract class AbstractXmlReadHandler implements XmlReadHandler { private static final Log logger = LogFactory.getLog(AbstractXmlReadHandler.class); /** * The root handler. */ private RootXmlReadHandler rootHandler; /** * The tag name. */ private String tagName; /** * THe namespace URI. */ private String uri; /** * A flag indicating the first call. */ private boolean firstCall; /** * Creates a new handler. */ protected AbstractXmlReadHandler() { } /** * Initialises the handler. * * @param rootHandler the root handler. * @param tagName the tag name. */ public void init(final RootXmlReadHandler rootHandler, final String uri, final String tagName) { if (rootHandler == null) { throw new NullPointerException("Root handler must not be null"); } if (tagName == null) { throw new NullPointerException("Tag name must not be null"); } this.uri = uri; this.rootHandler = rootHandler; this.tagName = tagName; this.firstCall = true; } /** * This method is called at the start of an element. * * @param tagName the tag name. * @param attrs the attributes. * @throws SAXException if there is a parsing error. */ public final void startElement(final String uri, final String tagName, final Attributes attrs) throws SAXException { if (this.firstCall) { if (!this.tagName.equals(tagName) || !this.uri.equals(uri)) { throw new ParseException( "Expected <" + this.tagName + ">, found <" + tagName + '>', getLocator()); } this.firstCall = false; startParsing(attrs); } else { final XmlReadHandler childHandler = getHandlerForChild(uri, tagName, attrs); if (childHandler == null) { logger.warn("Unknown tag <" + uri + ':' + tagName + ">: Start to ignore this element and all of its childs. " + getLocatorString()); logger.debug(this.getClass()); final IgnoreAnyChildReadHandler ignoreAnyChildReadHandler = new IgnoreAnyChildReadHandler(); ignoreAnyChildReadHandler.init(getRootHandler(), uri, tagName); this.rootHandler.recurse(ignoreAnyChildReadHandler, uri, tagName, attrs); } else { childHandler.init(getRootHandler(), uri, tagName); this.rootHandler.recurse(childHandler, uri, tagName, attrs); } } } /** * This method is called to process the character data between element tags. * * @param ch the character buffer. * @param start the start index. * @param length the length. * @throws SAXException if there is a parsing error. */ public void characters(final char[] ch, final int start, final int length) throws SAXException { // nothing required } /** * This method is called at the end of an element. * * @param tagName the tag name. * @throws SAXException if there is a parsing error. */ public final void endElement(final String uri, final String tagName) throws SAXException { if (this.tagName.equals(tagName) && this.uri.equals(uri)) { doneParsing(); this.rootHandler.unwind(uri, tagName); } else { throw new ParseException("Illegal Parser State." + toString(), getLocator()); } } /** * Computes a string containing the current parse location or an empty string if there is no locator. * * @return the location as debug-text. */ private String getLocatorString() { final Locator locator = getLocator(); if (locator == null) { return ""; } final StringBuffer message = new StringBuffer(100); message.append(" [Location: Line="); message.append(locator.getLineNumber()); message.append(" Column="); message.append(locator.getColumnNumber()); message.append("] "); return message.toString(); } /** * Starts parsing. * * @param attrs the attributes. * @throws SAXException if there is a parsing error. */ protected void startParsing(final Attributes attrs) throws SAXException { // nothing required } /** * Done parsing. * * @throws SAXException if there is a parsing error. */ protected void doneParsing() throws SAXException { // nothing required } /** * Checks whether the given url denotes the same namespace as the element's namespace. * * @param namespaceURI the namespace that should be tested. * @return true, if the namespace matches the element's namespace,false otherwise. */ protected boolean isSameNamespace(final String namespaceURI) { return ObjectUtilities.equal(namespaceURI, getUri()); } /** * Returns the handler for a child element. * * @param uri the URI of the namespace of the current element. * @param tagName the tag name. * @param atts the attributes. * @return the handler or null, if the tagname is invalid. * @throws SAXException if there is a parsing error. */ protected XmlReadHandler getHandlerForChild(final String uri, final String tagName, final Attributes atts) throws SAXException { return null; } /** * Returns the tag name. * * @return the tag name. */ public String getTagName() { return this.tagName; } /** * Returns the uri of the element. The URI identifies the namespace. * * @return the element's URI. */ public String getUri() { return uri; } /** * Returns the root handler for the parsing. * * @return the root handler. */ public RootXmlReadHandler getRootHandler() { return this.rootHandler; } /** * Returns the locator as provided by the XML parser. This method may return null if the XML parser has no * locator support. * * @return the locator or null. */ public Locator getLocator() { return rootHandler.getDocumentLocator(); } /** * Parses an external file using LibLoader and returns the parsed result as an object of type * targetClass. The file is given as relative pathname (relative to the current source file). * The current helper-methods are used as parse-parameters for the external parsing. * * @param file the file to be parsed. * @param targetClass the target type of the parse operation. * @return the result, never null. * @throws ParseException if parsing the result failed for some reason. * @throws ResourceLoadingException if there was an IO error loading the resource. * @see #deriveParseParameters() * @see #performExternalParsing(String, Class, Map) */ protected Object performExternalParsing(final String file, final Class targetClass) throws ParseException, ResourceLoadingException { return performExternalParsing(file, targetClass, deriveParseParameters()); } /** * Parses an external file using LibLoader and returns the parsed result as an object of type * targetClass. The file is given as relative pathname (relative to the current source file). * The current helper-methods are used as parse-parameters for the external parsing. * * @param file the file to be parsed. * @param targetClass the target type of the parse operation. * @param map the map of parse parameters. * @return the result, never null. * @throws ParseException if parsing the result failed for some reason. * @throws ResourceLoadingException if there was an IO error loading the resource. * @see #deriveParseParameters() */ protected Object performExternalParsing(final String file, final Class targetClass, final Map map) throws ParseException, ResourceLoadingException { try { final ResourceManager resourceManager = rootHandler.getResourceManager(); final ResourceKey source = rootHandler.getSource(); final ResourceKey target = resourceManager.deriveKey(source, file, map); final DependencyCollector dc = rootHandler.getDependencyCollector(); final Resource resource = resourceManager.create(target, rootHandler.getContext(), targetClass); dc.add(resource); return resource.getResource(); } catch (ResourceLoadingException rle) { throw rle; } catch (ResourceException e) { throw new ParseException("Failure while loading data: " + file, e, getLocator()); } } /** * Creates a working copy of the current parse state. * * @noinspection ObjectAllocationInLoop as this is a cloning operation. * @return the derived parse-parameters. */ protected Map deriveParseParameters() { final RootXmlReadHandler rootHandler = getRootHandler(); final HashMap map = new HashMap(); final String[] names = rootHandler.getHelperObjectNames(); final int length = names.length; for (int i = 0; i < length; i++) { final String name = names[i]; final FactoryParameterKey key = new FactoryParameterKey(name); map.put(key, rootHandler.getHelperObject(name)); } return map; } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/writer/0000755000175000017500000000000011365606150024563 5ustar renerenelibxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/writer/HtmlCharacterEntities.java0000644000175000017500000002536211365606150031664 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.writer; import java.util.Properties; /** * A collection of all character entites defined in the HTML4 standard. The key * is the entity name, the property value is the decoded string. * * @author Thomas Morgner */ public class HtmlCharacterEntities extends Properties { /** * The singleton instance for this entity-parser implementation. */ private static CharacterEntityParser entityParser; private static final long serialVersionUID = 5118172339379209383L; /** * Gets the character entity parser for HTML content. The CharacterEntity * parser translates known characters into predefined entities. * * @return the character entity parser instance. */ public static synchronized CharacterEntityParser getEntityParser() { if (entityParser == null) { entityParser = new CharacterEntityParser(new HtmlCharacterEntities()); } return entityParser; } /** * Creates an instance. */ public HtmlCharacterEntities() { setProperty("ang", "\u2220"); setProperty("spades", "\u2660"); setProperty("frasl", "\u2044"); setProperty("copy", "\u00a9"); setProperty("Upsilon", "\u03a5"); setProperty("rsquo", "\u2019"); setProperty("sdot", "\u22c5"); setProperty("beta", "\u03b2"); setProperty("egrave", "\u00e8"); setProperty("Pi", "\u03a0"); setProperty("micro", "\u00b5"); setProperty("lArr", "\u21d0"); setProperty("Beta", "\u0392"); setProperty("eacute", "\u00e9"); setProperty("agrave", "\u00e0"); setProperty("sbquo", "\u201a"); setProperty("ucirc", "\u00fb"); setProperty("mdash", "\u2014"); setProperty("rho", "\u03c1"); setProperty("Nu", "\u039d"); setProperty("ne", "\u2260"); setProperty("nsub", "\u2284"); setProperty("AElig", "\u00c6"); setProperty("raquo", "\u00bb"); setProperty("aacute", "\u00e1"); setProperty("le", "\u2264"); setProperty("harr", "\u2194"); setProperty("frac34", "\u00be"); setProperty("bdquo", "\u201e"); setProperty("cup", "\u222a"); setProperty("frac14", "\u00bc"); setProperty("exist", "\u2203"); setProperty("Ccedil", "\u00c7"); setProperty("phi", "\u03c6"); setProperty("Lambda", "\u039b"); setProperty("alpha", "\u03b1"); setProperty("sigma", "\u03c3"); setProperty("thetasym", "\u03d1"); setProperty("Rho", "\u03a1"); setProperty("hArr", "\u21d4"); setProperty("Dagger", "\u2021"); setProperty("otilde", "\u00f5"); setProperty("Epsilon", "\u0395"); setProperty("iuml", "\u00ef"); setProperty("Phi", "\u03a6"); setProperty("prod", "\u220f"); setProperty("Aring", "\u00c5"); setProperty("rlm", "\u200f"); setProperty("yen", "\u00a5"); setProperty("emsp", "\u2003"); setProperty("rang", "\u232a"); setProperty("Atilde", "\u00c3"); setProperty("Iuml", "\u00cf"); setProperty("iota", "\u03b9"); setProperty("deg", "\u00b0"); setProperty("prop", "\u221d"); setProperty("and", "\u2227"); setProperty("para", "\u00b6"); setProperty("darr", "\u2193"); setProperty("curren", "\u00a4"); setProperty("crarr", "\u21b5"); setProperty("not", "\u00ac"); setProperty("Iota", "\u0399"); setProperty("aelig", "\u00e6"); setProperty("rdquo", "\u201d"); setProperty("Ocirc", "\u00d4"); setProperty("ntilde", "\u00f1"); setProperty("reg", "\u00ae"); setProperty("zeta", "\u03b6"); setProperty("middot", "\u00b7"); setProperty("cent", "\u00a2"); setProperty("quot", "\""); setProperty("hellip", "\u2026"); setProperty("Zeta", "\u0396"); setProperty("rceil", "\u2309"); setProperty("eta", "\u03b7"); setProperty("nbsp", "\u00a0"); setProperty("rarr", "\u2192"); setProperty("frac12", "\u00bd"); setProperty("real", "\u211c"); setProperty("mu", "\u03bc"); setProperty("dArr", "\u21d3"); setProperty("divide", "\u00f7"); setProperty("cap", "\u2229"); setProperty("chi", "\u03c7"); setProperty("times", "\u00d7"); setProperty("euml", "\u00eb"); setProperty("Gamma", "\u0393"); setProperty("loz", "\u25ca"); setProperty("acute", "\u00b4"); setProperty("Omega", "\u03a9"); setProperty("ndash", "\u2013"); setProperty("clubs", "\u2663"); setProperty("macr", "\u00af"); setProperty("Yacute", "\u00dd"); setProperty("Ugrave", "\u00d9"); setProperty("Euml", "\u00cb"); setProperty("Eta", "\u0397"); setProperty("sect", "\u00a7"); setProperty("asymp", "\u2248"); setProperty("ordm", "\u00ba"); setProperty("rArr", "\u21d2"); setProperty("radic", "\u221a"); setProperty("Uacute", "\u00da"); setProperty("omicron", "\u03bf"); setProperty("Chi", "\u03a7"); setProperty("aring", "\u00e5"); setProperty("Theta", "\u0398"); setProperty("supe", "\u2287"); setProperty("ensp", "\u2002"); setProperty("uml", "\u00a8"); setProperty("ccedil", "\u00e7"); setProperty("lambda", "\u03bb"); setProperty("gt", "\u003e"); setProperty("uarr", "\u2191"); setProperty("alefsym", "\u2135"); setProperty("auml", "\u00e4"); setProperty("sup3", "\u00b3"); setProperty("circ", "\u02c6"); setProperty("lsquo", "\u2018"); setProperty("Auml", "\u00c4"); setProperty("dagger", "\u2020"); setProperty("Kappa", "\u039a"); setProperty("cong", "\u2245"); setProperty("zwnj", "\u200c"); setProperty("shy", "\u00ad"); setProperty("ouml", "\u00f6"); setProperty("diams", "\u2666"); setProperty("uArr", "\u21d1"); setProperty("atilde", "\u00e3"); setProperty("THORN", "\u00de"); setProperty("or", "\u2228"); setProperty("Ograve", "\u00d2"); setProperty("ocirc", "\u00f4"); setProperty("plusm", "\u00b1"); setProperty("Ouml", "\u00d6"); setProperty("nabla", "\u2207"); setProperty("psi", "\u03c8"); setProperty("sigmaf", "\u03c2"); setProperty("euro", "\u20ac"); setProperty("sube", "\u2286"); setProperty("sup2", "\u00b2"); setProperty("laquo", "\u00ab"); setProperty("forall", "\u2200"); setProperty("Oacute", "\u00d3"); setProperty("iexcl", "\u00a1"); fillMoreEntities(); } /** * Externalized initialization method to make CheckStyle happy. */ private void fillMoreEntities() { setProperty("piv", "\u03d6"); setProperty("minus", "\u2212"); setProperty("zwj", "\u200d"); setProperty("tau", "\u03c4"); setProperty("Mu", "\u039c"); setProperty("gamma", "\u03b3"); setProperty("sup", "\u2283"); setProperty("Psi", "\u03a8"); setProperty("omega", "\u03c9"); setProperty("Oslash", "\u00d8"); setProperty("weierp", "\u2118"); setProperty("Igrave", "\u00cc"); setProperty("OElig", "\u0152"); setProperty("sup1", "\u00b9"); setProperty("cedil", "\u00b8"); setProperty("upsilon", "\u03c5"); setProperty("equiv", "\u2261"); setProperty("isin", "\u2208"); setProperty("Delta", "\u0394"); setProperty("yacute", "\u00fd"); setProperty("ugrave", "\u00f9"); setProperty("ge", "\u2265"); setProperty("Iacute", "\u00cd"); setProperty("brvbar", "\u00a6"); setProperty("Tau", "\u03a4"); setProperty("Prime", "\u2033"); setProperty("rfloor", "\u22a7"); setProperty("Ecirc", "\u00ca"); setProperty("ETH", "\u00d0"); setProperty("int", "\u222b"); setProperty("xi", "\u03be"); setProperty("uacute", "\u00fa"); setProperty("bull", "\u2022"); setProperty("Scaron", "\u0160"); setProperty("theta", "\u03b8"); setProperty("yuml", "\u00ff"); setProperty("oplus", "\u2295"); setProperty("part", "\u2202"); setProperty("ldquo", "\u201c"); setProperty("Icirc", "\u00ce"); setProperty("Yuml", "\u0178"); setProperty("eth", "\u00f0"); setProperty("Acirc", "\u00c2"); setProperty("sub", "\u2282"); setProperty("lceil", "\u2308"); setProperty("Egrave", "\u00c8"); setProperty("tilde", "\u02dc"); setProperty("pi", "\u03c0"); setProperty("rsaquo", "\u203a"); setProperty("kappa", "\u03ba"); setProperty("upsih", "\u03d2"); setProperty("Omicron", "\u039f"); setProperty("otimes", "\u2297"); setProperty("ni", "\u220b"); setProperty("amp", "\u0026"); setProperty("Eacute", "\u00c9"); setProperty("nu", "\u03bd"); setProperty("Ucirc", "\u00db"); setProperty("uuml", "\u00fc"); setProperty("oslash", "\u00f8"); setProperty("thorn", "\u00fe"); setProperty("trade", "\u2122"); setProperty("epsilon", "\u03b5"); setProperty("ograve", "\u00f2"); setProperty("hearts", "\u2665"); setProperty("iquest", "\u00bf"); setProperty("Uuml", "\u00dc"); setProperty("empty", "\u2205"); setProperty("lowast", "\u2217"); setProperty("sum", "\u2211"); setProperty("lfloor", "\u22a6"); setProperty("lrm", "\u200e"); setProperty("oacute", "\u00f3"); setProperty("image", "\u2111"); setProperty("Agrave", "\u00c0"); setProperty("oline", "\u203e"); setProperty("oelig", "\u0153"); setProperty("Sigma", "\u03a3"); setProperty("permil", "\u2030"); setProperty("perp", "\u22a5"); setProperty("lt", "\u003c"); setProperty("Aacute", "\u00c1"); setProperty("acirc", "\u00e2"); setProperty("lang", "\u2329"); setProperty("delta", "\u03b4"); setProperty("infin", "\u221e"); setProperty("igrave", "\u00ec"); setProperty("ordf", "\u00aa"); setProperty("lsaquo", "\u2039"); setProperty("prime", "\u2032"); setProperty("ecirc", "\u00ea"); setProperty("there4", "\u2234"); setProperty("iacute", "\u00ed"); setProperty("sim", "\u223c"); setProperty("Alpha", "\u0391"); setProperty("pound", "\u00a3"); setProperty("notin", "\u2209"); setProperty("Ntilde", "\u00d1"); setProperty("Xi", "\u039e"); setProperty("thinsp", "\u2009"); setProperty("Otilde", "\u00d5"); setProperty("icirc", "\u00ee"); setProperty("scaron", "\u0161"); setProperty("szlig", "\u00df"); setProperty("larr", "\u2190"); } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/writer/XmlWriter.java0000644000175000017500000002124411365606150027366 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.writer; import java.io.IOException; import java.io.Reader; import java.io.Writer; import org.pentaho.reporting.libraries.xmlns.common.AttributeList; import org.pentaho.reporting.libraries.base.util.IOUtils; /** * A class for writing XML to a character stream. * * @author Thomas Morgner */ public class XmlWriter extends XmlWriterSupport { /** * The character stream. */ private Writer writer; /** * Creates a new XML writer for the specified character stream. By default, * four spaces are used for indentation. * * @param writer the character stream. */ public XmlWriter(final Writer writer) { this(writer, " "); } /** * Default Constructor. The created XMLWriterSupport will not have no safe * tags and starts with an indention level of 0. * * @param writer the character stream. * @param tagDescription the tags that are safe for line breaks. */ public XmlWriter(final Writer writer, final TagDescription tagDescription) { this(writer, tagDescription, " "); } /** * Creates a new XML writer for the specified character stream. * * @param writer the character stream. * @param indentString the string used for indentation (should contain white * space, for example four spaces). */ public XmlWriter(final Writer writer, final String indentString) { this(writer, new DefaultTagDescription(), indentString); } /** * Creates a new XMLWriter instance. * * @param writer the character stream. * @param tagDescription the tags that are safe for line breaks. * @param indentString the indent string. */ public XmlWriter(final Writer writer, final TagDescription tagDescription, final String indentString) { super(tagDescription, indentString); if (writer == null) { throw new NullPointerException("Writer must not be null."); } this.writer = writer; } /** * Creates a new XMLWriter instance. * * @param writer the character stream. * @param tagDescription the tags that are safe for line breaks. * @param indentString the indent string. * @param lineSeparator the line separator to be used. */ public XmlWriter(final Writer writer, final TagDescription tagDescription, final String indentString, final String lineSeparator) { super(tagDescription, indentString, lineSeparator); if (writer == null) { throw new NullPointerException("Writer must not be null."); } this.writer = writer; } /** * Writes the XML declaration that usually appears at the top of every XML * file. * * @param encoding the encoding that should be declared (this has to match the * encoding of the writer, or funny things may happen when * parsing the xml file later). * @throws java.io.IOException if there is a problem writing to the character * stream. */ public void writeXmlDeclaration(final String encoding) throws IOException { if (encoding == null) { this.writer.write(""); this.writer.write(getLineSeparator()); return; } this.writer.write(""); this.writer.write(getLineSeparator()); } /** * Writes an opening XML tag that has no attributes. * * @param namespace the namespace URI for the element * @param name the tag name. * @param close a flag that controls whether or not the tag is closed * immediately. * @throws java.io.IOException if there is an I/O problem. */ public void writeTag(final String namespace, final String name, final boolean close) throws IOException { if (close) { writeTag(this.writer, namespace, name, null, XmlWriterSupport.CLOSE); } else { writeTag(this.writer, namespace, name, null, XmlWriterSupport.OPEN); } } /** * Writes a closing XML tag. * * @throws java.io.IOException if there is an I/O problem. */ public void writeCloseTag() throws IOException { super.writeCloseTag(this.writer); } /** * Writes an opening XML tag with an attribute/value pair. * * @param namespace the namespace URI for the element * @param name the tag name. * @param attributeName the attribute name. * @param attributeValue the attribute value. * @param close controls whether the tag is closed. * @throws java.io.IOException if there is an I/O problem. */ public void writeTag(final String namespace, final String name, final String attributeName, final String attributeValue, final boolean close) throws IOException { writeTag(this.writer, namespace, name, attributeName, attributeValue, close); } /** * Writes an opening XML tag along with a list of attribute/value pairs. * * @param namespace the namespace URI for the element * @param name the tag name. * @param attributes the attributes. * @param close controls whether the tag is closed. * @throws java.io.IOException if there is an I/O problem. */ public void writeTag(final String namespace, final String name, final AttributeList attributes, final boolean close) throws IOException { writeTag(this.writer, namespace, name, attributes, close); } /** * Writes some text to the character stream. * * @param text the text. * @throws IOException if there is a problem writing to the character stream. */ public void writeText(final String text) throws IOException { this.writer.write(text); setLineEmpty(false); } /** * Writes the given text into the stream using a streaming xml-normalization method. * * @param s the string to be written. * @param transformNewLine whether to encode newlines using character-entities. * @throws IOException if an IO error occured. */ public void writeTextNormalized(final String s, final boolean transformNewLine) throws IOException { writeTextNormalized(writer, s, transformNewLine); } /** * Copies the given reader to the character stream. This method should be used * for large chunks of data. * * @param reader the reader providing the text. * @throws IOException if there is a problem writing to the character stream. */ public void writeStream(final Reader reader) throws IOException { IOUtils.getInstance().copyWriter(reader, writer); setLineEmpty(false); } /** * Closes the underlying character stream. * * @throws IOException if there is a problem closing the character stream. */ public void close() throws IOException { this.writer.close(); } /** * Writes a comment into the generated xml file. * * @param comment the comment text * @throws IOException if there is a problem writing to the character stream. */ public void writeComment(final String comment) throws IOException { super.writeComment(writer, comment); } /** * Writes a linebreak to the writer. * * @throws IOException if there is a problem writing to the character stream. */ public void writeNewLine() throws IOException { super.writeNewLine(writer); } /** * Flushs the underlying writer. * * @throws IOException if something goes wrong. */ public void flush() throws IOException { this.writer.flush(); } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/writer/XmlWriterSupport.java0000644000175000017500000007755111365606150030777 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.writer; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.Properties; import org.pentaho.reporting.libraries.base.util.FastStack; import org.pentaho.reporting.libraries.base.util.ObjectUtilities; import org.pentaho.reporting.libraries.base.util.StringUtils; import org.pentaho.reporting.libraries.xmlns.common.AttributeList; /** * A support class for writing XML files. * * @author Thomas Morgner */ public class XmlWriterSupport { /** * An internal state-management class containing the state for nested * tags. */ private static class ElementLevel { private String namespace; private String prefix; private String tagName; private DeclaredNamespaces namespaces; /** * Creates a new ElementLevel object. * * @param namespace the namespace of the current tag (can be null). * @param prefix the namespace prefix of the current tag (can be null). * @param tagName the tagname (never null). * @param namespaces the collection of all currently known namespaces (never null). */ protected ElementLevel(final String namespace, final String prefix, final String tagName, final DeclaredNamespaces namespaces) { if (tagName == null) { throw new NullPointerException(); } if (namespaces == null) { throw new NullPointerException(); } this.prefix = prefix; this.namespace = namespace; this.tagName = tagName; this.namespaces = namespaces; } /** * Creates a new ElementLevel with no namespace information. * * @param tagName the xml-tagname. * @param namespaces the currently known namespaces. */ protected ElementLevel(final String tagName, final DeclaredNamespaces namespaces) { if (tagName == null) { throw new NullPointerException(); } if (namespaces == null) { throw new NullPointerException(); } this.namespaces = namespaces; this.tagName = tagName; } /** * Returns the defined namespace prefix for this entry. * * @return the namespace prefix. */ public String getPrefix() { return prefix; } /** * Returns the defined namespace uri for this entry. * * @return the namespace uri. */ public String getNamespace() { return namespace; } /** * Returns the tagname for this entry. * * @return the tagname. */ public String getTagName() { return tagName; } /** * Returns the map of defined namespace for this entry. * * @return the namespaces. */ public DeclaredNamespaces getNamespaces() { return namespaces; } } /** * A constant for controlling the indent function. */ public static final int OPEN_TAG_INCREASE = 1; /** * A constant for controlling the indent function. */ public static final int CLOSE_TAG_DECREASE = 2; /** * A constant for controlling the indent function. */ public static final int INDENT_ONLY = 3; /** * A constant for close. */ public static final boolean CLOSE = true; /** * A constant for open. */ public static final boolean OPEN = false; /** * A list of safe tags. */ private TagDescription safeTags; /** * The indent level for that writer. */ private FastStack openTags; /** * The indent string. */ private String indentString; private boolean lineEmpty; private int additionalIndent; private boolean alwaysAddNamespace; private boolean assumeDefaultNamespace; private HashMap impliedNamespaces; private boolean writeFinalLinebreak; private boolean htmlCompatiblityMode; private String lineSeparator; private StringBuffer normalizeBuffer; /** * Default Constructor. The created XMLWriterSupport will not have no safe tags and starts with an indention level of * 0. */ public XmlWriterSupport() { this(new DefaultTagDescription(), " "); } /** * Creates a new support instance. * * @param safeTags the tags that are safe for line breaks. * @param indentString the indent string. */ public XmlWriterSupport(final TagDescription safeTags, final String indentString) { this(safeTags, indentString, StringUtils.getLineSeparator()); } /** * Create a new XmlWriterSupport instance. * * @param safeTags the tags that are safe for line breaks. * @param indentString the indent string. * @param lineseparator the lineseparator that should be used for writing XML files. */ public XmlWriterSupport(final TagDescription safeTags, final String indentString, final String lineseparator) { if (indentString == null) { throw new NullPointerException("IndentString must not be null"); } if (safeTags == null) { throw new NullPointerException("SafeTags must not be null"); } if (lineseparator == null) { throw new NullPointerException("LineSeparator must not be null"); } this.normalizeBuffer = new StringBuffer(128); this.safeTags = safeTags; this.openTags = new FastStack(); this.indentString = indentString; this.lineEmpty = true; this.writeFinalLinebreak = true; this.lineSeparator = lineseparator; addImpliedNamespace("http://www.w3.org/XML/1998/namespace", "xml"); } /** * Checks, whether the HTML compatibility mode is enabled. In HTML compatibility * mode, closed empty tags will have a space between the tagname and the * close-indicator. * * @return true, if the HTML compatiblity mode is enabled, false otherwise. */ public boolean isHtmlCompatiblityMode() { return htmlCompatiblityMode; } /** * Enables or disables the HTML Compatibility mode. In HTML compatibility * mode, closed empty tags will have a space between the tagname and the * close-indicator. * * @param htmlCompatiblityMode true, if the HTML compatiblity mode is enabled, false otherwise. */ public void setHtmlCompatiblityMode(final boolean htmlCompatiblityMode) { this.htmlCompatiblityMode = htmlCompatiblityMode; } /** * Checks, whether the XML writer should always add a namespace prefix to * the attributes. The XML specification leaves it up to the application on * how to handle unqualified attributes. If this mode is enabled, all * attributes will always be fully qualified - which removed the ambugity * but may not be compatible with simple, non namespace aware parsers. * * @return true, if all attributes should be qualified, false otherwise. */ public boolean isAlwaysAddNamespace() { return alwaysAddNamespace; } /** * Defines, whether the XML writer should always add a namespace prefix to * the attributes. The XML specification leaves it up to the application on * how to handle unqualified attributes. If this mode is enabled, all * attributes will always be fully qualified - which removed the ambugity * but may not be compatible with simple, non namespace aware parsers. * * @param alwaysAddNamespace set to true, if all attributes should be qualified, false otherwise. */ public void setAlwaysAddNamespace(final boolean alwaysAddNamespace) { this.alwaysAddNamespace = alwaysAddNamespace; } /** * Returns the indent level that should be added to the automaticly * computed indentation. * * @return the indent level. */ public int getAdditionalIndent() { return additionalIndent; } /** * Defines the indent level that should be added to the automaticly * computed indentation. * * @param additionalIndent the indent level. */ public void setAdditionalIndent(final int additionalIndent) { this.additionalIndent = additionalIndent; } /** * Returns the line separator. * * @return the line separator. */ public String getLineSeparator() { return lineSeparator; } /** * Writes an opening XML tag that has no attributes. * * @param w the writer. * @param namespaceUri the namespace URI for the element. * @param name the tag name. * @throws java.io.IOException if there is an I/O problem. */ public void writeTag(final Writer w, final String namespaceUri, final String name) throws IOException { writeTag(w, namespaceUri, name, null, XmlWriterSupport.OPEN); } /** * Writes a closing XML tag. * * @param w the writer. * @throws java.io.IOException if there is an I/O problem. */ public void writeCloseTag(final Writer w) throws IOException { indentForClose(w); final ElementLevel level = (ElementLevel) openTags.pop(); setLineEmpty(false); w.write(""); doEndOfLine(w); } /** * Writes a linebreak to the writer. * * @param writer the writer. * @throws IOException if there is a problem writing to the character stream. */ public void writeNewLine(final Writer writer) throws IOException { if (isLineEmpty() == false) { writer.write(lineSeparator); setLineEmpty(true); } } /** * Checks, whether the currently generated line of text is empty. * * @return true, if the line is empty, false otherwise. */ public boolean isLineEmpty() { return lineEmpty; } /** * A marker flag to track, wether the current line is empty. This influences the indention. * * @param lineEmpty defines, whether the current line should be treated as empty line. */ public void setLineEmpty(final boolean lineEmpty) { this.lineEmpty = lineEmpty; } /** * Writes an opening XML tag with an attribute/value pair. * * @param w the writer. * @param namespace the namespace URI for the element * @param name the tag name. * @param attributeName the attribute name. * @param attributeValue the attribute value. * @param close controls whether the tag is closed. * @throws java.io.IOException if there is an I/O problem. */ public void writeTag(final Writer w, final String namespace, final String name, final String attributeName, final String attributeValue, final boolean close) throws IOException { if (attributeName != null) { final AttributeList attr = new AttributeList(); attr.setAttribute(namespace, attributeName, attributeValue); writeTag(w, namespace, name, attr, close); } else { writeTag(w, namespace, name, null, close); } } /** * Adds an implied namespace to the document. Such a namespace is not explicitly declared, it is assumed that the * xml-parser knows the prefix by some other means. Using implied namespaces for standalone documents is almost always * a bad idea. * * @param uri the uri of the namespace. * @param prefix the defined prefix. */ public void addImpliedNamespace(final String uri, final String prefix) { if (openTags.isEmpty() == false) { throw new IllegalStateException("Cannot modify the implied namespaces in the middle of the processing"); } if (prefix == null) { if (impliedNamespaces == null) { return; } impliedNamespaces.remove(uri); } else { if (impliedNamespaces == null) { impliedNamespaces = new HashMap(); } impliedNamespaces.put(uri, prefix); } } /** * Copies all currently declared namespaces of the given XmlWriterSupport instance as new implied namespaces into this * instance. * * @param writerSupport the Xml-writer from where to copy the declared namespaces. */ public void copyNamespaces(final XmlWriterSupport writerSupport) { if (openTags.isEmpty() == false) { throw new IllegalStateException("Cannot modify the implied namespaces in the middle of the processing"); } if (impliedNamespaces == null) { impliedNamespaces = new HashMap(); } if (writerSupport.openTags.isEmpty() == false) { final ElementLevel parent = (ElementLevel) writerSupport.openTags.peek(); impliedNamespaces.putAll(parent.getNamespaces().getNamespaces()); } if (writerSupport.impliedNamespaces != null) { impliedNamespaces.putAll(writerSupport.impliedNamespaces); } } /** * Checks, whether the given URI is defined as valid namespace. * * @param uri the uri of the namespace. * @return true, if there's a namespace defined, false otherwise. */ public boolean isNamespaceDefined(final String uri) { if (impliedNamespaces != null) { if (impliedNamespaces.containsKey(uri)) { return true; } } if (openTags.isEmpty()) { return false; } final ElementLevel parent = (ElementLevel) openTags.peek(); return parent.getNamespaces().isNamespaceDefined(uri); } /** * Checks, whether the given namespace prefix is defined. * * @param prefix the namespace prefix. * @return true, if the prefix is defined, false otherwise. */ public boolean isNamespacePrefixDefined(final String prefix) { if (impliedNamespaces != null) { if (impliedNamespaces.containsValue(prefix)) { return true; } } if (openTags.isEmpty()) { return false; } final ElementLevel parent = (ElementLevel) openTags.peek(); return parent.getNamespaces().isPrefixDefined(prefix); } /** * Returns all namespaces as properties-collection. This reflects the currently defined namespaces, therefore * calls to writeOpenTag(..) might cause this method to return different collections. * * @return the defined namespaces. */ public Properties getNamespaces() { final Properties namespaces = new Properties(); if (openTags.isEmpty()) { if (impliedNamespaces != null) { //noinspection UseOfPropertiesAsHashtable namespaces.putAll(impliedNamespaces); } return namespaces; } final ElementLevel parent = (ElementLevel) openTags.peek(); //noinspection UseOfPropertiesAsHashtable namespaces.putAll(parent.getNamespaces().getNamespaces()); return namespaces; } /** * Computes the current collection of defined namespaces. * * @return the namespaces declared at this writing position. */ protected DeclaredNamespaces computeNamespaces() { if (openTags.isEmpty()) { final DeclaredNamespaces namespaces = new DeclaredNamespaces(); if (impliedNamespaces != null) { return namespaces.add(impliedNamespaces); } return namespaces; } final ElementLevel parent = (ElementLevel) openTags.peek(); return parent.getNamespaces(); } /** * Writes an opening XML tag along with a list of attribute/value pairs. * * @param w the writer. * @param namespaceUri the namespace uri for the element (can be null). * @param name the tag name. * @param attributes the attributes. * @param close controls whether the tag is closed. * @throws java.io.IOException if there is an I/O problem. */ public void writeTag(final Writer w, final String namespaceUri, final String name, final AttributeList attributes, final boolean close) throws IOException { if (name == null) { throw new NullPointerException(); } indent(w); setLineEmpty(false); DeclaredNamespaces namespaces = computeNamespaces(); if (attributes != null) { namespaces = namespaces.add(attributes); } w.write("<"); if (namespaceUri == null) { w.write(name); openTags.push(new ElementLevel(name, namespaces)); } else { final String nsPrefix = namespaces.getPrefix(namespaceUri); if (nsPrefix == null) { throw new IllegalArgumentException( "Namespace " + namespaceUri + " is not defined."); } if ("".equals(nsPrefix)) { w.write(name); openTags.push(new ElementLevel(namespaceUri, null, name, namespaces)); } else { w.write(nsPrefix); w.write(":"); w.write(name); openTags.push(new ElementLevel(namespaceUri, nsPrefix, name, namespaces)); } } if (attributes != null) { final AttributeList.AttributeEntry[] entries = attributes.toArray(); for (int i = 0; i < entries.length; i++) { final AttributeList.AttributeEntry entry = entries[i]; w.write(" "); buildAttributeName(entry, namespaces, w); w.write("=\""); writeTextNormalized(w, entry.getValue(), true); w.write("\""); } } if (close) { if (isHtmlCompatiblityMode()) { w.write(" />"); } else { w.write("/>"); } openTags.pop(); doEndOfLine(w); } else { w.write(">"); doEndOfLine(w); } } /** * Conditionally writes an end-of-line character. The End-Of-Line is only written, if the tag description indicates * that the currently open element does not expect any CDATA inside. Writing a newline for CDATA-elements may have * sideeffects. * * @param w the writer. * @throws java.io.IOException if there is an I/O problem. */ private void doEndOfLine(final Writer w) throws IOException { if (openTags.isEmpty()) { if (isWriteFinalLinebreak()) { writeNewLine(w); } } else { final ElementLevel level = (ElementLevel) openTags.peek(); if (getTagDescription().hasCData (level.getNamespace(), level.getTagName()) == false) { writeNewLine(w); } } } /** * Processes a single attribute and searches for namespace declarations. If a namespace declaration is found, it is * returned in a normalized way. If namespace processing is active, the attribute name will be fully qualified with * the prefix registered for the attribute's namespace URI. * * @param entry the attribute enty. * @param namespaces the currently known namespaces. * @param writer the writer that should receive the formatted attribute name. * @throws IOException if an IO error occured. */ private void buildAttributeName(final AttributeList.AttributeEntry entry, final DeclaredNamespaces namespaces, final Writer writer) throws IOException { final ElementLevel currentElement = (ElementLevel) openTags.peek(); final String name = entry.getName(); final String namespaceUri = entry.getNamespace(); if (isAlwaysAddNamespace() == false && ObjectUtilities.equal(currentElement.getNamespace(), namespaceUri)) { writer.write(name); return; } if (namespaceUri == null) { writer.write(name); return; } if (AttributeList.XMLNS_NAMESPACE.equals(namespaceUri)) { // its a namespace declaration. if ("".equals(name)) { writer.write("xmlns"); return; } writer.write("xmlns:"); writer.write(name); return; } final String namespacePrefix = namespaces.getPrefix(namespaceUri); if (namespacePrefix != null && "".equals(namespacePrefix) == false) { writer.write(namespacePrefix); writer.write(':'); writer.write(name); } else { writer.write(name); } } /** * Normalizes the given string using a shared buffer. * * @param s the string that should be XML-Encoded. * @param transformNewLine a flag controling whether to transform newlines into character-entities. * @return the transformed string. */ public String normalizeLocal(final String s, final boolean transformNewLine) { if (s == null) { return ""; } normalizeBuffer.delete(0, normalizeBuffer.length()); final int len = s.length(); for (int i = 0; i < len; i++) { final char ch = s.charAt(i); switch (ch) { case '<': { normalizeBuffer.append("<"); break; } case '>': { normalizeBuffer.append(">"); break; } case '&': { normalizeBuffer.append("&"); break; } case '"': { normalizeBuffer.append("""); break; } case '\n': { if (transformNewLine) { normalizeBuffer.append(" "); } else { normalizeBuffer.append('\n'); } break; } case '\r': { if (transformNewLine) { normalizeBuffer.append(" "); } else { normalizeBuffer.append('\r'); } break; } case 0x09: { normalizeBuffer.append(ch); break; } default: { if (ch >= 0x20) { normalizeBuffer.append(ch); } } } } final String retval = normalizeBuffer.toString(); normalizeBuffer.delete(0, normalizeBuffer.length()); return retval; } /** * Normalizes the given string and writes the result directly to the stream. * * @param writer the writer that should receive the normalized content. * @param s the string that should be XML-Encoded. * @param transformNewLine a flag controling whether to transform newlines into character-entities. * @throws IOException if writing to the stream failed. */ public void writeTextNormalized(final Writer writer, final String s, final boolean transformNewLine) throws IOException { if (s == null) { return; } final char[] data = s.toCharArray(); final int len = data.length; int startIdx = 0; int length = 0; for (int i = 0; i < len; i++) { final char ch = data[i]; switch (ch) { case '<': { if (length != 0) { writer.write(data, startIdx, length); length = 0; } writer.write("<"); startIdx = i + 1; continue; } case '>': { if (length != 0) { writer.write(data, startIdx, length); length = 0; } writer.write(">"); startIdx = i + 1; continue; } case '&': { if (length != 0) { writer.write(data, startIdx, length); length = 0; } writer.write("&"); startIdx = i + 1; continue; } case '"': { if (length != 0) { writer.write(data, startIdx, length); length = 0; } writer.write("""); startIdx = i + 1; continue; } case '\n': { if (transformNewLine) { if (length != 0) { writer.write(data, startIdx, length); length = 0; } writer.write(" "); startIdx = i + 1; continue; } break; } case '\r': { if (transformNewLine) { if (length != 0) { writer.write(data, startIdx, length); length = 0; } writer.write(" "); startIdx = i + 1; continue; } break; } case 0x09: // tab { break; } default: { if (ch >= 0x20) { // anything above the control-character range is ok. break; } // skip .. if (length != 0) { writer.write(data, startIdx, length); length = 0; } startIdx = i + 1; continue; } } length += 1; } if (length != 0) { writer.write(data, startIdx, length); } } /** * Normalises a string, replacing certain characters with their escape sequences so that the XML text is not * corrupted. * * @param s the string. * @param transformNewLine true, if a newline in the string should be converted into a character entity. * @return the normalised string. */ public static String normalize(final String s, final boolean transformNewLine) { if (s == null) { return ""; } final int len = s.length(); final StringBuffer str = new StringBuffer(len); for (int i = 0; i < len; i++) { final char ch = s.charAt(i); switch (ch) { case '<': { str.append("<"); break; } case '>': { str.append(">"); break; } case '&': { str.append("&"); break; } case '"': { str.append("""); break; } case '\n': { if (transformNewLine) { str.append(" "); } else { str.append('\n'); } break; } case '\r': { if (transformNewLine) { str.append(" "); } else { str.append('\r'); } break; } case 0x09: // tab { str.append((char) 0x09); } default: { if (ch >= 0x20) { str.append(ch); } } } } return (str.toString()); } /** * Indent the line. Called for proper indenting in various places. * * @param writer the writer which should receive the indentention. * @throws java.io.IOException if writing the stream failed. */ public void indent(final Writer writer) throws IOException { if (openTags.isEmpty()) { for (int i = 0; i < additionalIndent; i++) { writer.write(this.indentString); } return; } final ElementLevel level = (ElementLevel) openTags.peek(); if (getTagDescription().hasCData(level.getNamespace(), level.getTagName()) == false) { doEndOfLine(writer); for (int i = 0; i < this.openTags.size(); i++) { writer.write(this.indentString); } for (int i = 0; i < additionalIndent; i++) { writer.write(this.indentString); } } } /** * Indent the line. Called for proper indenting in various places. * * @param writer the writer which should receive the indentention. * @throws java.io.IOException if writing the stream failed. */ public void indentForClose(final Writer writer) throws IOException { if (openTags.isEmpty()) { for (int i = 0; i < additionalIndent; i++) { writer.write(this.indentString); } return; } final ElementLevel level = (ElementLevel) openTags.peek(); if (getTagDescription().hasCData(level.getNamespace(), level.getTagName()) == false) { doEndOfLine(writer); for (int i = 1; i < this.openTags.size(); i++) { writer.write(this.indentString); } for (int i = 0; i < additionalIndent; i++) { writer.write(this.indentString); } } } /** * Returns the list of safe tags. * * @return The list. */ public TagDescription getTagDescription() { return this.safeTags; } /** * Writes a comment into the generated xml file. * * @param writer the writer. * @param comment the comment text * @throws IOException if there is a problem writing to the character stream. */ public void writeComment(final Writer writer, final String comment) throws IOException { if (openTags.isEmpty() == false) { final ElementLevel level = (ElementLevel) openTags.peek(); if (getTagDescription().hasCData (level.getNamespace(), level.getTagName()) == false) { indent(writer); } } setLineEmpty(false); writer.write(""); doEndOfLine(writer); } /** * Checks, whether attributes of the same namespace as the current element should be written without a prefix. * Attributes without a prefix are considered to be not in any namespace at all. How to treat such attributes is * implementation dependent. (Appendix A; Section 6.2 of the XmlNamespaces recommendation) * * @return true, if attributes in the element's namespace should be written without a prefix, false to write all * attributes with a prefix. */ public boolean isAssumeDefaultNamespace() { return assumeDefaultNamespace; } /** * Defines, whether attributes of the same namespace as the current element should be written without a prefix. * Attributes without a prefix are considered to be not in any namespace at all. How to treat such attributes is * implementation dependent. (Appendix A; Section 6.2 of the XmlNamespaces recommendation) * * @param assumeDefaultNamespace true, if attributes in the element's namespace should be written without a prefix, * false to write all attributes with a prefix. */ public void setAssumeDefaultNamespace(final boolean assumeDefaultNamespace) { this.assumeDefaultNamespace = assumeDefaultNamespace; } /** * Returns the current indention level. * * @return the indention level. */ public int getCurrentIndentLevel() { return additionalIndent + openTags.size(); } /** * Defines, whether the written XML file should end with an empty line. * * @param writeFinalLinebreak true, if an linebreak should be added at the * end of the file, false otherwise. */ public void setWriteFinalLinebreak(final boolean writeFinalLinebreak) { this.writeFinalLinebreak = writeFinalLinebreak; } /** * Checks, whether the written XML file should end with an empty line. * * @return true, if an linebreak should be added at the * end of the file, false otherwise. */ public boolean isWriteFinalLinebreak() { return writeFinalLinebreak; } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/writer/DeclaredNamespaces.java0000644000175000017500000001521311365606150031133 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.writer; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.pentaho.reporting.libraries.xmlns.common.AttributeList; /** * A immutable namespace collection. Any attempt to modify the declared namespaces creates a new copy of the map. * * @author Thomas Morgner */ public final class DeclaredNamespaces { private HashMap namespaces; /** * Creates a new namespaces collection. */ public DeclaredNamespaces() { } /** * Creates a new namespaces collection using the given namespaces as initial values. * * @param namespaces the namespaces, never null. */ public DeclaredNamespaces(final DeclaredNamespaces namespaces) { if (namespaces == null) { throw new NullPointerException(); } if (namespaces.namespaces != null) { this.namespaces = (HashMap) namespaces.namespaces.clone(); } } /** * Adds all namespaces from the given hashmap into this map. The namespaces map must only contain string keys and * string values and must not contain either null-keys or null-values. * * @param newNamespaces the namespaces collection. * @return the created namespaces object. */ public DeclaredNamespaces add(final HashMap newNamespaces) { if (newNamespaces == null) { throw new NullPointerException(); } final DeclaredNamespaces retval = new DeclaredNamespaces(); if (this.namespaces == null) { retval.namespaces = new HashMap(); } else { retval.namespaces = (HashMap) this.namespaces.clone(); } final Iterator iterator = newNamespaces.entrySet().iterator(); while (iterator.hasNext()) { final Map.Entry entry = (Map.Entry) iterator.next(); final String value = (String) entry.getValue(); final String o = (String) entry.getKey(); if (value == null || o == null) { throw new NullPointerException(); } retval.namespaces.put(o, value); } return retval; } /** * Adds all declared namespaces from the given attribute-list into the namespaces collection. * * @param attributes the attribute list containing namespace definitions. * @return the new namespaces collection. */ public DeclaredNamespaces add(final AttributeList attributes) { if (attributes == null) { throw new NullPointerException(); } DeclaredNamespaces retval = null; final AttributeList.AttributeEntry[] entries = attributes.toArray(); for (int i = 0; i < entries.length; i++) { final AttributeList.AttributeEntry entry = entries[i]; final String prefix = entry.getName(); if ("xmlns".equals(prefix)) { if (entry.getNamespace() == null || "".equals(entry.getNamespace())) { if (retval == null) { retval = new DeclaredNamespaces(); if (namespaces != null) { retval.namespaces = (HashMap) namespaces.clone(); } else { retval.namespaces = new HashMap(); } } retval.namespaces.put(entry.getValue(), ""); } } else if (AttributeList.XMLNS_NAMESPACE.equals(entry.getNamespace())) { if (retval == null) { retval = new DeclaredNamespaces(); if (namespaces != null) { retval.namespaces = (HashMap) namespaces.clone(); } else { retval.namespaces = new HashMap(); } } retval.namespaces.put(entry.getValue(), prefix); } } if (retval == null) { return this; } return retval; } /** * Adds a single namespace definition to the collection. * * @param uri the URI of the namespace. * @param prefix the prefix to be used for the namespace. * @return the new namespaces collection. */ public DeclaredNamespaces add(final String uri, final String prefix) { if (uri == null) { throw new NullPointerException(); } if (prefix == null) { throw new NullPointerException(); } final DeclaredNamespaces retval = new DeclaredNamespaces(); if (namespaces == null) { retval.namespaces = new HashMap(); } else { retval.namespaces = (HashMap) namespaces.clone(); } retval.namespaces.put(uri, prefix); return retval; } /** * Looksup the prefix for the given URI. This returns null if the URI is not a declared namespace. * * @param uri the URI. * @return the prefix for the given URI or null, if the URI is not part of this collection. */ public String getPrefix(final String uri) { if (uri == null) { throw new NullPointerException(); } if (namespaces == null) { return null; } return (String) namespaces.get(uri); } /** * Checks, whether the namespace marked by the given URI is defined in this collection. * * @param uri the URI to be checked. * @return true, if the URI is known, false otherwise. */ public boolean isNamespaceDefined(final String uri) { if (uri == null) { throw new NullPointerException(); } if (namespaces == null) { return false; } return namespaces.containsKey(uri); } /** * Returns all known namespaces as unmodifiable map. * * @return the namespaces. */ public Map getNamespaces() { return Collections.unmodifiableMap(namespaces); } /** * Checks whether the given prefix is already defined in the collection. * * @param prefix the prefix. * @return true, if the prefix is already used, false otherwise. */ public boolean isPrefixDefined(final String prefix) { return namespaces.containsValue(prefix); } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/writer/NamespaceCollection.java0000644000175000017500000000564611365606150031351 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.writer; import java.util.HashMap; import java.util.Iterator; import org.pentaho.reporting.libraries.base.config.Configuration; /** * Holds a set of namespace definitions that have been declared in a libbase-configuration. * * @author Thomas Morgner */ public class NamespaceCollection { private HashMap entries; /** * Default constructor. */ public NamespaceCollection() { entries = new HashMap(); } /** * Configures the namespace collection and adds all namespace definitions found in the configuration under * the given prefix to the collection. * * @param config the configuration from where to read the namespaces. * @param prefix the configuration prefix for filtering the configuration entries. */ public void configure(final Configuration config, final String prefix) { final Iterator keys = config.findPropertyKeys(prefix); while (keys.hasNext()) { final String key = (String) keys.next(); if (key.endsWith(".Uri") == false) { continue; } final String nsPrefix = key.substring(0, key.length() - 3); final String uri = config.getConfigProperty(key); if (uri == null) { continue; } final String trimmedUri = uri.trim(); if (trimmedUri.length() == 0) { continue; } final String prefixAttr = config.getConfigProperty(nsPrefix + "Prefix"); if (prefixAttr != null) { entries.put(trimmedUri, prefixAttr); } } } /** * Returns the prefered namespace prefix for the given namespace URI. * * @param uri the namespace for which a prefix should be looked up. * @return the defined prefix. */ public String getPrefix(final String uri) { return (String) entries.get(uri); } /** * Returns all known namespaces for which definitions exist in this collection. * * @return the defined uris as array. */ public String[] getDefinedUris() { return (String[]) entries.keySet().toArray(new String[entries.size()]); } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/writer/TagDescription.java0000644000175000017500000000273611365606150030355 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.writer; /** * A tag-description provides information about xml tags. At the moment, we * simply care whether an element can contain CDATA. In such cases, we do not * indent the inner elements. * * @author Thomas Morgner */ public interface TagDescription { /** * Checks, whether the element specified by the tagname and namespace can * contain CDATA. * * @param namespace the namespace (as URI) * @param tagname the tagname * @return true, if the element can contain CDATA, false otherwise */ boolean hasCData(String namespace, String tagname); } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/writer/DefaultTagDescription.java0000644000175000017500000002203411365606150031653 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.writer; import java.util.HashMap; import java.util.Iterator; import org.pentaho.reporting.libraries.base.config.Configuration; /** * A tag-description provides information about xml tags. At the moment, we * simply care whether an element can contain CDATA. In such cases, we do not * indent the inner elements. * * @author Thomas Morgner */ public class DefaultTagDescription implements TagDescription { /** * The TagDefinitionKey is a compund key to lookup tag-specifications * using a namespace and tagname. */ private static class TagDefinitionKey { private String namespace; private String tagName; /** * Creates a new key. * * @param namespace the namespace (can be null for undefined). * @param tagName the tagname (can be null for undefined). */ private TagDefinitionKey(final String namespace, final String tagName) { this.namespace = namespace; this.tagName = tagName; } /** * Updates the internal state for the tag-definition lookup-key. Calling this on a non-lookup key will * give funny and unpredictable results. * * @param namespace the namespace of the key. * @param tagName the tagname. */ public void update(final String namespace, final String tagName) { this.namespace = namespace; this.tagName = tagName; } /** * Compares this key for equality with an other object. * * @param o the other object. * @return true, if this key is the same as the given object, false otherwise. */ public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final TagDefinitionKey that = (TagDefinitionKey) o; if (namespace != null ? !namespace.equals(that.namespace) : that.namespace != null) { return false; } if (tagName != null ? !tagName.equals(that.tagName) : that.tagName != null) { return false; } return true; } public int hashCode() { int result = (namespace != null ? namespace.hashCode() : 0); result = 29 * result + (tagName != null ? tagName.hashCode() : 0); return result; } /** * Computes the hashcode for this key. * * @return the hashcode. */ public String toString() { return "TagDefinitionKey{" + "namespace='" + namespace + '\'' + ", tagName='" + tagName + '\'' + '}'; } } private HashMap defaultDefinitions; private HashMap tagData; private String defaultNamespace; private TagDefinitionKey lookupKey; /** * A default-constructor. */ public DefaultTagDescription() { defaultDefinitions = new HashMap(); tagData = new HashMap(); lookupKey = new TagDefinitionKey(null, null); } /** * Creates and configures a new TagDescription collection. * * @param conf the configuration. * @param prefix the key-prefix. * @see #configure(Configuration, String) */ public DefaultTagDescription(final Configuration conf, final String prefix) { this(); configure(conf, prefix); } /** * Configures this factory from the given configuration using the speoified * prefix as filter. * * @param conf the configuration. * @param prefix the key-prefix. * @noinspection ObjectAllocationInLoop as this is a factory configuration method. */ public void configure(final Configuration conf, final String prefix) { if (conf == null) { throw new NullPointerException(); } if (prefix == null) { throw new NullPointerException(); } final HashMap knownNamespaces = new HashMap(); final String nsConfPrefix = prefix + "namespace."; final Iterator namespaces = conf.findPropertyKeys(nsConfPrefix); while (namespaces.hasNext()) { final String key = (String) namespaces.next(); final String nsPrefix = key.substring(nsConfPrefix.length()); final String nsUri = conf.getConfigProperty(key); knownNamespaces.put(nsPrefix, nsUri); } defaultNamespace = (String) knownNamespaces.get (conf.getConfigProperty(prefix + "namespace")); final String globalDefaultKey = prefix + "default"; final boolean globalValue = "allow".equals(conf.getConfigProperty(globalDefaultKey)) == false; defaultDefinitions.put(null, (globalValue) ? Boolean.TRUE : Boolean.FALSE); final String nsDefaultPrefix = prefix + "default."; final Iterator defaults = conf.findPropertyKeys(nsDefaultPrefix); while (defaults.hasNext()) { final String key = (String) defaults.next(); final String nsPrefix = key.substring(nsDefaultPrefix.length()); final String nsUri = (String) knownNamespaces.get(nsPrefix); if (nsUri == null) { continue; } final boolean value = "allow".equals(conf.getConfigProperty(key)) == false; defaultDefinitions.put(nsUri, (value) ? Boolean.TRUE : Boolean.FALSE); } final String nsTagsPrefix = prefix + "tag."; final Iterator tags = conf.findPropertyKeys(nsTagsPrefix); while (tags.hasNext()) { final String key = (String) tags.next(); final String tagDef = key.substring(nsTagsPrefix.length()); final boolean value = "allow".equals(conf.getConfigProperty(key)) == false; final int delim = tagDef.indexOf('.'); if (delim == -1) { tagData.put(new TagDefinitionKey(null, tagDef), (value) ? Boolean.TRUE : Boolean.FALSE); } else { final String nsPrefix = tagDef.substring(0, delim); final String nsUri = (String) knownNamespaces.get(nsPrefix); if (nsUri == null) { continue; } final String tagName = tagDef.substring(delim + 1); tagData.put(new TagDefinitionKey(nsUri, tagName), (value) ? Boolean.TRUE : Boolean.FALSE); } } } /** * Adds a configuration default for the given namespace to the tag-descriptions. If the namespace URI given * here is null, this defines the global default for all namespaces. * * @param namespaceUri the namespace URI for which a default should be configured. * @param hasCData the default value. */ public void addDefaultDefinition(final String namespaceUri, final boolean hasCData) { defaultDefinitions.put(namespaceUri, hasCData ? Boolean.TRUE : Boolean.FALSE); } /** * Adds a configuration entry for the given namespace and tag-name to the tag-descriptions. * * @param namespaceUri the namespace URI for which a default should be configured. * @param tagName the tagname for which the entry should be added. * @param hasCData the default value. */ public void addTagDefinition(final String namespaceUri, final String tagName, final boolean hasCData) { if (namespaceUri == null) { throw new NullPointerException(); } if (tagName == null) { throw new NullPointerException(); } tagData.put(new TagDefinitionKey(namespaceUri, tagName), hasCData ? Boolean.TRUE : Boolean.FALSE); } /** * Queries the defined tag-descriptions whether the given tag and namespace * is defined to allow character-data. * * @param namespace the namespace. * @param tagname the xml-tagname. * @return true, if the element may contain character data, false otherwise. */ public boolean hasCData(String namespace, final String tagname) { if (tagname == null) { throw new NullPointerException(); } if (namespace == null) { namespace = defaultNamespace; } if (tagData.isEmpty() == false) { lookupKey.update(namespace, tagname); final Object tagVal = tagData.get(lookupKey); if (tagVal != null) { return Boolean.FALSE.equals(tagVal) == false; } } if (defaultDefinitions.isEmpty()) { return true; } final Object obj = defaultDefinitions.get(namespace); if (obj != null) { return Boolean.FALSE.equals(obj) == false; } final Object defaultValue = defaultDefinitions.get(null); return Boolean.FALSE.equals(defaultValue) == false; } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/writer/sample.properties0000644000175000017500000000061511365606150030164 0ustar renerene# # Copyright (c) 2007, Pentaho Corporation. All Rights Reserved. # # # A sample file demonstrating the format of the tag-description # database namespace.html=schema://namespace.url/ default.html=deny # # For each tag, define if it is allowed to indent the children or if it # does not allowed (deny). # # For tags not listed, we assume the default. tag.html.paragraph=deny tag.html.img=allow libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/writer/CharacterEntityParser.java0000644000175000017500000001666211365606150031707 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.writer; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; /** * The character entity parser replaces all known occurrences of an entity in * the format &entityname;. * * @author Thomas Morgner */ public class CharacterEntityParser { private String[] charMap; /** * the entities, keyed by entity name. */ private final HashMap entities; /** * Creates a new CharacterEntityParser and initializes the parser with the * given set of entities. * * @param characterEntities the entities used for the parser */ public CharacterEntityParser(final Properties characterEntities) { if (characterEntities == null) { throw new NullPointerException("CharacterEntities must not be null"); } entities = new HashMap(characterEntities); charMap = new String[65536]; final Iterator entries = entities.entrySet().iterator(); while (entries.hasNext()) { final Map.Entry entry = (Map.Entry) entries.next(); final String value = (String) entry.getValue(); final String entityName = (String) entry.getKey(); if (value.length() != 1) { throw new IllegalStateException(); } charMap[value.charAt(0)] = entityName; } } /** * Creates a new CharacterEntityParser and initializes the parser with the * given set of entities. * * @param characterEntities the entities used for the parser */ public CharacterEntityParser(final HashMap characterEntities) { if (characterEntities == null) { throw new NullPointerException("CharacterEntities must not be null"); } entities = (HashMap) characterEntities.clone(); charMap = new String[65536]; final Iterator entries = entities.entrySet().iterator(); while (entries.hasNext()) { final Map.Entry entry = (Map.Entry) entries.next(); final String value = (String) entry.getValue(); final String entityName = (String) entry.getKey(); if (value.length() != 1) { throw new IllegalStateException(); } charMap[value.charAt(0)] = entityName; } } /** * create a new Character entity parser and initializes the parser with the * entities defined in the XML standard. * * @return the CharacterEntityParser initialized with XML entities. */ public static CharacterEntityParser createXMLEntityParser() { final HashMap entities = new HashMap(); entities.put("amp", "&"); entities.put("quot", "\""); entities.put("lt", "<"); entities.put("gt", ">"); entities.put("apos", "\u0027"); return new CharacterEntityParser(entities); } /** * returns the entities used in the parser. * * @return the properties for this parser. */ private HashMap getEntities() { return entities; } /** * Looks up the character for the entity name specified in key. * * @param key the entity name * @return the character as string with a length of 1 */ private String lookupCharacter(final String key) { return (String) getEntities().get(key); } /** * Encode the given String, so that all known entites are encoded. All * characters represented by these entites are now removed from the string. * * @param value the original string * @return the encoded string. */ public String encodeEntities(final String value) { if (value == null) { throw new NullPointerException(); } final int length = value.length(); final StringBuffer writer = new StringBuffer(length); for (int i = 0; i < length; i++) { final char character = value.charAt(i); final String lookup = charMap[character]; if (lookup == null) { writer.append(character); } else { writer.append('&'); writer.append(lookup); writer.append(';'); } } return writer.toString(); } /** * Decode the string, all known entities are replaced by their resolved * characters. * * @param value the string that should be decoded. * @return the decoded string. */ public String decodeEntities(final String value) { if (value == null) { throw new NullPointerException(); } int parserIndex = 0; int subStart = value.indexOf('&', parserIndex); if (subStart == -1) { return value; } int subEnd = value.indexOf(';', subStart); if (subEnd == -1) { return value; } final StringBuffer bufValue = new StringBuffer(value.substring(0, subStart)); do { // at this point we know, that there is at least one entity .. if (value.charAt(subStart + 1) == '#') { final int subValue = parseInt(value.substring(subStart + 2, subEnd), 0); if ((subValue >= 1) && (subValue <= 65536)) { final char[] chr = new char[1]; chr[0] = (char) subValue; bufValue.append(chr); } else { // invalid entity, do not decode .. bufValue.append(value.substring(subStart, subEnd)); } } else { final String entity = value.substring(subStart + 1, subEnd); final String replaceString = lookupCharacter(entity); if (replaceString != null) { bufValue.append(decodeEntities(replaceString)); } else { bufValue.append('&'); bufValue.append(entity); bufValue.append(';'); } } parserIndex = subEnd + 1; subStart = value.indexOf('&', parserIndex); if (subStart == -1) { bufValue.append(value.substring(parserIndex)); subEnd = -1; } else { subEnd = value.indexOf(';', subStart); if (subEnd == -1) { bufValue.append(value.substring(parserIndex)); } else { bufValue.append(value.substring(parserIndex, subStart)); } } } while (subStart != -1 && subEnd != -1); return bufValue.toString(); } /** * Parses the given string into an int-value. On errors the default value * is returned. * * @param s the string * @param defaultVal the default value that should be used in case of errors * @return the parsed int or the default value. */ private int parseInt(final String s, final int defaultVal) { if (s == null) { return defaultVal; } try { return Integer.parseInt(s); } catch (Exception e) { // ignored .. } return defaultVal; } } libxml-java-1.1.6/source/org/pentaho/reporting/libraries/xmlns/LibXmlInfo.java0000644000175000017500000000474711365606150026131 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns; import org.pentaho.reporting.libraries.resourceloader.LibLoaderInfo; import org.pentaho.reporting.libraries.base.LibBaseInfo; import org.pentaho.reporting.libraries.base.versioning.ProjectInformation; /** * The LibXmlInfo class contains all dependency information and some * common information like version, license and contributors about the * library itself. * * @author Thomas Morgner */ public class LibXmlInfo extends ProjectInformation { /** * The XML-Namespace is used for the 'id' attribute. */ public static final String XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace"; /** * The XML-Namespace is used for the 'id' attribute. */ public static final String XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; private static LibXmlInfo info; /** * Constructs an empty project info object. */ private LibXmlInfo() { super("libxml", "LibXML"); } /** * Initialized the project info object. */ private void initialize() { setInfo("http://reporting.pentaho.org/libxml/"); setCopyright("(C)opyright 2007-2010, by Object Refinery Limited, Pentaho Corporation and Contributors"); setLicenseName("LGPL"); addLibrary(LibBaseInfo.getInstance()); addLibrary(LibLoaderInfo.getInstance()); setBootClass(LibXmlBoot.class.getName()); } /** * Returns the singleton instance of the info-class. * * @return the singleton info. */ public static synchronized ProjectInformation getInstance() { if (info == null) { info = new LibXmlInfo(); info.initialize(); } return info; } } libxml-java-1.1.6/README.txt0000644000175000017500000000400511365606150014071 0ustar renerene************************ * LibXML 0.99.0 * ************************ 30 May 2008 1. INTRODUCTION --------------- LibXML is a namespace aware SAX-Parser utility library. It eases the pain of implementing non-trivial SAX input handlers. The original code of these classes had been written by Peter Becker for the JCommon library. LibXML replaces the JCommon-XML classes, which were not namespace aware. Due to JCommons frozen API, namespace awareness could not be added to the original code without creating a mess. For the latest news and information about libXML, please refer to: http://reporting.pentaho.org/libxml/ 2. SUPPORT ---------- Free support is available via the JFreeReport forum, follow the link from the LibXml home page. Please note that questions are answered by volunteers, so there is no guaranteed response time or level of service. Please avoid e-mailing the developers directly for support questions. If you post a message in the forum, then everyone can see the question, and everyone can see the answer. 3. REPORTING BUGS ----------------- If you find bugs in LibXml, we'd like to hear about it so that we can improve future releases of LibXml. Please post a bug report to the JIRA bug-tracker at Pentaho.org: http://jira.pentaho.org/ Please be sure to provide as much information as you can. We need to know the version of LibXml that you are using, the JDK version, and the steps required to replicate the bug. Include any other information that you think is relevant. 4. ANT ------ We use an open source build tool called Ant to build LibXml. An Ant script (tested using Ant 1.6) is included in the distribution: /ant/build.xml You can find out more about Ant at: http://ant.apache.org/ Ant is licensed under the terms of the Apache Software License (a popular open source software license). 5. OTHER FEEDBACK ----------------- For other feedback and comments, please post a message on the Pentaho forums. The Forum is available at http://forums.pentaho.org/ libxml-java-1.1.6/ivy.xml0000644000175000017500000000236511365606150013733 0ustar renerene libxml-java-1.1.6/test-lib/0000755000175000017500000000000011640445372014122 5ustar renerenelibxml-java-1.1.6/lib/0000755000175000017500000000000011636144620013142 5ustar renerenelibxml-java-1.1.6/test/0000755000175000017500000000000011365606146013360 5ustar renerenelibxml-java-1.1.6/test/org/0000755000175000017500000000000011365606146014147 5ustar renerenelibxml-java-1.1.6/test/org/pentaho/0000755000175000017500000000000011365606146015605 5ustar renerenelibxml-java-1.1.6/test/org/pentaho/reporting/0000755000175000017500000000000011365606146017616 5ustar renerenelibxml-java-1.1.6/test/org/pentaho/reporting/libraries/0000755000175000017500000000000011365606146021572 5ustar renerenelibxml-java-1.1.6/test/org/pentaho/reporting/libraries/xmlns/0000755000175000017500000000000011365606146022733 5ustar renerenelibxml-java-1.1.6/test/org/pentaho/reporting/libraries/xmlns/writer/0000755000175000017500000000000011365606146024247 5ustar renerenelibxml-java-1.1.6/test/org/pentaho/reporting/libraries/xmlns/writer/DefaultTagDescriptionTest.java0000644000175000017500000000267411365606146032207 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.writer; import org.pentaho.reporting.libraries.base.config.DefaultConfiguration; import junit.framework.TestCase; /** * Todo: Document Me * * @author Thomas Morgner */ public class DefaultTagDescriptionTest extends TestCase { public DefaultTagDescriptionTest() { } public DefaultTagDescriptionTest(final String s) { super(s); } public void testSillyTag() { final DefaultTagDescription dt = new DefaultTagDescription(new DefaultConfiguration(), "silly-prefix"); assertFalse(dt.hasCData("basas", "adsda")); } } libxml-java-1.1.6/test/org/pentaho/reporting/libraries/xmlns/writer/XmlWriterSupportTest.java0000644000175000017500000000531311365606146031306 0ustar renerene/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2009 Object Refinery Ltd, Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.xmlns.writer; import java.io.StringWriter; import java.io.IOException; import junit.framework.TestCase; /** * Todo: Document Me * * @author Thomas Morgner */ public class XmlWriterSupportTest extends TestCase { public XmlWriterSupportTest() { } public XmlWriterSupportTest(final String s) { super(s); } public void testEncoding() throws IOException { final StringWriter writer1 = new StringWriter(); final StringWriter writer2 = new StringWriter(); final StringWriter writer3 = new StringWriter(); final StringWriter writer4 = new StringWriter(); final StringWriter writer5 = new StringWriter(); final StringWriter writer6 = new StringWriter(); final XmlWriterSupport support = new XmlWriterSupport(new DefaultTagDescription(), ""); support.writeTextNormalized(writer1, "Some text to make me happy", false); support.writeTextNormalized(writer2, "Some &to; make me happy", false); support.writeTextNormalized(writer3, "Some <>make me happy", false); support.writeTextNormalized(writer4, "Some \n>text to <\rmake me happy", false); support.writeTextNormalized(writer5, "Some \n>text to <\rmake me happy", true); support.writeTextNormalized(writer6, "Some \\d>text to \\windows\\path <\rmake me happy", true); assertEquals(writer1.toString(), "Some text to make me happy"); assertEquals(writer2.toString(), "Some <text> &to; make me happy"); assertEquals(writer3.toString(), "Some <<text to >>make me happy"); assertEquals(writer4.toString(), "Some \n" + ">text to <\r" + "make me happy"); assertEquals(writer5.toString(), "Some >text to < make me happy"); assertEquals(writer6.toString(), "Some \\d>text to \\windows\\path < make me happy"); } } libxml-java-1.1.6/.classpath0000644000175000017500000000146611365606146014373 0ustar renerene libxml-java-1.1.6/build.xml0000644000175000017500000000323211365606150014215 0ustar renerene This build file is used to create the libformula project and works with the common_build.xml file.