pax_global_header00006660000000000000000000000064115714211120014505gustar00rootroot0000000000000052 comment=93476ed878c995c046b74d78bbb2ddb739189ccd txw2-0.1+20070624/000077500000000000000000000000001157142111200131515ustar00rootroot00000000000000txw2-0.1+20070624/build.xml000066400000000000000000000151741157142111200150020ustar00rootroot00000000000000 The 'version' property needs to be defined The 'version' property needs to be defined 4.0.0 com.sun.xml.txw2 @{artifactId} jar ${version} ]]> txw2-0.1+20070624/doc/000077500000000000000000000000001157142111200137165ustar00rootroot00000000000000txw2-0.1+20070624/doc/license.txt000066400000000000000000000473011157142111200161060ustar00rootroot00000000000000COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 1. Definitions. 1.1. "Contributor" means each individual or entity that creates or contributes to the creation of Modifications. 1.2. "Contributor Version" means the combination of the Original Software, prior Modifications used by a Contributor (if any), and the Modifications made by that particular Contributor. 1.3. "Covered Software" means (a) the Original Software, or (b) Modifications, or (c) the combination of files containing Original Software with files containing Modifications, in each case including portions thereof. 1.4. "Executable" means the Covered Software in any form other than Source Code. 1.5. "Initial Developer" means the individual or entity that first makes Original Software available under this License. 1.6. "Larger Work" means a work which combines Covered Software or portions thereof with code not governed by the terms of this License. 1.7. "License" means this document. 1.8. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein. 1.9. "Modifications" means the Source Code and Executable form of any of the following: A. Any file that results from an addition to, deletion from or modification of the contents of a file containing Original Software or previous Modifications; B. Any new file that contains any part of the Original Software or previous Modification; or C. Any new file that is contributed or otherwise made available under the terms of this License. 1.10. "Original Software" means the Source Code and Executable form of computer software code that is originally released under this License. 1.11. "Patent Claims" means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor. 1.12. "Source Code" means (a) the common form of computer software code in which modifications are made and (b) associated documentation included in or with such code. 1.13. "You" (or "Your") means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants. 2.1. The Initial Developer Grant. Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, the Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer, to use, reproduce, modify, display, perform, sublicense and distribute the Original Software (or portions thereof), with or without Modifications, and/or as part of a Larger Work; and (b) under Patent Claims infringed by the making, using or selling of Original Software, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Software (or portions thereof). (c) The licenses granted in Sections 2.1(a) and (b) are effective on the date Initial Developer first distributes or otherwise makes the Original Software available to a third party under the terms of this License. (d) Notwithstanding Section 2.1(b) above, no patent license is granted: (1) for code that You delete from the Original Software, or (2) for infringements caused by: (i) the modification of the Original Software, or (ii) the combination of the Original Software with other software or devices. 2.2. Contributor Grant. Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by Contributor to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof), either on an unmodified basis, with other Modifications, as Covered Software and/or as part of a Larger Work; and (b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: (1) Modifications made by that Contributor (or portions thereof); and (2) the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination). (c) The licenses granted in Sections 2.2(a) and 2.2(b) are effective on the date Contributor first distributes or otherwise makes the Modifications available to a third party. (d) Notwithstanding Section 2.2(b) above, no patent license is granted: (1) for any code that Contributor has deleted from the Contributor Version; (2) for infringements caused by: (i) third party modifications of Contributor Version, or (ii) the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or (3) under Patent Claims infringed by Covered Software in the absence of Modifications made by that Contributor. 3. Distribution Obligations. 3.1. Availability of Source Code. Any Covered Software that You distribute or otherwise make available in Executable form must also be made available in Source Code form and that Source Code form must be distributed only under the terms of this License. You must include a copy of this License with every copy of the Source Code form of the Covered Software You distribute or otherwise make available. You must inform recipients of any such Covered Software in Executable form as to how they can obtain such Covered Software in Source Code form in a reasonable manner on or through a medium customarily used for software exchange. 3.2. Modifications. The Modifications that You create or to which You contribute are governed by the terms of this License. You represent that You believe Your Modifications are Your original creation(s) and/or You have sufficient rights to grant the rights conveyed by this License. 3.3. Required Notices. You must include a notice in each of Your Modifications that identifies You as the Contributor of the Modification. You may not remove or alter any copyright, patent or trademark notices contained within the Covered Software, or any notices of licensing or any descriptive text giving attribution to any Contributor or the Initial Developer. 3.4. Application of Additional Terms. You may not offer or impose any terms on any Covered Software in Source Code form that alters or restricts the applicable version of this License or the recipientsÕ rights hereunder. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, you may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear that any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer. 3.5. Distribution of Executable Versions. You may distribute the Executable form of the Covered Software under the terms of this License or under the terms of a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable form does not attempt to limit or alter the recipientÕs rights in the Source Code form from the rights set forth in this License. If You distribute the Covered Software in Executable form under a different license, You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer or Contributor. You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of any such terms You offer. 3.6. Larger Works. You may create a Larger Work by combining Covered Software with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Software. 4. Versions of the License. 4.1. New Versions. Sun Microsystems, Inc. is the initial license steward and may publish revised and/or new versions of this License from time to time. Each version will be given a distinguishing version number. Except as provided in Section 4.3, no one other than the license steward has the right to modify this License. 4.2. Effect of New Versions. You may always continue to use, distribute or otherwise make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. If the Initial Developer includes a notice in the Original Software prohibiting it from being distributed or otherwise made available under any subsequent version of the License, You must distribute and make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. Otherwise, You may also choose to use, distribute or otherwise make the Covered Software available under the terms of any subsequent version of the License published by the license steward. 4.3. Modified Versions. When You are an Initial Developer and You want to create a new license for Your Original Software, You may create and use a modified version of this License if You: (a) rename the license and remove any references to the name of the license steward (except to note that the license differs from this License); and (b) otherwise make it clear that the license contains terms which differ from this License. 5. DISCLAIMER OF WARRANTY. COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. 6. TERMINATION. 6.1. This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive. 6.2. If You assert a patent infringement claim (excluding declaratory judgment actions) against Initial Developer or a Contributor (the Initial Developer or Contributor against whom You assert such claim is referred to as "Participant") alleging that the Participant Software (meaning the Contributor Version where the Participant is a Contributor or the Original Software where the Participant is the Initial Developer) directly or indirectly infringes any patent, then any and all rights granted directly or indirectly to You by such Participant, the Initial Developer (if the Initial Developer is not the Participant) and all Contributors under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively and automatically at the expiration of such 60 day notice period, unless if within such 60 day period You withdraw Your claim with respect to the Participant Software against such Participant either unilaterally or pursuant to a written agreement with Participant. 6.3. In the event of termination under Sections 6.1 or 6.2 above, all end user licenses that have been validly granted by You or any distributor hereunder prior to termination (excluding licenses granted to You by any distributor) shall survive termination. 7. LIMITATION OF LIABILITY. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTYÕS NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. 8. U.S. GOVERNMENT END USERS. The Covered Software is a "commercial item," as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer software" (as that term is defined at 48 C.F.R. ¤ 252.227-7014(a)(1)) and "commercial computer software documentation" as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Software with only those rights set forth herein. This U.S. Government Rights clause is in lieu of, and supersedes, any other FAR, DFAR, or other clause or provision that addresses Government rights in computer software under this License. 9. MISCELLANEOUS. This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by the law of the jurisdiction specified in a notice contained within the Original Software (except to the extent applicable law, if any, provides otherwise), excluding such jurisdictionÕs conflict-of-law provisions. Any litigation relating to this License shall be subject to the jurisdiction of the courts located in the jurisdiction and venue specified in a notice contained within the Original Software, with the losing party responsible for costs, including, without limitation, court costs and reasonable attorneysÕ fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License. You agree that You alone are responsible for compliance with the United States export administration regulations (and the export control laws and regulation of any other countries) when You use, distribute or otherwise make available any Covered Software. 10. RESPONSIBILITY FOR CLAIMS. As between Initial Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability. txw2-0.1+20070624/doc/readme.txt000066400000000000000000000000641157142111200157140ustar00rootroot00000000000000See http://txw.dev.java.net/ for the documentation. txw2-0.1+20070624/lib/000077500000000000000000000000001157142111200137175ustar00rootroot00000000000000txw2-0.1+20070624/lib/compiler/000077500000000000000000000000001157142111200155315ustar00rootroot00000000000000txw2-0.1+20070624/lib/compiler/args4j-1.0-RC.license.txt000066400000000000000000000025011157142111200217010ustar00rootroot00000000000000Copyright (c) 2003, Kohsuke Kawaguchi All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. txw2-0.1+20070624/nbproject/000077500000000000000000000000001157142111200151375ustar00rootroot00000000000000txw2-0.1+20070624/nbproject/project.xml000066400000000000000000000071451157142111200173360ustar00rootroot00000000000000 org.netbeans.modules.ant.freeform txw2 src ${project.dir} java ${project.dir}/compiler java ${project.dir}/runtime jar clean jar clean javadoc test ${project.dir}/compiler ${project.dir}/runtime build.xml ${project.dir}/compiler C:\kohsuke\Sun\txw2\lib\compiler\ant.jar;C:\kohsuke\Sun\txw2\lib\compiler\codemodel.jar;C:\kohsuke\Sun\txw2\lib\compiler\commons-cli-1.0.jar;C:\kohsuke\Sun\txw2\lib\compiler\relaxngDatatype.jar;C:\kohsuke\Sun\txw2\lib\compiler\rngom.jar;C:\kohsuke\Sun\txw2\lib\compiler\xsdlib.jar;C:\kohsuke\Sun\txw2\lib\compiler\xsom.jar 1.5 ${project.dir}/runtime C:\kohsuke\Sun\txw2\lib\runtime\jsr173_1.0_api.jar 1.5 txw2-0.1+20070624/src/000077500000000000000000000000001157142111200137405ustar00rootroot00000000000000txw2-0.1+20070624/src/compiler/000077500000000000000000000000001157142111200155525ustar00rootroot00000000000000txw2-0.1+20070624/src/compiler/com/000077500000000000000000000000001157142111200163305ustar00rootroot00000000000000txw2-0.1+20070624/src/compiler/com/sun/000077500000000000000000000000001157142111200171355ustar00rootroot00000000000000txw2-0.1+20070624/src/compiler/com/sun/tools/000077500000000000000000000000001157142111200202755ustar00rootroot00000000000000txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/000077500000000000000000000000001157142111200212015ustar00rootroot00000000000000txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/AntErrorListener.java000066400000000000000000000034121157142111200253060ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2; import org.apache.tools.ant.Project; import org.xml.sax.SAXParseException; import java.text.MessageFormat; /** * @author Kohsuke Kawaguchi */ public class AntErrorListener implements ErrorListener { private final Project project; public AntErrorListener(Project p) { this.project = p; } public void error(SAXParseException e) { print(e,Project.MSG_ERR); } public void fatalError(SAXParseException e) { print(e,Project.MSG_ERR); } public void warning(SAXParseException e) { print(e,Project.MSG_WARN); } private void print(SAXParseException e, int level) { project.log(e.getMessage(),level); project.log(getLocation(e),level); } String getLocation(SAXParseException e) { return MessageFormat.format(" {0}:{1} of {2}", new Object[]{ String.valueOf(e.getLineNumber()), String.valueOf(e.getColumnNumber()), e.getSystemId()}); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/ConsoleErrorReporter.java000066400000000000000000000035061157142111200262070ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2; import org.xml.sax.SAXParseException; import java.io.PrintStream; import java.text.MessageFormat; /** * Prints the error to a stream. * * @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public class ConsoleErrorReporter implements ErrorListener { private final PrintStream out; public ConsoleErrorReporter(PrintStream out) { this.out = out; } public void error(SAXParseException exception) { out.print("[ERROR] "); print(exception); } public void fatalError(SAXParseException exception) { out.print("[FATAL] "); print(exception); } public void warning(SAXParseException exception) { out.print("[WARNING] "); print(exception); } private void print(SAXParseException e) { out.println(e.getMessage()); out.println(MessageFormat.format(" {0}:{1} of {2}", new Object[]{ String.valueOf(e.getLineNumber()), String.valueOf(e.getColumnNumber()), e.getSystemId()})); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/ErrorListener.java000066400000000000000000000022641157142111200246470ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; /** * Used internally to report errors. * * @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public interface ErrorListener extends ErrorHandler { abstract void error (SAXParseException exception); abstract void fatalError (SAXParseException exception); abstract void warning (SAXParseException exception); } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/Main.java000066400000000000000000000161131157142111200227320ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2; import com.sun.codemodel.writer.FileCodeWriter; import com.sun.codemodel.writer.SingleStreamCodeWriter; import com.sun.tools.txw2.model.NodeSet; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.opts.BooleanOption; import org.kohsuke.args4j.opts.StringOption; import org.kohsuke.rngom.parse.IllegalSchemaException; import org.kohsuke.rngom.parse.Parseable; import org.kohsuke.rngom.parse.compact.CompactParseable; import org.kohsuke.rngom.parse.xml.SAXParseable; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.util.Properties; /** * Programatic entry point to the TXW compiler. * * @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public class Main { private final TxwOptions opts; public Main(TxwOptions opts) { this.opts = opts; } public static void main(String[] args) { System.exit(run(args)); } public static class Options { public StringOption output = new StringOption("-o"); public StringOption pkg = new StringOption("-p"); public BooleanOption compact = new BooleanOption("-c"); public BooleanOption xml = new BooleanOption("-x"); public BooleanOption xsd = new BooleanOption("-xsd"); public BooleanOption chain = new BooleanOption("-h"); } public static int run(String[] args) { Options opts = new Options(); CmdLineParser parser = new CmdLineParser(); parser.addOptionClass(opts); try { parser.parse(args); } catch (CmdLineException e) { System.out.println(e.getMessage()); printUsage(); return 1; } TxwOptions topts = new TxwOptions(); topts.errorListener = new ConsoleErrorReporter(System.out); if(opts.output.value!=null) { try { topts.codeWriter = new FileCodeWriter(new File(opts.output.value)); } catch( IOException e ) { System.out.println(e.getMessage()); printUsage(); return 1; } } else { topts.codeWriter = new SingleStreamCodeWriter(System.out); } if(opts.chain.isOn()) { topts.chainMethod = true; } if(opts.pkg.value!=null) { topts._package = topts.codeModel._package(opts.pkg.value); } else { topts._package = topts.codeModel.rootPackage(); } // make sure that there's only one argument (namely the schema) if(parser.getArguments().size()!=1) { printUsage(); return 1; } try { topts.source = makeSourceSchema(parser,opts,topts.errorListener); } catch (MalformedURLException e) { System.out.println(e.getMessage()); printUsage(); return 1; } return run(topts); } /** * Parses the command line and makes a {@link Parseable} object * out of the specified schema file. */ private static SchemaBuilder makeSourceSchema(CmdLineParser parser, Options opts, ErrorHandler eh) throws MalformedURLException { File f = new File((String)parser.getArguments().get(0)); final InputSource in = new InputSource(f.toURL().toExternalForm()); if(opts.xsd.isOff() && opts.xml.isOff() && opts.compact.isOff()) { // auto detect if(in.getSystemId().endsWith(".rnc")) opts.compact.value=true; else if(in.getSystemId().endsWith(".rng")) opts.xml.value=true; else opts.xsd.value=true; } if(opts.xsd.isOn()) return new XmlSchemaLoader(in); final Parseable parseable = makeRELAXNGSource(opts, in, eh, f); return new RELAXNGLoader(parseable); } private static Parseable makeRELAXNGSource(Options opts, final InputSource in, ErrorHandler eh, File f) { if(opts.compact.isOn()) return new CompactParseable(in,eh); if(opts.xml.isOn()) return new SAXParseable(in,eh); // otherwise sniff from the file extension if(f.getPath().toLowerCase().endsWith("rnc")) return new CompactParseable(in,eh); else return new SAXParseable(in,eh); } private static void printUsage() { System.out.println("Typed Xml Writer ver."+getVersion()); System.out.println( "txw \n"+ " -o : Specify the directory to place generated source files\n"+ " -p : Specify the Java package to put the generated classes into\n"+ " -c : The input schema is written in the RELAX NG compact syntax\n"+ " -x : The input schema is written in the RELAX NG XML syntax\n"+ " -xsd : The input schema is written in the XML SChema\n"+ " -h : Generate code that allows method invocation chaining\n" ); } public static int run(TxwOptions opts) { return new Main(opts).run(); } private int run() { try { NodeSet ns = opts.source.build(opts); ns.write(opts); opts.codeModel.build(opts.codeWriter); return 0; } catch (IOException e) { opts.errorListener.error(new SAXParseException(e.getMessage(),null,e)); return 1; } catch (IllegalSchemaException e) { opts.errorListener.error(new SAXParseException(e.getMessage(),null,e)); return 1; } catch (SAXParseException e) { opts.errorListener.error(e); return 1; } catch (SAXException e) { opts.errorListener.error(new SAXParseException(e.getMessage(),null,e)); return 1; } } /** * Gets the version number of TXW. */ public static String getVersion() { try { Properties p = new Properties(); p.load(Main.class.getResourceAsStream("version.properties")); return p.get("version").toString(); } catch( Throwable _ ) { return "unknown"; } } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/NameUtil.java000066400000000000000000000254151157142111200235710ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2; import com.sun.codemodel.JJavaName; import java.util.ArrayList; /** * @author Kohsuke Kawaguchi */ public class NameUtil { protected static boolean isPunct(char c) { return (c == '-' || c == '.' || c == ':' || c == '_' || c == '\u00b7' || c == '\u0387' || c == '\u06dd' || c == '\u06de'); } protected static boolean isDigit(char c) { return ((c >= '0' && c <= '9') || Character.isDigit(c)); } protected static boolean isUpper(char c) { return ((c >= 'A' && c <= 'Z') || Character.isUpperCase(c)); } protected static boolean isLower(char c) { return ((c >= 'a' && c <= 'z') || Character.isLowerCase(c)); } protected static boolean isLetter(char c) { return ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || Character.isLetter(c)); } /** * Capitalizes the first character of the specified string, * and de-capitalize the rest of characters. */ public static String capitalize(String s) { if (!isLower(s.charAt(0))) return s; StringBuffer sb = new StringBuffer(s.length()); sb.append(Character.toUpperCase(s.charAt(0))); sb.append(s.substring(1).toLowerCase()); return sb.toString(); } // Precondition: s[start] is not punctuation protected static int nextBreak(String s, int start) { int n = s.length(); for (int i = start; i < n; i++) { char c0 = s.charAt(i); if (i < n - 1) { char c1 = s.charAt(i + 1); if (isPunct(c1)) return i + 1; if (isDigit(c0) && !isDigit(c1)) return i + 1; if (!isDigit(c0) && isDigit(c1)) return i + 1; if (isLower(c0) && !isLower(c1)) return i + 1; if (isLetter(c0) && !isLetter(c1)) return i + 1; if (!isLetter(c0) && isLetter(c1)) return i + 1; if (i < n - 2) { char c2 = s.charAt(i + 2); if (isUpper(c0) && isUpper(c1) && isLower(c2)) return i + 1; } } } return -1; } /** * Tokenizes a string into words and capitalizes the first * character of each word. * *

* This method uses a change in character type as a splitter * of two words. For example, "abc100ghi" will be splitted into * {"Abc", "100","Ghi"}. */ public static String[] toWordList(String s) { ArrayList ss = new ArrayList(); int n = s.length(); for (int i = 0; i < n;) { // Skip punctuation while (i < n) { if (!isPunct(s.charAt(i))) break; i++; } if (i >= n) break; // Find next break and collect word int b = nextBreak(s, i); String w = (b == -1) ? s.substring(i) : s.substring(i, b); ss.add(escape(capitalize(w))); if (b == -1) break; i = b; } // we can't guarantee a valid Java identifier anyway, // so there's not much point in rejecting things in this way. // if (ss.size() == 0) // throw new IllegalArgumentException("Zero-length identifier"); return (String[])(ss.toArray(new String[0])); } protected static String toMixedCaseName(String[] ss, boolean startUpper) { StringBuffer sb = new StringBuffer(); if(ss.length>0) { sb.append(startUpper ? ss[0] : ss[0].toLowerCase()); for (int i = 1; i < ss.length; i++) sb.append(ss[i]); } return sb.toString(); } protected static String toMixedCaseVariableName(String[] ss, boolean startUpper, boolean cdrUpper) { if (cdrUpper) for (int i = 1; i < ss.length; i++) ss[i] = capitalize(ss[i]); StringBuffer sb = new StringBuffer(); if( ss.length>0 ) { sb.append(startUpper ? ss[0] : ss[0].toLowerCase()); for (int i = 1; i < ss.length; i++) sb.append(ss[i]); } return sb.toString(); } /** * Formats a string into "THIS_KIND_OF_FORMAT_ABC_DEF". * * @return * Always return a string but there's no guarantee that * the generated code is a valid Java identifier. */ public static String toConstantName(String s) { return toConstantName(toWordList(s)); } /** * Formats a string into "THIS_KIND_OF_FORMAT_ABC_DEF". * * @return * Always return a string but there's no guarantee that * the generated code is a valid Java identifier. */ public static String toConstantName(String[] ss) { StringBuffer sb = new StringBuffer(); if( ss.length>0 ) { sb.append(ss[0].toUpperCase()); for (int i = 1; i < ss.length; i++) { sb.append('_'); sb.append(ss[i].toUpperCase()); } } return sb.toString(); } /** * Escapes characters is the given string so that they can be * printed by only using US-ASCII characters. * * The escaped characters will be appended to the given * StringBuffer. * * @param sb * StringBuffer that receives escaped string. * @param s * String to be escaped. s.substring(start) * will be escaped and copied to the string buffer. */ public static void escape(StringBuffer sb, String s, int start) { int n = s.length(); for (int i = start; i < n; i++) { char c = s.charAt(i); if (Character.isJavaIdentifierPart(c)) sb.append(c); else { sb.append("_"); if (c <= '\u000f') sb.append("000"); else if (c <= '\u00ff') sb.append("00"); else if (c <= '\u0fff') sb.append("0"); sb.append(Integer.toString(c, 16)); } } } /** * Escapes characters that are unusable as Java identifiers * by replacing unsafe characters with safe characters. */ private static String escape(String s) { int n = s.length(); for (int i = 0; i < n; i++) if (!Character.isJavaIdentifierPart(s.charAt(i))) { StringBuffer sb = new StringBuffer(s.substring(0, i)); escape(sb, s, i); return sb.toString(); } return s; } /** * Escape any characters that would cause the single arg constructor * of java.net.URI to complain about illegal chars. * * @param s source string to be escaped */ public static String escapeURI(String s) { StringBuffer sb = new StringBuffer(); for( int i = 0; i < s.length(); i++ ) { char c = s.charAt(i); if(Character.isSpaceChar(c)) { sb.append("%20"); } else { sb.append(c); } } return sb.toString(); } /** * Calculate the parent URI path of the given URI path. * * @param uriPath the uriPath (as returned by java.net.URI#getPath() * @return the parent URI path of the given URI path */ public static String getParentUriPath(String uriPath) { int idx = uriPath.lastIndexOf('/'); if (uriPath.endsWith("/")) { uriPath = uriPath.substring(0,idx); // trim trailing slash idx = uriPath.lastIndexOf('/'); // move idx to parent context } return uriPath.substring(0, idx)+"/"; } /** * Calculate the normalized form of the given uriPath. * * For example: * /a/b/c/ -> /a/b/c/ * /a/b/c -> /a/b/ * /a/ -> /a/ * /a -> / * * @param uriPath path of a URI (as returned by java.net.URI#getPath() * @return the normalized uri path */ public static String normalizeUriPath(String uriPath) { if (uriPath.endsWith("/")) return uriPath; // the uri path should always have at least a leading slash, // so no need to make sure that ( idx == -1 ) int idx = uriPath.lastIndexOf('/'); return uriPath.substring(0, idx+1); } /** * determine if two Strings are equal ignoring case allowing null values * * @param s string 1 * @param t string 2 * @return true iff the given strings are equal ignoring case, false if they aren't * equal or either of them are null. */ public static boolean equalsIgnoreCase(String s, String t) { if (s == t) return true; if ((s != null) && (t != null)) { return s.equalsIgnoreCase(t); } return false; } /** * determine if two Strings are iqual allowing null values * * @param s string 1 * @param t string 2 * @return true iff the strings are equal, false if they aren't equal or either of * them are null. */ public static boolean equal(String s, String t) { if (s == t) return true; if ((s != null) && (t != null)) { return s.equals(t); } return false; } public static String toClassName(String s) { return toMixedCaseName(toWordList(s), true); } public static String toVariableName(String s) { return toMixedCaseName(toWordList(s), false); } public static String toMethodName(String s) { String m = toMixedCaseName(toWordList(s), false); if(JJavaName.isJavaIdentifier(m)) return m; else return '_'+m; } public static String toInterfaceName( String token ) { return toClassName(token); } public static String toPropertyName(String s) { return toClassName(s); } public static String toPackageName( String s ) { return toMixedCaseName(toWordList(s), false ); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/RELAXNGLoader.java000066400000000000000000000036751157142111200243060ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2; import org.kohsuke.rngom.parse.Parseable; import org.kohsuke.rngom.parse.IllegalSchemaException; import org.kohsuke.rngom.ast.util.CheckingSchemaBuilder; import org.kohsuke.rngom.dt.CascadingDatatypeLibraryFactory; import org.kohsuke.rngom.dt.builtin.BuiltinDatatypeLibraryFactory; import org.relaxng.datatype.helpers.DatatypeLibraryLoader; import com.sun.tools.txw2.model.NodeSet; import com.sun.tools.txw2.model.Leaf; import com.sun.tools.txw2.builder.relaxng.SchemaBuilderImpl; /** * @author Kohsuke Kawaguchi */ class RELAXNGLoader implements SchemaBuilder { private final Parseable parseable; public RELAXNGLoader(Parseable parseable) { this.parseable = parseable; } public NodeSet build(TxwOptions options) throws IllegalSchemaException { SchemaBuilderImpl stage1 = new SchemaBuilderImpl(options.codeModel); Leaf pattern = (Leaf)parseable.parse(new CheckingSchemaBuilder(stage1,options.errorListener, new CascadingDatatypeLibraryFactory( new BuiltinDatatypeLibraryFactory(new DatatypeLibraryLoader()), new DatatypeLibraryLoader()))); return new NodeSet(options,pattern); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/SchemaBuilder.java000066400000000000000000000021641157142111200245560ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2; import com.sun.tools.txw2.model.NodeSet; import org.kohsuke.rngom.parse.IllegalSchemaException; import org.xml.sax.SAXException; /** * Encapsulation of the schema file and the builder. * * @author Kohsuke Kawaguchi */ public interface SchemaBuilder { NodeSet build(TxwOptions options) throws IllegalSchemaException, SAXException; } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/TxwOptions.java000066400000000000000000000037121157142111200242050ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2; import com.sun.codemodel.CodeWriter; import com.sun.codemodel.JCodeModel; import com.sun.codemodel.JPackage; import com.sun.xml.txw2.annotation.XmlNamespace; /** * Controls the various aspects of the TXW generation. * * But this doesn't contain options for the command-line interface * nor any of the driver-level configuration (such as where to place * the generated source code, etc.) * * @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public class TxwOptions { public final JCodeModel codeModel = new JCodeModel(); /** * The package to put the generated code into. */ public JPackage _package; /** * Always non-null. */ public ErrorListener errorListener; /** * The generated code will be sent to this. */ CodeWriter codeWriter; /** * Schema file. */ SchemaBuilder source; /** * If true, generate attribute/value methods that * returns the this object for chaining. */ public boolean chainMethod; /** * If true, the generated code will not use the package-level * {@link XmlNamespace} annotation. */ public boolean noPackageNamespace; } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/TxwTask.java000066400000000000000000000110471157142111200234540ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2; import com.sun.codemodel.writer.FileCodeWriter; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.kohsuke.rngom.parse.compact.CompactParseable; import org.kohsuke.rngom.parse.xml.SAXParseable; import org.xml.sax.InputSource; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; /** * Ant task interface for txw compiler. * * @author ryan_shoemaker@dev.java.net */ public class TxwTask extends org.apache.tools.ant.Task { // txw options - reuse command line options from the main driver private final TxwOptions options = new TxwOptions(); // schema file private File schemaFile; // syntax style of RELAX NG source schema - "xml" or "compact" private static enum Style { COMPACT, XML, XMLSCHEMA, AUTO_DETECT } private Style style = Style.AUTO_DETECT; public TxwTask() { // default package options._package = options.codeModel.rootPackage(); // default codewriter try { options.codeWriter = new FileCodeWriter(new File(".")); } catch (IOException e) { throw new BuildException(e); } } /** * Parse @package * * @param pkg name of the package to generate the java classes into */ public void setPackage( String pkg ) { options._package = options.codeModel._package( pkg ); } /** * Parse @syntax * * @param style either "compact" for RELAX NG compact syntax or "XML" * for RELAX NG xml syntax */ public void setSyntax( String style ) { this.style = Style.valueOf(style.toUpperCase()); } /** * parse @schema * * @param schema the schema file to be processed by txw */ public void setSchema( File schema ) { schemaFile = schema; } /** * parse @destdir * * @param dir the directory to produce generated source code in */ public void setDestdir( File dir ) { try { options.codeWriter = new FileCodeWriter(dir); } catch (IOException e) { throw new BuildException(e); } } /** * parse @methodChaining * * @param flg true if the txw should generate api's that allow * method chaining (when possible, false otherwise */ public void setMethodChaining( boolean flg ) { options.chainMethod = flg; } /** * launch txw */ public void execute() throws BuildException { options.errorListener = new AntErrorListener(getProject()); try { InputSource in = new InputSource(schemaFile.toURL().toExternalForm()); String msg = "Compiling: " + in.getSystemId(); log( msg, Project.MSG_INFO ); if(style==Style.AUTO_DETECT) { String fileName = schemaFile.getPath().toLowerCase(); if(fileName.endsWith("rnc")) style = Style.COMPACT; else if(fileName.endsWith("xsd")) style = Style.XMLSCHEMA; else style = Style.XML; } switch(style) { case COMPACT: options.source = new RELAXNGLoader(new CompactParseable(in,options.errorListener)); break; case XML: options.source = new RELAXNGLoader(new SAXParseable(in,options.errorListener)); break; case XMLSCHEMA: options.source = new XmlSchemaLoader(in); break; } } catch (MalformedURLException e) { throw new BuildException(e); } // kick off the compiler Main.run(options); log( "Compilation complete.", Project.MSG_INFO ); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/XmlSchemaLoader.java000066400000000000000000000025771157142111200250670ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.sun.tools.txw2.model.NodeSet; import com.sun.tools.txw2.builder.xsd.XmlSchemaBuilder; import com.sun.xml.xsom.parser.XSOMParser; /** * @author Kohsuke Kawaguchi */ class XmlSchemaLoader implements SchemaBuilder { private final InputSource in; public XmlSchemaLoader(InputSource in) { this.in = in; } public NodeSet build(TxwOptions options) throws SAXException { XSOMParser xsom = new XSOMParser(); xsom.parse(in); return XmlSchemaBuilder.build(xsom.getResult(),options); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/builder/000077500000000000000000000000001157142111200226275ustar00rootroot00000000000000txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/builder/relaxng/000077500000000000000000000000001157142111200242675ustar00rootroot00000000000000txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/builder/relaxng/AnnotationsImpl.java000066400000000000000000000030711157142111200302520ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.builder.relaxng; import org.kohsuke.rngom.ast.builder.Annotations; import org.kohsuke.rngom.ast.builder.BuildException; import org.kohsuke.rngom.ast.om.ParsedElementAnnotation; import org.kohsuke.rngom.ast.util.LocatorImpl; /** * @author Kohsuke Kawaguchi */ final class AnnotationsImpl implements Annotations { public void addAttribute(String ns, String localName, String prefix, String value, LocatorImpl locator) throws BuildException { } public void addElement(ParsedElementAnnotation parsedElementAnnotation) throws BuildException { } public void addComment(CommentListImpl commentList) throws BuildException { } public void addLeadingComment(CommentListImpl commentList) throws BuildException { } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/builder/relaxng/CommentListImpl.java000066400000000000000000000017731157142111200302220ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.builder.relaxng; import org.kohsuke.rngom.ast.builder.CommentList; import org.kohsuke.rngom.ast.util.LocatorImpl; /** * @author Kohsuke Kawaguchi */ public interface CommentListImpl extends CommentList { } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/builder/relaxng/DataPatternBuilderImpl.java000066400000000000000000000037511157142111200315000ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.builder.relaxng; import com.sun.codemodel.JType; import com.sun.tools.txw2.model.Data; import com.sun.tools.txw2.model.Leaf; import org.kohsuke.rngom.ast.builder.BuildException; import org.kohsuke.rngom.ast.builder.DataPatternBuilder; import org.kohsuke.rngom.ast.om.ParsedElementAnnotation; import org.kohsuke.rngom.ast.util.LocatorImpl; import org.kohsuke.rngom.parse.Context; /** * @author Kohsuke Kawaguchi */ final class DataPatternBuilderImpl implements DataPatternBuilder { final JType type; public DataPatternBuilderImpl(JType type) { this.type = type; } public Leaf makePattern(LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { return new Data(locator,type); } public void addParam(String name, String value, Context context, String ns, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { } public void annotation(ParsedElementAnnotation parsedElementAnnotation) { } public Leaf makePattern(Leaf except, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { return makePattern(locator,annotations); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/builder/relaxng/DatatypeFactory.java000066400000000000000000000041551157142111200302420ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.builder.relaxng; import com.sun.tools.txw2.model.Data; import com.sun.codemodel.JType; import com.sun.codemodel.JCodeModel; import javax.xml.namespace.QName; /** * Builds {@link Data} from a XML Schema datatype. * @author Kohsuke Kawaguchi */ public class DatatypeFactory { private final JCodeModel codeModel; public DatatypeFactory(JCodeModel codeModel) { this.codeModel = codeModel; } /** * Decides the Java datatype from XML datatype. * * @return null * if none is found. */ public JType getType(String datatypeLibrary, String type) { if(datatypeLibrary.equals("http://www.w3.org/2001/XMLSchema-datatypes") || datatypeLibrary.equals("http://www.w3.org/2001/XMLSchema")) { type = type.intern(); if(type=="boolean") return codeModel.BOOLEAN; if(type=="int" || type=="nonNegativeInteger" || type=="positiveInteger") return codeModel.INT; if(type=="QName") return codeModel.ref(QName.class); if(type=="float") return codeModel.FLOAT; if(type=="double") return codeModel.DOUBLE; if(type=="anySimpleType" || type=="anyType") return codeModel.ref(String.class); } return null; } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/builder/relaxng/DivImpl.java000066400000000000000000000027361157142111200265060ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.builder.relaxng; import com.sun.tools.txw2.model.Grammar; import com.sun.tools.txw2.model.Leaf; import org.kohsuke.rngom.ast.builder.Div; import org.kohsuke.rngom.ast.builder.Scope; import org.kohsuke.rngom.ast.om.ParsedElementAnnotation; import org.kohsuke.rngom.ast.util.LocatorImpl; /** * @author Kohsuke Kawaguchi */ class DivImpl extends GrammarSectionImpl implements Div { DivImpl(Scope parent, Grammar grammar) { super(parent,grammar); } public void endDiv(LocatorImpl locator, AnnotationsImpl annotations) { } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/builder/relaxng/ElementAnnotationBuilderImpl.java000066400000000000000000000034561157142111200327170ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.builder.relaxng; import org.kohsuke.rngom.ast.builder.BuildException; import org.kohsuke.rngom.ast.builder.CommentList; import org.kohsuke.rngom.ast.builder.ElementAnnotationBuilder; import org.kohsuke.rngom.ast.om.Location; import org.kohsuke.rngom.ast.om.ParsedElementAnnotation; /** * @author Kohsuke Kawaguchi */ final class ElementAnnotationBuilderImpl implements ElementAnnotationBuilder { public void addText(String value, Location location, CommentList commentList) throws BuildException { } public ParsedElementAnnotation makeElementAnnotation() throws BuildException { return null; } public void addAttribute(String ns, String localName, String prefix, String value, Location location) throws BuildException { } public void addElement(ParsedElementAnnotation parsedElementAnnotation) throws BuildException { } public void addComment(CommentList commentList) throws BuildException { } public void addLeadingComment(CommentList commentList) throws BuildException { } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/builder/relaxng/GrammarImpl.java000066400000000000000000000037521157142111200273510ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.builder.relaxng; import com.sun.tools.txw2.model.Leaf; import com.sun.tools.txw2.model.Ref; import org.kohsuke.rngom.ast.builder.BuildException; import org.kohsuke.rngom.ast.builder.Grammar; import org.kohsuke.rngom.ast.builder.Scope; import org.kohsuke.rngom.ast.om.ParsedElementAnnotation; import org.kohsuke.rngom.ast.util.LocatorImpl; /** * @author Kohsuke Kawaguchi */ class GrammarImpl extends GrammarSectionImpl implements Grammar { GrammarImpl(Scope scope) { super(scope,new com.sun.tools.txw2.model.Grammar()); } public Leaf endGrammar(LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { return new Ref(locator,grammar,com.sun.tools.txw2.model.Grammar.START); } public Leaf makeParentRef(String name, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { return parent.makeRef(name,locator,annotations); } public Leaf makeRef(String name, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { return new Ref(locator,grammar,name); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/builder/relaxng/GrammarSectionImpl.java000066400000000000000000000052351157142111200306740ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.builder.relaxng; import com.sun.tools.txw2.model.Define; import com.sun.tools.txw2.model.Grammar; import com.sun.tools.txw2.model.Leaf; import org.kohsuke.rngom.ast.builder.BuildException; import org.kohsuke.rngom.ast.builder.Div; import org.kohsuke.rngom.ast.builder.GrammarSection; import org.kohsuke.rngom.ast.builder.Include; import org.kohsuke.rngom.ast.builder.Scope; import org.kohsuke.rngom.ast.om.ParsedElementAnnotation; import org.kohsuke.rngom.ast.util.LocatorImpl; /** * @author Kohsuke Kawaguchi */ abstract class GrammarSectionImpl implements GrammarSection { protected final Scope parent; protected final Grammar grammar; GrammarSectionImpl( Scope scope, Grammar grammar ) { this.parent = scope; this.grammar = grammar; } public void topLevelAnnotation(ParsedElementAnnotation parsedElementAnnotation) throws BuildException { } public void topLevelComment(CommentListImpl commentList) throws BuildException { } public Div makeDiv() { return new DivImpl(parent,grammar); } public Include makeInclude() { // TODO throw new UnsupportedOperationException(); } public void define(String name, Combine combine, Leaf leaf, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { Define def = grammar.get(name); def.location = locator; if(combine==null || def.leaf==null) { def.leaf = leaf; } else { def.leaf.merge(leaf); } } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/builder/relaxng/SchemaBuilderImpl.java000066400000000000000000000174151157142111200304730ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.builder.relaxng; import com.sun.codemodel.JClass; import com.sun.codemodel.JCodeModel; import com.sun.codemodel.JType; import com.sun.tools.txw2.model.Attribute; import com.sun.tools.txw2.model.Data; import com.sun.tools.txw2.model.Element; import com.sun.tools.txw2.model.Empty; import com.sun.tools.txw2.model.Leaf; import com.sun.tools.txw2.model.List; import com.sun.tools.txw2.model.Value; import org.kohsuke.rngom.ast.builder.BuildException; import org.kohsuke.rngom.ast.builder.DataPatternBuilder; import org.kohsuke.rngom.ast.builder.ElementAnnotationBuilder; import org.kohsuke.rngom.ast.builder.Grammar; import org.kohsuke.rngom.ast.builder.NameClassBuilder; import org.kohsuke.rngom.ast.builder.SchemaBuilder; import org.kohsuke.rngom.ast.builder.Scope; import org.kohsuke.rngom.ast.om.ParsedElementAnnotation; import org.kohsuke.rngom.ast.util.LocatorImpl; import org.kohsuke.rngom.nc.NameClass; import org.kohsuke.rngom.nc.NameClassBuilderImpl; import org.kohsuke.rngom.parse.Context; import org.kohsuke.rngom.parse.IllegalSchemaException; import org.kohsuke.rngom.parse.Parseable; import javax.xml.namespace.QName; /** * Builds a model from a RELAX NG grammar. * * @author Kohsuke Kawaguchi */ public final class SchemaBuilderImpl implements SchemaBuilder { private final NameClassBuilderImpl ncb = new NameClassBuilderImpl(); private final JClass string; private final DatatypeFactory dtf; public SchemaBuilderImpl(JCodeModel codeModel) { string = codeModel.ref(String.class); dtf = new DatatypeFactory(codeModel); } public Leaf expandPattern(Leaf leaf) throws BuildException { return leaf; } public NameClassBuilder getNameClassBuilder() throws BuildException { return ncb; } private Leaf merge(java.util.List leaves) { for( int i=1; i leaves, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { return merge(leaves); } public Leaf makeInterleave(java.util.List leaves, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { return merge(leaves); } public Leaf makeGroup(java.util.List leaves, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { return merge(leaves); } public Leaf makeOneOrMore(Leaf leaf, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { return leaf; } public Leaf makeZeroOrMore(Leaf leaf, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { return leaf.merge(new Empty(locator)); } public Leaf makeOptional(Leaf leaf, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { return leaf.merge(new Empty(locator)); } public Leaf makeList(Leaf leaf, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { return new List(locator,leaf); } public Leaf makeMixed(Leaf leaf, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { return leaf.merge(new Data(locator,string)); } public Leaf makeEmpty(LocatorImpl locator, AnnotationsImpl annotations) { return new Empty(locator); } public Leaf makeNotAllowed(LocatorImpl locator, AnnotationsImpl annotations) { // technically this is incorrect, but we won't be // able to handle correctly anyway. return new Empty(locator); } public Leaf makeText(LocatorImpl locator, AnnotationsImpl annotations) { return new Data(locator,string); } public Leaf makeAttribute(NameClass nameClass, Leaf leaf, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { Leaf r = null; for( QName n : nameClass.listNames() ) { Leaf l = new Attribute(locator,n,leaf); if(r!=null) r = r.merge(l); else r = l; } if(r==null) return new Empty(locator); return r; } public Leaf makeElement(NameClass nameClass, Leaf leaf, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { Leaf r = null; for( QName n : nameClass.listNames() ) { Leaf l = new Element(locator,n,leaf); if(r!=null) r = r.merge(l); else r = l; } if(r==null) return new Empty(locator); return r; } public DataPatternBuilder makeDataPatternBuilder(String datatypeLibrary, String type, LocatorImpl locator) throws BuildException { return new DataPatternBuilderImpl(getType(datatypeLibrary, type)); } private JType getType(String datatypeLibrary, String type) { JType t = dtf.getType(datatypeLibrary,type); if(t==null) t = string; return t; } public Leaf makeValue(String datatypeLibrary, String type, String value, Context c, String ns, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException { return new Value(locator,getType(datatypeLibrary, type),value); } public Grammar makeGrammar(Scope scope) { return new GrammarImpl(scope); } public Leaf annotate(Leaf leaf, AnnotationsImpl annotations) throws BuildException { return leaf; } public Leaf annotateAfter(Leaf leaf, ParsedElementAnnotation parsedElementAnnotation) throws BuildException { return leaf; } public Leaf makeErrorPattern() { return new Empty(null); } public boolean usesComments() { return false; } public Leaf makeExternalRef(Parseable current, String uri, String ns, Scope scope, LocatorImpl locator, AnnotationsImpl annotations) throws BuildException, IllegalSchemaException { // I'm not too sure if this is correct return current.parseExternal(uri, this, scope, ns ); } public LocatorImpl makeLocation(String systemId, int lineNumber, int columnNumber) { return new LocatorImpl(systemId,lineNumber,columnNumber); } public AnnotationsImpl makeAnnotations(CommentListImpl commentList, Context context) { return new AnnotationsImpl(); } public ElementAnnotationBuilder makeElementAnnotationBuilder(String ns, String localName, String prefix, LocatorImpl locator, CommentListImpl commentList, Context context) { return new ElementAnnotationBuilderImpl(); } public CommentListImpl makeCommentList() { return null; } public Leaf commentAfter(Leaf leaf, CommentListImpl commentList) throws BuildException { return leaf; } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/builder/relaxng/package.html000066400000000000000000000001361157142111200265500ustar00rootroot00000000000000 Reads RELAX NG grammar from RNGOM and builds the model for TXW. txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/builder/xsd/000077500000000000000000000000001157142111200234255ustar00rootroot00000000000000txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/builder/xsd/XmlSchemaBuilder.java000066400000000000000000000215441157142111200274660ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.builder.xsd; import com.sun.codemodel.JType; import com.sun.tools.txw2.TxwOptions; import com.sun.tools.txw2.builder.relaxng.DatatypeFactory; import com.sun.tools.txw2.model.Attribute; import com.sun.tools.txw2.model.Data; import com.sun.tools.txw2.model.Define; import com.sun.tools.txw2.model.Empty; import com.sun.tools.txw2.model.Grammar; import com.sun.tools.txw2.model.Leaf; import com.sun.tools.txw2.model.List; import com.sun.tools.txw2.model.NodeSet; import com.sun.tools.txw2.model.Element; import com.sun.tools.txw2.model.Ref; import com.sun.xml.xsom.XSAnnotation; import com.sun.xml.xsom.XSAttributeDecl; import com.sun.xml.xsom.XSAttributeUse; import com.sun.xml.xsom.XSComplexType; import com.sun.xml.xsom.XSContentType; import com.sun.xml.xsom.XSDeclaration; import com.sun.xml.xsom.XSFacet; import com.sun.xml.xsom.XSIdentityConstraint; import com.sun.xml.xsom.XSListSimpleType; import com.sun.xml.xsom.XSNotation; import com.sun.xml.xsom.XSParticle; import com.sun.xml.xsom.XSRestrictionSimpleType; import com.sun.xml.xsom.XSSchema; import com.sun.xml.xsom.XSSchemaSet; import com.sun.xml.xsom.XSSimpleType; import com.sun.xml.xsom.XSUnionSimpleType; import com.sun.xml.xsom.XSXPath; import com.sun.xml.xsom.XSWildcard; import com.sun.xml.xsom.XSModelGroupDecl; import com.sun.xml.xsom.XSModelGroup; import com.sun.xml.xsom.XSElementDecl; import com.sun.xml.xsom.XSType; import com.sun.xml.xsom.XSAttContainer; import com.sun.xml.xsom.XSAttGroupDecl; import com.sun.xml.xsom.visitor.XSFunction; import com.sun.xml.xsom.visitor.XSSimpleTypeFunction; import javax.xml.namespace.QName; import java.util.Map; import java.util.HashMap; /** * @author Kohsuke Kawaguchi */ public final class XmlSchemaBuilder implements XSFunction, XSSimpleTypeFunction { public static NodeSet build( XSSchemaSet xs, TxwOptions opts ) { XmlSchemaBuilder builder = new XmlSchemaBuilder(xs,opts); builder.build(xs); return builder.nodeSet; } private void build(XSSchemaSet xs) { // make sure that we bind all complex types for( XSSchema s : xs.getSchemas() ) { for( XSComplexType t : s.getComplexTypes().values() ) { t.apply(this); } } nodeSet.addAll(complexTypes.values()); nodeSet.addAll(modelGroups.values()); nodeSet.addAll(attGroups.values()); } public Leaf simpleType(XSSimpleType simpleType) { return simpleType.apply((XSSimpleTypeFunction)this); } public Leaf particle(XSParticle particle) { return particle.getTerm().apply(this); } public Leaf empty(XSContentType empty) { return new Empty(empty.getLocator()); } public Attribute attributeDecl(XSAttributeDecl decl) { return new Attribute(decl.getLocator(), getQName(decl), simpleType(decl.getType())); } public Attribute attributeUse(XSAttributeUse use) { return attributeDecl(use.getDecl()); } public Leaf wildcard(XSWildcard wc) { // wildcard can be always written through the well-formedness method. // no need to generate anything for this. return new Empty(wc.getLocator()); } public Leaf modelGroupDecl(XSModelGroupDecl mg) { Define def = modelGroups.get(mg); if(def==null) { def = grammar.get(mg.getName()); // TODO: name collision detection and avoidance modelGroups.put(mg,def); def.addChild(mg.getModelGroup().apply(this)); } return new Ref(mg.getLocator(),def); } public Leaf modelGroup(XSModelGroup mg) { XSParticle[] children = mg.getChildren(); if(children.length==0) return new Empty(mg.getLocator()); Leaf l = particle(children[0]); for( int i=1; i modelGroups = new HashMap(); /** * We map complex types to interfaces. */ private final Map complexTypes = new HashMap(); /** * ... and attribute groups */ private final Map attGroups = new HashMap(); private final Grammar grammar = new Grammar(); private XmlSchemaBuilder(XSSchemaSet xs,TxwOptions opts) { this.schemaSet = xs; grammar.addChild(new Empty(null)); this.nodeSet = new NodeSet(opts,grammar); this.dtf = new DatatypeFactory(opts.codeModel); } // won't be used public Leaf annotation(XSAnnotation xsAnnotation) { throw new IllegalStateException(); } public Leaf schema(XSSchema xsSchema) { throw new IllegalStateException(); } public Leaf facet(XSFacet xsFacet) { throw new IllegalStateException(); } public Leaf notation(XSNotation xsNotation) { throw new IllegalStateException(); } public Leaf identityConstraint(XSIdentityConstraint xsIdentityConstraint) { throw new IllegalStateException(); } public Leaf xpath(XSXPath xsxPath) { throw new IllegalStateException(); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/builder/xsd/package.html000066400000000000000000000001371157142111200257070ustar00rootroot00000000000000 Reads XML Schema grammar from XSOM and builds the model for TXW. txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/000077500000000000000000000000001157142111200223015ustar00rootroot00000000000000txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/Attribute.java000066400000000000000000000051511157142111200251110ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model; import com.sun.codemodel.JAnnotationUse; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JMethod; import com.sun.codemodel.JMod; import com.sun.codemodel.JType; import com.sun.tools.txw2.NameUtil; import com.sun.tools.txw2.model.prop.AttributeProp; import com.sun.tools.txw2.model.prop.Prop; import com.sun.xml.txw2.annotation.XmlAttribute; import org.xml.sax.Locator; import javax.xml.namespace.QName; import java.util.HashSet; import java.util.Set; /** * Attribute declaration. * * @author Kohsuke Kawaguchi */ public class Attribute extends XmlNode { public Attribute(Locator location, QName name, Leaf leaf) { super(location, name, leaf); } void declare(NodeSet nset) { ; // attributes won't produce a class } void generate(NodeSet nset) { ; // nothing } void generate(JDefinedClass clazz, NodeSet nset, Set props) { Set types = new HashSet(); for( Leaf l : collectChildren() ) { if (l instanceof Text) { types.add(((Text)l).getDatatype(nset)); } } String methodName = NameUtil.toMethodName(name.getLocalPart()); for( JType t : types ) { if(!props.add(new AttributeProp(name,t))) continue; JMethod m = clazz.method(JMod.PUBLIC, nset.opts.chainMethod? (JType)clazz : nset.codeModel.VOID, methodName); m.param(t,"value"); JAnnotationUse a = m.annotate(XmlAttribute.class); if(!methodName.equals(name.getLocalPart())) a.param("value",name.getLocalPart()); if(!name.getNamespaceURI().equals("")) a.param("ns",name.getNamespaceURI()); } } public String toString() { return "Attribute "+name; } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/CycleIterator.java000066400000000000000000000026721157142111200257240ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model; import java.util.Iterator; /** * @author Kohsuke Kawaguchi */ final class CycleIterator implements Iterator { private Leaf start; private Leaf current; private boolean hasNext = true; public CycleIterator(Leaf start) { assert start!=null; this.start = start; this.current = start; } public boolean hasNext() { return hasNext; } public Leaf next() { Leaf last = current; current = current.getNext(); if(current==start) hasNext = false; return last; } public void remove() { throw new UnsupportedOperationException(); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/Data.java000066400000000000000000000026631157142111200240240ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JType; import com.sun.tools.txw2.model.prop.Prop; import org.xml.sax.Locator; import java.util.Set; /** * @author Kohsuke Kawaguchi */ public class Data extends Leaf implements Text { /** * The Java representation of the datatype. */ public final JType type; public Data(Locator location, JType type) { super(location); this.type = type; } public JType getDatatype(NodeSet nset) { return type; } void generate(JDefinedClass clazz, NodeSet nset, Set props) { createDataMethod(clazz,type,nset,props); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/Define.java000066400000000000000000000051351157142111200243420ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model; import com.sun.codemodel.JDefinedClass; import com.sun.tools.txw2.model.prop.Prop; import com.sun.xml.txw2.TypedXmlWriter; import java.util.HashSet; import java.util.Set; /** * A named pattern. * * @author Kohsuke Kawaguchi */ public class Define extends WriterNode { public final Grammar scope; public final String name; JDefinedClass clazz; public Define(Grammar scope, String name) { super(null,null); if(scope==null) scope = (Grammar)this; // hack for start pattern this.scope = scope; this.name = name; assert name!=null; } /** * Returns true if this define only contains * one child (and thus considered inlinable.) * * A pattern definition is also inlineable if * it's the start of the grammar (because "start" isn't a meaningful name) */ public boolean isInline() { return hasOneChild() || name==Grammar.START; } void declare(NodeSet nset) { if(isInline()) return; clazz = nset.createClass(name); clazz._implements(TypedXmlWriter.class); } void generate(NodeSet nset) { if(clazz==null) return; HashSet props = new HashSet(); for( Leaf l : this ) l.generate(clazz,nset,props); } void generate(JDefinedClass clazz, NodeSet nset, Set props) { if(isInline()) { for( Leaf l : this ) l.generate(clazz,nset, props); } else { assert this.clazz!=null; clazz._implements(this.clazz); } } void prepare(NodeSet nset) { if(isInline() && leaf instanceof WriterNode && !name.equals(Grammar.START)) ((WriterNode)leaf).alternativeName = name; } public String toString() { return "Define "+name; } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/Element.java000066400000000000000000000134311157142111200245370ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model; import com.sun.codemodel.JAnnotationUse; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JMethod; import com.sun.codemodel.JMod; import com.sun.codemodel.JType; import com.sun.tools.txw2.NameUtil; import com.sun.tools.txw2.model.prop.ElementProp; import com.sun.tools.txw2.model.prop.LeafElementProp; import com.sun.tools.txw2.model.prop.Prop; import com.sun.xml.txw2.TypedXmlWriter; import com.sun.xml.txw2.annotation.XmlElement; import org.xml.sax.Locator; import javax.xml.namespace.QName; import java.util.HashSet; import java.util.Set; /** * Element declaration. * * @author Kohsuke Kawaguchi */ public class Element extends XmlNode { /** * True if this element can be a root element. */ public boolean isRoot; private Strategy strategy; public Element(Locator location, QName name, Leaf leaf) { super(location, name, leaf); } /** * Returns true if this element should generate an interface. */ private Strategy decideStrategy() { if(isRoot) return new ToInterface(); if(hasOneChild() && leaf instanceof Ref && !((Ref)leaf).isInline()) return new HasOneRef((Ref)leaf); Set children = collectChildren(); for( Leaf l : children ) { if( l instanceof XmlNode ) // if it has attributes/elements in children // generate an interface return new ToInterface(); } // otherwise this element only has data, so just generate methods for them. return new DataOnly(); } void declare(NodeSet nset) { strategy = decideStrategy(); strategy.declare(nset); } void generate(NodeSet nset) { strategy.generate(nset); } void generate(JDefinedClass clazz, NodeSet nset, Set props) { strategy.generate(clazz,nset,props); } private JMethod generateMethod(JDefinedClass clazz, NodeSet nset, JType retT) { String methodName = NameUtil.toMethodName(name.getLocalPart()); JMethod m = clazz.method(JMod.PUBLIC, retT, methodName); JAnnotationUse a = m.annotate(XmlElement.class); if(!methodName.equals(name.getLocalPart())) a.param("value",name.getLocalPart()); if(nset.defaultNamespace==null || !nset.defaultNamespace.equals(name.getNamespaceURI())) a.param("ns",name.getNamespaceURI()); return m; } public String toString() { return "Element "+name; } interface Strategy { void declare(NodeSet nset); void generate(NodeSet nset); void generate(JDefinedClass clazz, NodeSet nset, Set props); } /** * Maps to an interface */ private class ToInterface implements Strategy { private JDefinedClass clazz; public void declare(NodeSet nset) { String cname; if(alternativeName!=null) cname = alternativeName; else cname = name.getLocalPart(); clazz = nset.createClass(cname); clazz._implements(TypedXmlWriter.class); clazz.annotate(XmlElement.class) .param("value",name.getLocalPart()); // TODO: namespace } public void generate(NodeSet nset) { HashSet props = new HashSet(); for( Leaf l : Element.this ) l.generate(clazz,nset, props); } public void generate(JDefinedClass outer, NodeSet nset, Set props) { if(props.add(new ElementProp(name,clazz))) generateMethod(outer, nset, clazz); } } /** * For things like "element foo {refToAnotherPattern}" */ private class HasOneRef implements Strategy { private final Ref ref; public HasOneRef(Ref ref) { this.ref = ref; } public void declare(NodeSet nset) { } public void generate(NodeSet nset) { } public void generate(JDefinedClass clazz, NodeSet nset, Set props) { if(props.add(new ElementProp(name,ref.def.clazz))) generateMethod(clazz, nset, ref.def.clazz); } } private class DataOnly implements Strategy { public void declare(NodeSet nset) { } public void generate(NodeSet nset) { } // TODO: code share with Attribute public void generate(JDefinedClass clazz, NodeSet nset, Set props) { Set types = new HashSet(); for( Leaf l : collectChildren() ) { if (l instanceof Text) { types.add(((Text)l).getDatatype(nset)); } } for( JType t : types ) { if(!props.add(new LeafElementProp(name,t))) continue; generateMethod(clazz, nset, nset.opts.chainMethod? (JType)clazz : nset.codeModel.VOID ).param(t,"value"); } } } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/Empty.java000066400000000000000000000022271157142111200242450ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model; import com.sun.codemodel.JDefinedClass; import com.sun.tools.txw2.model.prop.Prop; import org.xml.sax.Locator; import java.util.Set; /** * @author Kohsuke Kawaguchi */ public class Empty extends Leaf { public Empty(Locator location) { super(location); } void generate(JDefinedClass clazz, NodeSet nset, Set props) { // noop } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/Grammar.java000066400000000000000000000032061157142111200245330ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model; import org.kohsuke.rngom.ast.builder.GrammarSection; import java.util.HashMap; import java.util.Map; import java.util.Collection; /** * Represents a RELAX NG grammar. * * A {@link Grammar} extends a {@link Define} as "start" * * @author Kohsuke Kawaguchi */ public class Grammar extends Define { private final Map patterns = new HashMap(); public Grammar() { super(null,START); patterns.put(START,this); } public Define get(String name) { Define def = patterns.get(name); if(def==null) patterns.put(name,def=new Define(this,name)); return def; } public Collection getDefinitions() { return patterns.values(); } /** * The name for the start pattern */ public static final String START = GrammarSection.START; } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/Leaf.java000066400000000000000000000061521157142111200240170ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JMethod; import com.sun.codemodel.JMod; import com.sun.codemodel.JType; import com.sun.tools.txw2.model.prop.Prop; import com.sun.tools.txw2.model.prop.ValueProp; import com.sun.xml.txw2.annotation.XmlValue; import org.kohsuke.rngom.ast.om.ParsedPattern; import org.xml.sax.Locator; import java.util.Iterator; import java.util.Set; /** * {@link Leaf}s form a set (by a cyclic doubly-linked list.) * * @author Kohsuke Kawaguchi */ public abstract class Leaf implements ParsedPattern { private Leaf next; private Leaf prev; /** * Source location where this leaf was defined. */ public Locator location; protected Leaf(Locator location) { this.location = location; prev = next = this; } public final Leaf getNext() { assert next!=null; assert next.prev == this; return next; } public final Leaf getPrev() { assert prev!=null; assert prev.next == this; return prev; } /** * Combines two sets into one set. * * @return this */ public final Leaf merge(Leaf that) { Leaf n1 = this.next; Leaf n2 = that.next; that.next = n1; that.next.prev = that; this.next = n2; this.next.prev = this; return this; } /** * Returns the collection of all the siblings * (including itself) */ public final Iterable siblings() { return new Iterable() { public Iterator iterator() { return new CycleIterator(Leaf.this); } }; } /** * Populate the body of the writer class. * * @param props * captures the generatesd {@link Prop}s to */ abstract void generate(JDefinedClass clazz, NodeSet nset, Set props); /** * Creates a prop of the data value method. */ protected final void createDataMethod(JDefinedClass clazz, JType valueType, NodeSet nset, Set props) { if(!props.add(new ValueProp(valueType))) return; JMethod m = clazz.method(JMod.PUBLIC, nset.opts.chainMethod? (JType)clazz : nset.codeModel.VOID, "_text"); m.annotate(XmlValue.class); m.param(valueType,"value"); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/List.java000066400000000000000000000030541157142111200240610ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JType; import com.sun.tools.txw2.model.prop.Prop; import org.xml.sax.Locator; import java.util.Set; /** * List of {@link Data} or {@link Value}. * * @author Kohsuke Kawaguchi */ public class List extends Node implements Text { public List(Locator location, Leaf leaf) { super(location, leaf); } public JType getDatatype(NodeSet nset) { if(hasOneChild() && leaf instanceof Text) { return ((Text)leaf).getDatatype(nset).array(); } else { return nset.codeModel.ref(String.class).array(); } } void generate(JDefinedClass clazz, NodeSet nset, Set props) { createDataMethod(clazz,getDatatype(nset),nset,props); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/Node.java000066400000000000000000000033721157142111200240360ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model; import org.xml.sax.Locator; import java.util.Iterator; /** * {@link Node} is a {@link Leaf} that has children. * * Children are orderless. * * @author Kohsuke Kawaguchi */ public abstract class Node extends Leaf implements Iterable { /** * Children of this node. */ public Leaf leaf; protected Node(Locator location, Leaf leaf) { super(location); this.leaf = leaf; } /** * Iterates all the children. */ public final Iterator iterator() { return new CycleIterator(leaf); } /** * Returns true if this node has only one child node. */ public final boolean hasOneChild() { return leaf==leaf.getNext(); } /** * Adds the given {@link Leaf} and their sibling as children of this {@link Node}. */ public final void addChild(Leaf child) { if(this.leaf==null) leaf = child; else leaf.merge(child); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/NodeSet.java000066400000000000000000000114061157142111200245070ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model; import com.sun.codemodel.ClassType; import com.sun.codemodel.JClassAlreadyExistsException; import com.sun.codemodel.JCodeModel; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JMod; import com.sun.tools.txw2.NameUtil; import com.sun.tools.txw2.TxwOptions; import com.sun.xml.txw2.annotation.XmlNamespace; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; /** * Root of the model. * * @author Kohsuke Kawaguchi */ public class NodeSet extends LinkedHashSet { /*package*/ final TxwOptions opts; /*package*/ final JCodeModel codeModel; /** * Set of all the {@link Element}s that can be root. */ private final Set rootElements = new HashSet(); /** The namespace URI declared in {@link XmlNamespace}. */ /*package*/ final String defaultNamespace; public NodeSet(TxwOptions opts, Leaf entry) { this.opts = opts; this.codeModel = opts.codeModel; addAll(entry.siblings()); markRoot(entry.siblings(),rootElements); // decide what to put in @XmlNamespace Set ns = new HashSet(); for( Element e : rootElements ) ns.add(e.name.getNamespaceURI()); if(ns.size()!=1 || opts.noPackageNamespace || opts._package.isUnnamed()) defaultNamespace = null; else { defaultNamespace = ns.iterator().next(); opts._package.annotate(XmlNamespace.class) .param("value",defaultNamespace); } } /** * Marks all the element children as root. */ private void markRoot(Iterable c, Set rootElements) { for( Leaf l : c ) { if( l instanceof Element ) { Element e = (Element)l; rootElements.add(e); e.isRoot = true; } if( l instanceof Ref ) { markRoot(((Ref)l).def,rootElements); } } } private void addAll(Iterable c) { for( Leaf l : c ) { if(l instanceof Element) if(add((Element)l)) addAll((Element)l); if(l instanceof Grammar) { Grammar g = (Grammar)l; for( Define d : g.getDefinitions() ) add(d); } if(l instanceof Ref) { Ref r = (Ref)l; Define def = r.def; // if(def instanceof Grammar) { // for( Define d : ((Grammar)def).getDefinitions() ) // if(add(d)) // addAll(d); // } add(def); } } } private boolean add(Define def) { boolean b = super.add(def); if(b) addAll(def); return b; } public Collection subset(Class t) { ArrayList r = new ArrayList(size()); for( WriterNode n : this ) if(t.isInstance(n)) r.add((T)n); return r; } /** * Generate code */ public void write(TxwOptions opts) { for( WriterNode n : this ) n.prepare(this); for( WriterNode n : this ) n.declare(this); for( WriterNode n : this ) n.generate(this); } /*package*/ final JDefinedClass createClass(String name) { try { return opts._package._class( JMod.PUBLIC, NameUtil.toClassName(name), ClassType.INTERFACE ); } catch (JClassAlreadyExistsException e) { for( int i=2; true; i++ ) { try { return opts._package._class( JMod.PUBLIC, NameUtil.toClassName(name+String.valueOf(i)), ClassType.INTERFACE ); } catch (JClassAlreadyExistsException e1) { ; // continue } } } } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/Ref.java000066400000000000000000000027421157142111200236650ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model; import com.sun.codemodel.JDefinedClass; import com.sun.tools.txw2.model.prop.Prop; import org.xml.sax.Locator; import java.util.Set; /** * A reference to a named pattern. * * @author Kohsuke Kawaguchi */ public final class Ref extends Leaf { public final Define def; public Ref(Locator location, Grammar scope, String name) { super(location); this.def = scope.get(name); } public Ref(Locator location, Define def) { super(location); this.def = def; } public boolean isInline() { return def.isInline(); } void generate(JDefinedClass clazz, NodeSet nset, Set props) { def.generate(clazz,nset,props); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/Text.java000066400000000000000000000020531157142111200240700ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model; import com.sun.codemodel.JType; /** * Implemented by {@link Leaf}s that map to PCDATA in XML. * * @author Kohsuke Kawaguchi */ public interface Text { /** * Obtains the Java class of this {@link Text}. */ JType getDatatype(NodeSet nset); } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/Value.java000066400000000000000000000031701157142111200242210ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JType; import com.sun.tools.txw2.model.prop.Prop; import org.xml.sax.Locator; import java.util.Set; /** * A constant value. * * @author Kohsuke Kawaguchi */ public class Value extends Leaf implements Text { /** * The underlying datatype, in case * we need to revert to {@link Data}. */ public final JType type; /** * Constant name. */ public final String name; public Value(Locator location, JType type, String name) { super(location); this.type = type; this.name = name; } void generate(JDefinedClass clazz, NodeSet nset, Set props) { createDataMethod(clazz,type,nset,props); } public JType getDatatype(NodeSet nset) { // TODO: enum support return type; } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/WriterNode.java000066400000000000000000000031521157142111200252270ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model; import org.xml.sax.Locator; /** * The {@link Node} that maps to the program element. * * @author Kohsuke Kawaguchi */ public abstract class WriterNode extends Node { /** * If this node is the sole child of a pattern block, * this field points to its name. * *

* When the element names are in conflict, this can be used. */ protected String alternativeName; public WriterNode(Locator location, Leaf leaf) { super(location, leaf); } /** * Declares the class without its contents. * * The first step of the code generation. */ abstract void declare(NodeSet nset); /** * Generates the contents. */ abstract void generate(NodeSet nset); /** * Prepares for the code generation. */ void prepare(NodeSet nset) {} } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/XmlNode.java000066400000000000000000000036411157142111200245160ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model; import org.xml.sax.Locator; import javax.xml.namespace.QName; import java.util.HashSet; import java.util.Set; import java.util.Stack; /** * Either an {@link Element} or {@link Attribute}. * * @author Kohsuke Kawaguchi */ public abstract class XmlNode extends WriterNode { /** * Name of the attribute/element. * * In TXW, we ignore all infinite names. * (finite name class will be expanded to a list of {@link XmlNode}s. */ public final QName name; protected XmlNode(Locator location, QName name, Leaf leaf) { super(location, leaf); this.name = name; } /** * Expand all refs and collect all children. */ protected final Set collectChildren() { Set result = new HashSet(); Stack work = new Stack(); work.push(this); while(!work.isEmpty()) { for( Leaf l : work.pop() ) { if( l instanceof Ref ) { work.push( ((Ref)l).def ); } else { result.add(l); } } } return result; } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/prop/000077500000000000000000000000001157142111200232615ustar00rootroot00000000000000txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/prop/AttributeProp.java000066400000000000000000000020511157142111200267260ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model.prop; import com.sun.codemodel.JType; import javax.xml.namespace.QName; /** * @author Kohsuke Kawaguchi */ public final class AttributeProp extends XmlItemProp { public AttributeProp(QName name, JType valueType) { super(name, valueType); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/prop/ElementProp.java000066400000000000000000000021151157142111200263550ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model.prop; import com.sun.codemodel.JType; import javax.xml.namespace.QName; /** * Property generated from elements. * * @author Kohsuke Kawaguchi */ public final class ElementProp extends XmlItemProp { public ElementProp(QName name, JType valueType) { super(name, valueType); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/prop/LeafElementProp.java000066400000000000000000000020551157142111200271500ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model.prop; import com.sun.codemodel.JType; import javax.xml.namespace.QName; /** * @author Kohsuke Kawaguchi */ public final class LeafElementProp extends XmlItemProp { public LeafElementProp(QName name, JType valueType) { super(name, valueType); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/prop/Prop.java000066400000000000000000000021471157142111200250500ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model.prop; /** * Immutable object that captures the characterstic * of the generated writer method. * *

* Instances of this class implement {@link #equals(Object)} * and {@link #hashCode()}. By using these we avoid generating * the same method twice. * * @author Kohsuke Kawaguchi */ public abstract class Prop { } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/prop/ValueProp.java000066400000000000000000000023651157142111200260470ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model.prop; import com.sun.codemodel.JType; /** * @author Kohsuke Kawaguchi */ public class ValueProp extends Prop { private final JType type; public ValueProp(JType type) { this.type = type; } public boolean equals(Object o) { if (!(o instanceof ValueProp)) return false; final ValueProp that = (ValueProp) o; return type.equals(that.type); } public int hashCode() { return type.hashCode(); } } txw2-0.1+20070624/src/compiler/com/sun/tools/txw2/model/prop/XmlItemProp.java000066400000000000000000000027731157142111200263550ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.txw2.model.prop; import com.sun.codemodel.JType; import javax.xml.namespace.QName; /** * Common implementation between elements and attributes. * * @author Kohsuke Kawaguchi */ abstract class XmlItemProp extends Prop { private final QName name; private final JType type; public XmlItemProp(QName name, JType valueType) { this.name = name; this.type = valueType; } public final boolean equals(Object o) { if (this.getClass()!=o.getClass()) return false; XmlItemProp that = (XmlItemProp)o; return this.name.equals(that.name) && this.type.equals(that.type); } public final int hashCode() { return name.hashCode()*29 + type.hashCode(); } } txw2-0.1+20070624/src/runtime/000077500000000000000000000000001157142111200154235ustar00rootroot00000000000000txw2-0.1+20070624/src/runtime/com/000077500000000000000000000000001157142111200162015ustar00rootroot00000000000000txw2-0.1+20070624/src/runtime/com/sun/000077500000000000000000000000001157142111200170065ustar00rootroot00000000000000txw2-0.1+20070624/src/runtime/com/sun/xml/000077500000000000000000000000001157142111200176065ustar00rootroot00000000000000txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/000077500000000000000000000000001157142111200205125ustar00rootroot00000000000000txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/Attribute.java000066400000000000000000000026421157142111200233240ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2; /** * @author Kohsuke Kawaguchi */ final class Attribute { final String nsUri; final String localName; /** * Attributes of an element form a linked list. */ Attribute next; /** * Attribute value that potentially contains dummy prefixes. */ final StringBuilder value = new StringBuilder(); Attribute(String nsUri, String localName) { assert nsUri!=null && localName!=null; this.nsUri = nsUri; this.localName = localName; } boolean hasName( String nsUri, String localName ) { return this.localName.equals(localName) && this.nsUri.equals(nsUri); } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/Cdata.java000066400000000000000000000021041157142111200223660ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2; /** * CDATA section. * * @author Kohsuke Kawaguchi */ final class Cdata extends Text { Cdata(Document document, NamespaceResolver nsResolver, Object obj) { super(document, nsResolver, obj); } void accept(ContentVisitor visitor) { visitor.onCdata(buffer); } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/Comment.java000066400000000000000000000024151157142111200227610ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2; /** * Comment. * * @author Kohsuke Kawaguchi */ final class Comment extends Content { /** * The text to be writtten. */ private final StringBuilder buffer = new StringBuilder(); public Comment(Document document, NamespaceResolver nsResolver, Object obj) { document.writeValue(obj,nsResolver,buffer); } boolean concludesPendingStartTag() { return false; } void accept(ContentVisitor visitor) { visitor.onComment(buffer); } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/ContainerElement.java000066400000000000000000000256321157142111200246210ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2; import com.sun.xml.txw2.annotation.XmlAttribute; import com.sun.xml.txw2.annotation.XmlElement; import com.sun.xml.txw2.annotation.XmlNamespace; import com.sun.xml.txw2.annotation.XmlValue; import com.sun.xml.txw2.annotation.XmlCDATA; import javax.xml.namespace.QName; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * Dynamically implements {@link TypedXmlWriter} interfaces. * * @author Kohsuke Kawaguchi */ final class ContainerElement implements InvocationHandler, TypedXmlWriter { final Document document; /** * Initially, point to the start tag token, but * once we know we are done with the start tag, we will reset it to null * so that the token sequence can be GC-ed. */ StartTag startTag; final EndTag endTag = new EndTag(); /** * Namespace URI of this element. */ private final String nsUri; /** * When this element can accept more child content, this value * is non-null and holds the last child {@link Content}. * * If this element is committed, this parameter is null. */ private Content tail; /** * Uncommitted {@link ContainerElement}s form a doubly-linked list, * so that the parent can close them recursively. */ private ContainerElement prevOpen; private ContainerElement nextOpen; private final ContainerElement parent; private ContainerElement lastOpenChild; /** * Set to true if the start eleent is blocked. */ private boolean blocked; public ContainerElement(Document document,ContainerElement parent,String nsUri, String localName) { this.parent = parent; this.document = document; this.nsUri = nsUri; this.startTag = new StartTag(this,nsUri,localName); tail = startTag; if(isRoot()) document.setFirstContent(startTag); } private boolean isRoot() { return parent==null; } private boolean isCommitted() { return tail==null; } public Document getDocument() { return document; } boolean isBlocked() { return blocked && !isCommitted(); } public void block() { blocked = true; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(method.getDeclaringClass()==TypedXmlWriter.class || method.getDeclaringClass()==Object.class) { // forward to myself try { return method.invoke(this,args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } XmlAttribute xa = method.getAnnotation(XmlAttribute.class); XmlValue xv = method.getAnnotation(XmlValue.class); XmlElement xe = method.getAnnotation(XmlElement.class); if(xa!=null) { if(xv!=null || xe!=null) throw new IllegalAnnotationException(method.toString()); addAttribute(xa,method,args); return proxy; // allow method chaining } if(xv!=null) { if(xe!=null) throw new IllegalAnnotationException(method.toString()); _pcdata(args); return proxy; // allow method chaining } return addElement(xe,method,args); } /** * Writes an attribute. */ private void addAttribute(XmlAttribute xa, Method method, Object[] args) { assert xa!=null; checkStartTag(); String localName = xa.value(); if(xa.value().length()==0) localName = method.getName(); _attribute(xa.ns(),localName,args); } private void checkStartTag() { if(startTag==null) throw new IllegalStateException("start tag has already been written"); } /** * Writes a new element. */ private Object addElement(XmlElement e, Method method, Object[] args) { Class rt = method.getReturnType(); // the last precedence: default name String nsUri = "##default"; String localName = method.getName(); if(e!=null) { // then the annotation on this method if(e.value().length()!=0) localName = e.value(); nsUri = e.ns(); } if(nsUri.equals("##default")) { // look for the annotation on the declaring class Class c = method.getDeclaringClass(); XmlElement ce = c.getAnnotation(XmlElement.class); if(ce!=null) { nsUri = ce.ns(); } if(nsUri.equals("##default")) // then default to the XmlNamespace nsUri = getNamespace(c.getPackage()); } if(rt==Void.TYPE) { // leaf element with just a value boolean isCDATA = method.getAnnotation(XmlCDATA.class)!=null; StartTag st = new StartTag(document,nsUri,localName); addChild(st); for( Object arg : args ) { Text text; if(isCDATA) text = new Cdata(document,st,arg); else text = new Pcdata(document,st,arg); addChild(text); } addChild(new EndTag()); return null; } if(TypedXmlWriter.class.isAssignableFrom(rt)) { // sub writer return _element(nsUri,localName,(Class)rt); } throw new IllegalSignatureException("Illegal return type: "+rt); } /** * Decides the namespace URI of the given package. */ private String getNamespace(Package pkg) { if(pkg==null) return ""; String nsUri; XmlNamespace ns = pkg.getAnnotation(XmlNamespace.class); if(ns!=null) nsUri = ns.value(); else nsUri = ""; return nsUri; } /** * Appends this child object to the tail. */ private void addChild(Content child) { tail.setNext(document,child); tail = child; } public void commit() { commit(true); } public void commit(boolean includingAllPredecessors) { _commit(includingAllPredecessors); document.flush(); } private void _commit(boolean includingAllPredecessors) { if(isCommitted()) return; addChild(endTag); if(isRoot()) addChild(new EndDocument()); tail = null; // _commit predecessors if so told if(includingAllPredecessors) { for( ContainerElement e=this; e!=null; e=e.parent ) { while(e.prevOpen!=null) { e.prevOpen._commit(false); // e.prevOpen should change as a result of committing it. } } } // _commit all children recursively while(lastOpenChild!=null) lastOpenChild._commit(false); // remove this node from the link if(parent!=null) { if(parent.lastOpenChild==this) { assert nextOpen==null : "this must be the last one"; parent.lastOpenChild = prevOpen; } else { assert nextOpen.prevOpen==this; nextOpen.prevOpen = this.prevOpen; } if(prevOpen!=null) { assert prevOpen.nextOpen==this; prevOpen.nextOpen = this.nextOpen; } } this.nextOpen = null; this.prevOpen = null; } public void _attribute(String localName, Object value) { _attribute("",localName,value); } public void _attribute(String nsUri, String localName, Object value) { checkStartTag(); startTag.addAttribute(nsUri,localName,value); } public void _attribute(QName attributeName, Object value) { _attribute(attributeName.getNamespaceURI(),attributeName.getLocalPart(),value); } public void _namespace(String uri) { _namespace(uri,false); } public void _namespace(String uri, String prefix) { if(prefix==null) throw new IllegalArgumentException(); checkStartTag(); startTag.addNamespaceDecl(uri,prefix,false); } public void _namespace(String uri, boolean requirePrefix) { checkStartTag(); startTag.addNamespaceDecl(uri,null,requirePrefix); } public void _pcdata(Object value) { // we need to allow this method even when startTag has already been completed. // checkStartTag(); addChild(new Pcdata(document,startTag,value)); } public void _cdata(Object value) { addChild(new Cdata(document,startTag,value)); } public void _comment(Object value) throws UnsupportedOperationException { addChild(new Comment(document,startTag,value)); } public T _element(String localName, Class contentModel) { return _element(nsUri,localName,contentModel); } public T _element(QName tagName, Class contentModel) { return _element(tagName.getNamespaceURI(),tagName.getLocalPart(),contentModel); } public T _element(Class contentModel) { return _element(TXW.getTagName(contentModel),contentModel); } public T _cast(Class facadeType) { return facadeType.cast(Proxy.newProxyInstance(facadeType.getClassLoader(),new Class[]{facadeType},this)); } public T _element(String nsUri, String localName, Class contentModel) { ContainerElement child = new ContainerElement(document,this,nsUri,localName); addChild(child.startTag); tail = child.endTag; // update uncommitted link list if(lastOpenChild!=null) { assert lastOpenChild.parent==this; assert child.prevOpen==null; assert child.nextOpen==null; child.prevOpen = lastOpenChild; assert lastOpenChild.nextOpen==null; lastOpenChild.nextOpen = child; } this.lastOpenChild = child; return child._cast(contentModel); } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/Content.java000066400000000000000000000040051157142111200227660ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2; /** * @author Kohsuke Kawaguchi */ abstract class Content { private Content next; /** * Returns null if the next token has not decided yet. */ final Content getNext() { return next; } /** * * @param doc * A {@link Content} object is so light-weight that * it doesn't even remember what document it belongs to. * So the caller needs to "remind" a {@link Content} * who its owner is. */ final void setNext(Document doc,Content next) { assert next!=null; assert this.next==null : "next of "+this+" is already set to "+this.next; this.next = next; doc.run(); } /** * Returns true if this content is ready to be committed. */ boolean isReadyToCommit() { return true; } /** * Returns true if this {@link Content} can guarantee that * no more new namespace decls is necessary for the currently * pending start tag. */ abstract boolean concludesPendingStartTag(); /** * Accepts a visitor. */ abstract void accept(ContentVisitor visitor); /** * Called when this content is written to the output. */ public void written() { } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/ContentVisitor.java000066400000000000000000000022551157142111200243530ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2; /** * Visits {@link Content}. * * @author Kohsuke Kawaguchi */ interface ContentVisitor { void onStartDocument(); void onEndDocument(); void onEndTag(); void onPcdata(StringBuilder buffer); void onCdata(StringBuilder buffer); void onStartTag(String nsUri, String localName, Attribute attributes, NamespaceDecl namespaces); void onComment(StringBuilder buffer); } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/DatatypeWriter.java000066400000000000000000000060531157142111200243310ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2; import javax.xml.namespace.QName; /** * Pluggable datatype writer. * * @author Kohsuke Kawaguchi */ public interface DatatypeWriter

{ /** * Gets the Java class that this writer can write. * * @return * must not be null. Must be the same value always. */ Class
getType(); /** * Prints the given datatype object and appends that result * into the given buffer. * * @param dt * the datatype object to be printed. * @param resolver * allows the converter to declare additional namespace prefixes. */ void print(DT dt, NamespaceResolver resolver, StringBuilder buf); static final DatatypeWriter[] BUILDIN = new DatatypeWriter[] { new DatatypeWriter() { public Class getType() { return String.class; } public void print(String s, NamespaceResolver resolver, StringBuilder buf) { buf.append(s); } }, new DatatypeWriter() { public Class getType() { return Integer.class; } public void print(Integer i, NamespaceResolver resolver, StringBuilder buf) { buf.append(i); } }, new DatatypeWriter() { public Class getType() { return Float.class; } public void print(Float f, NamespaceResolver resolver, StringBuilder buf) { buf.append(f); } }, new DatatypeWriter() { public Class getType() { return Double.class; } public void print(Double d, NamespaceResolver resolver, StringBuilder buf) { buf.append(d); } }, new DatatypeWriter() { public Class getType() { return QName.class; } public void print(QName qn, NamespaceResolver resolver, StringBuilder buf) { String p = resolver.getPrefix(qn.getNamespaceURI()); if(p.length()!=0) buf.append(p).append(':'); buf.append(qn.getLocalPart()); } } }; } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/Document.java000066400000000000000000000235501157142111200231400ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2; import com.sun.xml.txw2.output.XmlSerializer; import java.util.Map; import java.util.HashMap; /** * Coordinates the entire writing process. * * @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public final class Document { private final XmlSerializer out; /** * Set to true once we invoke {@link XmlSerializer#startDocument()}. * *

* This is so that we can defer the writing as much as possible. */ private boolean started=false; /** * Currently active writer. * *

* This points to the last written token. */ private Content current = null; private final Map datatypeWriters = new HashMap(); /** * Used to generate unique namespace prefix. */ private int iota = 1; /** * Used to keep track of in-scope namespace bindings declared in ancestors. */ private final NamespaceSupport inscopeNamespace = new NamespaceSupport(); /** * Remembers the namespace declarations of the last unclosed start tag, * so that we can fix up dummy prefixes in {@link Pcdata}. */ private NamespaceDecl activeNamespaces; Document(XmlSerializer out) { this.out = out; for( DatatypeWriter dw : DatatypeWriter.BUILDIN ) datatypeWriters.put(dw.getType(),dw); } void flush() { out.flush(); } void setFirstContent(Content c) { assert current==null; current = new StartDocument(); current.setNext(this,c); } /** * Defines additional user object -> string conversion logic. * *

* Applications can add their own {@link DatatypeWriter} so that * application-specific objects can be turned into {@link String} * for output. * * @param dw * The {@link DatatypeWriter} to be added. Must not be null. */ public void addDatatypeWriter( DatatypeWriter dw ) { datatypeWriters.put(dw.getType(),dw); } /** * Performs the output as much as possible */ void run() { while(true) { Content next = current.getNext(); if(next==null || !next.isReadyToCommit()) return; next.accept(visitor); next.written(); current = next; } } /** * Appends the given object to the end of the given buffer. * * @param nsResolver * use */ void writeValue( Object obj, NamespaceResolver nsResolver, StringBuilder buf ) { if(obj==null) throw new IllegalArgumentException("argument contains null"); if(obj instanceof Object[]) { for( Object o : (Object[])obj ) writeValue(o,nsResolver,buf); return; } if(obj instanceof Iterable) { for( Object o : (Iterable)obj ) writeValue(o,nsResolver,buf); return; } if(buf.length()>0) buf.append(' '); Class c = obj.getClass(); while(c!=null) { DatatypeWriter dw = datatypeWriters.get(c); if(dw!=null) { dw.print(obj,nsResolver,buf); return; } c = c.getSuperclass(); } // if nothing applies, just use toString buf.append(obj); } // I wanted to hide those write method from users private final ContentVisitor visitor = new ContentVisitor() { public void onStartDocument() { // the startDocument token is used as the sentry, so this method shall never // be called. // out.startDocument() is invoked when we write the start tag of the root element. throw new IllegalStateException(); } public void onEndDocument() { out.endDocument(); } public void onEndTag() { out.endTag(); inscopeNamespace.popContext(); activeNamespaces = null; } public void onPcdata(StringBuilder buffer) { if(activeNamespaces!=null) buffer = fixPrefix(buffer); out.text(buffer); } public void onCdata(StringBuilder buffer) { if(activeNamespaces!=null) buffer = fixPrefix(buffer); out.cdata(buffer); } public void onComment(StringBuilder buffer) { if(activeNamespaces!=null) buffer = fixPrefix(buffer); out.comment(buffer); } public void onStartTag(String nsUri, String localName, Attribute attributes, NamespaceDecl namespaces) { assert nsUri!=null; assert localName!=null; activeNamespaces = namespaces; if(!started) { started = true; out.startDocument(); } inscopeNamespace.pushContext(); // declare the explicitly bound namespaces for( NamespaceDecl ns=namespaces; ns!=null; ns=ns.next ) { ns.declared = false; // reset this flag if(ns.prefix!=null) { String uri = inscopeNamespace.getURI(ns.prefix); if(uri!=null && uri.equals(ns.uri)) ; // already declared else { // declare this new binding inscopeNamespace.declarePrefix(ns.prefix,ns.uri); ns.declared = true; } } } // then use in-scope namespace to assign prefixes to others for( NamespaceDecl ns=namespaces; ns!=null; ns=ns.next ) { if(ns.prefix==null) { if(inscopeNamespace.getURI("").equals(ns.uri)) ns.prefix=""; else { String p = inscopeNamespace.getPrefix(ns.uri); if(p==null) { // assign a new one while(inscopeNamespace.getURI(p=newPrefix())!=null) ; ns.declared = true; inscopeNamespace.declarePrefix(p,ns.uri); } ns.prefix = p; } } } // the first namespace decl must be the one for the element assert namespaces.uri.equals(nsUri); assert namespaces.prefix!=null : "a prefix must have been all allocated"; out.beginStartTag(nsUri,localName,namespaces.prefix); // declare namespaces for( NamespaceDecl ns=namespaces; ns!=null; ns=ns.next ) { if(ns.declared) out.writeXmlns( ns.prefix, ns.uri ); } // writeBody attributes for( Attribute a=attributes; a!=null; a=a.next) { String prefix; if(a.nsUri.length()==0) prefix=""; else prefix=inscopeNamespace.getPrefix(a.nsUri); out.writeAttribute( a.nsUri, a.localName, prefix, fixPrefix(a.value) ); } out.endStartTag(nsUri,localName,namespaces.prefix); } }; /** * Used by {@link #newPrefix()}. */ private final StringBuilder prefixSeed = new StringBuilder("ns"); private int prefixIota = 0; /** * Allocates a new unique prefix. */ private String newPrefix() { prefixSeed.setLength(2); prefixSeed.append(++prefixIota); return prefixSeed.toString(); } /** * Replaces dummy prefixes in the value to the real ones * by using {@link #activeNamespaces}. * * @return * the buffer passed as the buf parameter. */ private StringBuilder fixPrefix(StringBuilder buf) { assert activeNamespaces!=null; int i; int len=buf.length(); for(i=0;i * This module, both source code and documentation, is in the * Public Domain, and comes with NO WARRANTY. * See http://www.saxproject.org * for further information. * * *

This class encapsulates the logic of Namespace processing: it * tracks the declarations currently in force for each context and * automatically processes qualified XML names into their Namespace * parts; it can also be used in reverse for generating XML qnames * from Namespaces.

* *

Namespace support objects are reusable, but the reset method * must be invoked between each session.

* *

Here is a simple session:

* *
 * String parts[] = new String[3];
 * NamespaceSupport support = new NamespaceSupport();
 *
 * support.pushContext();
 * support.declarePrefix("", "http://www.w3.org/1999/xhtml");
 * support.declarePrefix("dc", "http://www.purl.org/dc#");
 *
 * parts = support.processName("p", parts, false);
 * System.out.println("Namespace URI: " + parts[0]);
 * System.out.println("Local name: " + parts[1]);
 * System.out.println("Raw name: " + parts[2]);
 *
 * parts = support.processName("dc:title", parts, false);
 * System.out.println("Namespace URI: " + parts[0]);
 * System.out.println("Local name: " + parts[1]);
 * System.out.println("Raw name: " + parts[2]);
 *
 * support.popContext();
 * 
* *

Note that this class is optimized for the use case where most * elements do not contain Namespace declarations: if the same * prefix/URI mapping is repeated for each context (for example), this * class will be somewhat less efficient.

* *

Although SAX drivers (parsers) may choose to use this class to * implement namespace handling, they are not required to do so. * Applications must track namespace information themselves if they * want to use namespace information. * * @since SAX 2.0 * @author David Megginson * @version 2.0.1 (sax2r2) */ final class NamespaceSupport { //////////////////////////////////////////////////////////////////// // Constants. //////////////////////////////////////////////////////////////////// /** * The XML Namespace URI as a constant. * The value is http://www.w3.org/XML/1998/namespace * as defined in the "Namespaces in XML" * recommendation. * *

This is the Namespace URI that is automatically mapped * to the "xml" prefix.

*/ public final static String XMLNS = "http://www.w3.org/XML/1998/namespace"; /** * The namespace declaration URI as a constant. * The value is http://www.w3.org/xmlns/2000/, as defined * in a backwards-incompatible erratum to the "Namespaces in XML" * recommendation. Because that erratum postdated SAX2, SAX2 defaults * to the original recommendation, and does not normally use this URI. * * *

This is the Namespace URI that is optionally applied to * xmlns and xmlns:* attributes, which are used to * declare namespaces.

* * @since SAX 2.1alpha * @see #setNamespaceDeclUris * @see #isNamespaceDeclUris */ public final static String NSDECL = "http://www.w3.org/xmlns/2000/"; /** * An empty enumeration. */ private final static Enumeration EMPTY_ENUMERATION = new Vector().elements(); //////////////////////////////////////////////////////////////////// // Constructor. //////////////////////////////////////////////////////////////////// /** * Create a new Namespace support object. */ public NamespaceSupport () { reset(); } //////////////////////////////////////////////////////////////////// // Context management. //////////////////////////////////////////////////////////////////// /** * Reset this Namespace support object for reuse. * *

It is necessary to invoke this method before reusing the * Namespace support object for a new session. If namespace * declaration URIs are to be supported, that flag must also * be set to a non-default value. *

* * @see #setNamespaceDeclUris */ public void reset () { contexts = new Context[32]; namespaceDeclUris = false; contextPos = 0; contexts[contextPos] = currentContext = new Context(); currentContext.declarePrefix("xml", XMLNS); } /** * Start a new Namespace context. * The new context will automatically inherit * the declarations of its parent context, but it will also keep * track of which declarations were made within this context. * *

Event callback code should start a new context once per element. * This means being ready to call this in either of two places. * For elements that don't include namespace declarations, the * ContentHandler.startElement() callback is the right place. * For elements with such a declaration, it'd done in the first * ContentHandler.startPrefixMapping() callback. * A boolean flag can be used to * track whether a context has been started yet. When either of * those methods is called, it checks the flag to see if a new context * needs to be started. If so, it starts the context and sets the * flag. After ContentHandler.startElement() * does that, it always clears the flag. * *

Normally, SAX drivers would push a new context at the beginning * of each XML element. Then they perform a first pass over the * attributes to process all namespace declarations, making * ContentHandler.startPrefixMapping() callbacks. * Then a second pass is made, to determine the namespace-qualified * names for all attributes and for the element name. * Finally all the information for the * ContentHandler.startElement() callback is available, * so it can then be made. * *

The Namespace support object always starts with a base context * already in force: in this context, only the "xml" prefix is * declared.

* * @see org.xml.sax.ContentHandler * @see #popContext */ public void pushContext () { int max = contexts.length; contextPos++; // Extend the array if necessary if (contextPos >= max) { Context newContexts[] = new Context[max*2]; System.arraycopy(contexts, 0, newContexts, 0, max); max *= 2; contexts = newContexts; } // Allocate the context if necessary. currentContext = contexts[contextPos]; if (currentContext == null) { contexts[contextPos] = currentContext = new Context(); } // Set the parent, if any. if (contextPos > 0) { currentContext.setParent(contexts[contextPos - 1]); } } /** * Revert to the previous Namespace context. * *

Normally, you should pop the context at the end of each * XML element. After popping the context, all Namespace prefix * mappings that were previously in force are restored.

* *

You must not attempt to declare additional Namespace * prefixes after popping a context, unless you push another * context first.

* * @see #pushContext */ public void popContext () { contexts[contextPos].clear(); contextPos--; if (contextPos < 0) { throw new EmptyStackException(); } currentContext = contexts[contextPos]; } //////////////////////////////////////////////////////////////////// // Operations within a context. //////////////////////////////////////////////////////////////////// /** * Declare a Namespace prefix. All prefixes must be declared * before they are referenced. For example, a SAX driver (parser) * would scan an element's attributes * in two passes: first for namespace declarations, * then a second pass using {@link #processName processName()} to * interpret prefixes against (potentially redefined) prefixes. * *

This method declares a prefix in the current Namespace * context; the prefix will remain in force until this context * is popped, unless it is shadowed in a descendant context.

* *

To declare the default element Namespace, use the empty string as * the prefix.

* *

Note that there is an asymmetry in this library: {@link * #getPrefix getPrefix} will not return the "" prefix, * even if you have declared a default element namespace. * To check for a default namespace, * you have to look it up explicitly using {@link #getURI getURI}. * This asymmetry exists to make it easier to look up prefixes * for attribute names, where the default prefix is not allowed.

* * @param prefix The prefix to declare, or the empty string to * indicate the default element namespace. This may never have * the value "xml" or "xmlns". * @param uri The Namespace URI to associate with the prefix. * @return true if the prefix was legal, false otherwise * * @see #processName * @see #getURI * @see #getPrefix */ public boolean declarePrefix (String prefix, String uri) { if (prefix.equals("xml") || prefix.equals("xmlns")) { return false; } else { currentContext.declarePrefix(prefix, uri); return true; } } /** * Process a raw XML qualified name, after all declarations in the * current context have been handled by {@link #declarePrefix * declarePrefix()}. * *

This method processes a raw XML qualified name in the * current context by removing the prefix and looking it up among * the prefixes currently declared. The return value will be the * array supplied by the caller, filled in as follows:

* *
*
parts[0]
*
The Namespace URI, or an empty string if none is * in use.
*
parts[1]
*
The local name (without prefix).
*
parts[2]
*
The original raw name.
*
* *

All of the strings in the array will be internalized. If * the raw name has a prefix that has not been declared, then * the return value will be null.

* *

Note that attribute names are processed differently than * element names: an unprefixed element name will receive the * default Namespace (if any), while an unprefixed attribute name * will not.

* * @param qName The XML qualified name to be processed. * @param parts An array supplied by the caller, capable of * holding at least three members. * @param isAttribute A flag indicating whether this is an * attribute name (true) or an element name (false). * @return The supplied array holding three internalized strings * representing the Namespace URI (or empty string), the * local name, and the XML qualified name; or null if there * is an undeclared prefix. * @see #declarePrefix * @see java.lang.String#intern */ public String [] processName (String qName, String parts[], boolean isAttribute) { String myParts[] = currentContext.processName(qName, isAttribute); if (myParts == null) { return null; } else { parts[0] = myParts[0]; parts[1] = myParts[1]; parts[2] = myParts[2]; return parts; } } /** * Look up a prefix and get the currently-mapped Namespace URI. * *

This method looks up the prefix in the current context. * Use the empty string ("") for the default Namespace.

* * @param prefix The prefix to look up. * @return The associated Namespace URI, or null if the prefix * is undeclared in this context. * @see #getPrefix * @see #getPrefixes */ public String getURI (String prefix) { return currentContext.getURI(prefix); } /** * Return an enumeration of all prefixes whose declarations are * active in the current context. * This includes declarations from parent contexts that have * not been overridden. * *

Note: if there is a default prefix, it will not be * returned in this enumeration; check for the default prefix * using the {@link #getURI getURI} with an argument of "".

* * @return An enumeration of prefixes (never empty). * @see #getDeclaredPrefixes * @see #getURI */ public Enumeration getPrefixes () { return currentContext.getPrefixes(); } /** * Return one of the prefixes mapped to a Namespace URI. * *

If more than one prefix is currently mapped to the same * URI, this method will make an arbitrary selection; if you * want all of the prefixes, use the {@link #getPrefixes} * method instead.

* *

Note: this will never return the empty (default) prefix; * to check for a default prefix, use the {@link #getURI getURI} * method with an argument of "".

* * @param uri the namespace URI * @return one of the prefixes currently mapped to the URI supplied, * or null if none is mapped or if the URI is assigned to * the default namespace * @see #getPrefixes(java.lang.String) * @see #getURI */ public String getPrefix (String uri) { return currentContext.getPrefix(uri); } /** * Return an enumeration of all prefixes for a given URI whose * declarations are active in the current context. * This includes declarations from parent contexts that have * not been overridden. * *

This method returns prefixes mapped to a specific Namespace * URI. The xml: prefix will be included. If you want only one * prefix that's mapped to the Namespace URI, and you don't care * which one you get, use the {@link #getPrefix getPrefix} * method instead.

* *

Note: the empty (default) prefix is never included * in this enumeration; to check for the presence of a default * Namespace, use the {@link #getURI getURI} method with an * argument of "".

* * @param uri The Namespace URI. * @return An enumeration of prefixes (never empty). * @see #getPrefix * @see #getDeclaredPrefixes * @see #getURI */ public Enumeration getPrefixes (String uri) { Vector prefixes = new Vector(); Enumeration allPrefixes = getPrefixes(); while (allPrefixes.hasMoreElements()) { String prefix = (String)allPrefixes.nextElement(); if (uri.equals(getURI(prefix))) { prefixes.addElement(prefix); } } return prefixes.elements(); } /** * Return an enumeration of all prefixes declared in this context. * *

The empty (default) prefix will be included in this * enumeration; note that this behaviour differs from that of * {@link #getPrefix} and {@link #getPrefixes}.

* * @return An enumeration of all prefixes declared in this * context. * @see #getPrefixes * @see #getURI */ public Enumeration getDeclaredPrefixes () { return currentContext.getDeclaredPrefixes(); } /** * Controls whether namespace declaration attributes are placed * into the {@link #NSDECL NSDECL} namespace * by {@link #processName processName()}. This may only be * changed before any contexts have been pushed. * * @since SAX 2.1alpha * * @exception IllegalStateException when attempting to set this * after any context has been pushed. */ public void setNamespaceDeclUris (boolean value) { if (contextPos != 0) throw new IllegalStateException (); if (value == namespaceDeclUris) return; namespaceDeclUris = value; if (value) currentContext.declarePrefix ("xmlns", NSDECL); else { contexts[contextPos] = currentContext = new Context(); currentContext.declarePrefix("xml", XMLNS); } } /** * Returns true if namespace declaration attributes are placed into * a namespace. This behavior is not the default. * * @since SAX 2.1alpha */ public boolean isNamespaceDeclUris () { return namespaceDeclUris; } //////////////////////////////////////////////////////////////////// // Internal state. //////////////////////////////////////////////////////////////////// private Context contexts[]; private Context currentContext; private int contextPos; private boolean namespaceDeclUris; //////////////////////////////////////////////////////////////////// // Internal classes. //////////////////////////////////////////////////////////////////// /** * Internal class for a single Namespace context. * *

This module caches and reuses Namespace contexts, * so the number allocated * will be equal to the element depth of the document, not to the total * number of elements (i.e. 5-10 rather than tens of thousands). * Also, data structures used to represent contexts are shared when * possible (child contexts without declarations) to further reduce * the amount of memory that's consumed. *

*/ final class Context { /** * Create the root-level Namespace context. */ Context () { copyTables(); } /** * (Re)set the parent of this Namespace context. * The context must either have been freshly constructed, * or must have been cleared. * * @param context The parent Namespace context object. */ void setParent (Context parent) { this.parent = parent; declarations = null; prefixTable = parent.prefixTable; uriTable = parent.uriTable; elementNameTable = parent.elementNameTable; attributeNameTable = parent.attributeNameTable; defaultNS = parent.defaultNS; declSeen = false; } /** * Makes associated state become collectible, * invalidating this context. * {@link #setParent} must be called before * this context may be used again. */ void clear () { parent = null; prefixTable = null; uriTable = null; elementNameTable = null; attributeNameTable = null; defaultNS = ""; } /** * Declare a Namespace prefix for this context. * * @param prefix The prefix to declare. * @param uri The associated Namespace URI. * @see org.xml.sax.helpers.NamespaceSupport#declarePrefix */ void declarePrefix (String prefix, String uri) { // Lazy processing... // if (!declsOK) // throw new IllegalStateException ( // "can't declare any more prefixes in this context"); if (!declSeen) { copyTables(); } if (declarations == null) { declarations = new Vector(); } prefix = prefix.intern(); uri = uri.intern(); if ("".equals(prefix)) { defaultNS = uri; } else { prefixTable.put(prefix, uri); uriTable.put(uri, prefix); // may wipe out another prefix } declarations.addElement(prefix); } /** * Process an XML qualified name in this context. * * @param qName The XML qualified name. * @param isAttribute true if this is an attribute name. * @return An array of three strings containing the * URI part (or empty string), the local part, * and the raw name, all internalized, or null * if there is an undeclared prefix. * @see org.xml.sax.helpers.NamespaceSupport#processName */ String [] processName (String qName, boolean isAttribute) { String name[]; Hashtable table; // Select the appropriate table. if (isAttribute) { table = attributeNameTable; } else { table = elementNameTable; } // Start by looking in the cache, and // return immediately if the name // is already known in this content name = (String[])table.get(qName); if (name != null) { return name; } // We haven't seen this name in this // context before. Maybe in the parent // context, but we can't assume prefix // bindings are the same. name = new String[3]; name[2] = qName.intern(); int index = qName.indexOf(':'); // No prefix. if (index == -1) { if (isAttribute) { if (qName == "xmlns" && namespaceDeclUris) name[0] = NSDECL; else name[0] = ""; } else { name[0] = defaultNS; } name[1] = name[2]; } // Prefix else { String prefix = qName.substring(0, index); String local = qName.substring(index+1); String uri; if ("".equals(prefix)) { uri = defaultNS; } else { uri = (String)prefixTable.get(prefix); } if (uri == null || (!isAttribute && "xmlns".equals (prefix))) { return null; } name[0] = uri; name[1] = local.intern(); } // Save in the cache for future use. // (Could be shared with parent context...) table.put(name[2], name); return name; } /** * Look up the URI associated with a prefix in this context. * * @param prefix The prefix to look up. * @return The associated Namespace URI, or null if none is * declared. * @see org.xml.sax.helpers.NamespaceSupport#getURI */ String getURI (String prefix) { if ("".equals(prefix)) { return defaultNS; } else if (prefixTable == null) { return null; } else { return (String)prefixTable.get(prefix); } } /** * Look up one of the prefixes associated with a URI in this context. * *

Since many prefixes may be mapped to the same URI, * the return value may be unreliable.

* * @param uri The URI to look up. * @return The associated prefix, or null if none is declared. * @see org.xml.sax.helpers.NamespaceSupport#getPrefix */ String getPrefix (String uri) { if (uriTable == null) { return null; } else { return (String)uriTable.get(uri); } } /** * Return an enumeration of prefixes declared in this context. * * @return An enumeration of prefixes (possibly empty). * @see org.xml.sax.helpers.NamespaceSupport#getDeclaredPrefixes */ Enumeration getDeclaredPrefixes () { if (declarations == null) { return EMPTY_ENUMERATION; } else { return declarations.elements(); } } /** * Return an enumeration of all prefixes currently in force. * *

The default prefix, if in force, is not * returned, and will have to be checked for separately.

* * @return An enumeration of prefixes (never empty). * @see org.xml.sax.helpers.NamespaceSupport#getPrefixes */ Enumeration getPrefixes () { if (prefixTable == null) { return EMPTY_ENUMERATION; } else { return prefixTable.keys(); } } //////////////////////////////////////////////////////////////// // Internal methods. //////////////////////////////////////////////////////////////// /** * Copy on write for the internal tables in this context. * *

This class is optimized for the normal case where most * elements do not contain Namespace declarations.

*/ private void copyTables () { if (prefixTable != null) { prefixTable = (Hashtable)prefixTable.clone(); } else { prefixTable = new Hashtable(); } if (uriTable != null) { uriTable = (Hashtable)uriTable.clone(); } else { uriTable = new Hashtable(); } elementNameTable = new Hashtable(); attributeNameTable = new Hashtable(); declSeen = true; } //////////////////////////////////////////////////////////////// // Protected state. //////////////////////////////////////////////////////////////// Hashtable prefixTable; Hashtable uriTable; Hashtable elementNameTable; Hashtable attributeNameTable; String defaultNS = ""; //////////////////////////////////////////////////////////////// // Internal state. //////////////////////////////////////////////////////////////// private Vector declarations = null; private boolean declSeen = false; private Context parent = null; } } // end of NamespaceSupport.java txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/Pcdata.java000066400000000000000000000021001157142111200225420ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2; /** * PCDATA. * * @author Kohsuke Kawaguchi */ final class Pcdata extends Text { Pcdata(Document document, NamespaceResolver nsResolver, Object obj) { super(document, nsResolver, obj); } void accept(ContentVisitor visitor) { visitor.onPcdata(buffer); } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/StartDocument.java000066400000000000000000000020071157142111200241500ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2; /** * @author Kohsuke Kawaguchi */ final class StartDocument extends Content { boolean concludesPendingStartTag() { return true; } void accept(ContentVisitor visitor) { visitor.onStartDocument(); } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/StartTag.java000066400000000000000000000167701157142111200231210ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2; import javax.xml.namespace.QName; /** * Start tag. * *

* This object implements {@link NamespaceResolver} for attribute values. * * @author Kohsuke Kawaguchi */ class StartTag extends Content implements NamespaceResolver { /** * Tag name of the element. * *

* This field is also used as a flag to indicate * whether the start tag has been written. * This field is initially set to non-null, and * then reset to null when it's written. */ private String uri; // but we keep the local name non-null so that // we can diagnose an error private final String localName; private Attribute firstAtt; private Attribute lastAtt; /** * If this {@link StartTag} has the parent {@link ContainerElement}, * that value. Otherwise null. */ private ContainerElement owner; /** * Explicitly given namespace declarations on this element. * *

* Additional namespace declarations might be necessary to * generate child {@link QName}s and attributes. */ private NamespaceDecl firstNs; private NamespaceDecl lastNs; final Document document; public StartTag(ContainerElement owner, String uri, String localName) { this(owner.document,uri,localName); this.owner = owner; } public StartTag(Document document, String uri, String localName) { assert uri!=null; assert localName!=null; this.uri = uri; this.localName = localName; this.document = document; // TODO: think about a better way to maintain namespace decls. // this requires at least one NamespaceDecl per start tag, // which is rather expensive. addNamespaceDecl(uri,null,false); } public void addAttribute(String nsUri, String localName, Object arg) { checkWritable(); // look for the existing ones Attribute a; for(a=firstAtt; a!=null; a=a.next) { if(a.hasName(nsUri,localName)) { break; } } // if not found, declare a new one if(a==null) { a = new Attribute(nsUri,localName); if(lastAtt==null) { assert firstAtt==null; firstAtt = lastAtt = a; } else { assert firstAtt!=null; lastAtt.next = a; lastAtt = a; } if(nsUri.length()>0) addNamespaceDecl(nsUri,null,true); } document.writeValue(arg,this,a.value); } /** * Declares a new namespace URI on this tag. * * @param uri * namespace URI to be bound. Can be empty, but must not be null. * @param prefix * If non-null and non-empty, this prefix is bound to the URI * on this element. If empty, then the runtime will still try to * use the URI as the default namespace, but it may fail to do so * because of the constraints in the XML. *

* If this parameter is null, the runtime will allocate an unique prefix. * @param requirePrefix * Used only when the prefix parameter is null. If true, this indicates * that the non-empty prefix must be assigned to this URI. If false, * then this URI might be used as the default namespace. *

* Normally you just need to set it to false. */ public NamespaceDecl addNamespaceDecl(String uri, String prefix,boolean requirePrefix) { checkWritable(); if(uri==null) throw new IllegalArgumentException(); if(uri.length()==0) { if(requirePrefix) throw new IllegalArgumentException("The empty namespace cannot have a non-empty prefix"); if(prefix!=null && prefix.length()>0) throw new IllegalArgumentException("The empty namespace can be only bound to the empty prefix"); prefix = ""; } // check for the duplicate for(NamespaceDecl n=firstNs; n!=null; n=n.next) { if(uri.equals(n.uri)) { if(prefix==null) { // reuse this binding n.requirePrefix |= requirePrefix; return n; } if(n.prefix==null) { // reuse this binding n.prefix = prefix; n.requirePrefix |= requirePrefix; return n; } if(prefix.equals(n.prefix)) { // reuse this binding n.requirePrefix |= requirePrefix; return n; } } if(prefix!=null && n.prefix!=null && n.prefix.equals(prefix)) throw new IllegalArgumentException( "Prefix '"+prefix+"' is already bound to '"+n.uri+'\''); } NamespaceDecl ns = new NamespaceDecl(document.assignNewId(),uri,prefix,requirePrefix); if(lastNs==null) { assert firstNs==null; firstNs = lastNs = ns; } else { assert firstNs!=null; lastNs.next = ns; lastNs = ns; } return ns; } /** * Throws an error if the start tag has already been committed. */ private void checkWritable() { if(isWritten()) throw new IllegalStateException( "The start tag of "+this.localName+" has already been written. " + "If you need out of order writing, see the TypedXmlWriter.block method"); } /** * Returns true if this start tag has already been written. */ boolean isWritten() { return uri==null; } /** * A {@link StartTag} can be only written after * we are sure that all the necessary namespace declarations are given. */ boolean isReadyToCommit() { if(owner!=null && owner.isBlocked()) return false; for( Content c=getNext(); c!=null; c=c.getNext() ) if(c.concludesPendingStartTag()) return true; return false; } public void written() { firstAtt = lastAtt = null; uri = null; if(owner!=null) { assert owner.startTag==this; owner.startTag = null; } } boolean concludesPendingStartTag() { return true; } void accept(ContentVisitor visitor) { visitor.onStartTag(uri,localName,firstAtt,firstNs); } public String getPrefix(String nsUri) { NamespaceDecl ns = addNamespaceDecl(nsUri,null,false); if(ns.prefix!=null) // if the prefix has already been declared, use it. return ns.prefix; return ns.dummyPrefix; } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/TXW.java000066400000000000000000000065261157142111200220500ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2; import com.sun.xml.txw2.output.XmlSerializer; import com.sun.xml.txw2.annotation.XmlElement; import com.sun.xml.txw2.annotation.XmlNamespace; import javax.xml.namespace.QName; /** * Entry point to TXW. * * @author Kohsuke Kawaguchi */ public abstract class TXW { private TXW() {} // no instanciation please /*package*/ static QName getTagName( Class c ) { String localName=""; String nsUri="##default"; XmlElement xe = c.getAnnotation(XmlElement.class); if(xe!=null) { localName = xe.value(); nsUri = xe.ns(); } if(localName.length()==0) { localName = c.getName(); int idx = localName.lastIndexOf('.'); if(idx>=0) localName = localName.substring(idx+1); localName = Character.toLowerCase(localName.charAt(0))+localName.substring(1); } if(nsUri.equals("##default")) { Package pkg = c.getPackage(); if(pkg!=null) { XmlNamespace xn = pkg.getAnnotation(XmlNamespace.class); if(xn!=null) nsUri = xn.value(); } } if(nsUri.equals("##default")) nsUri = ""; return new QName(nsUri,localName); } /** * Creates a new {@link TypedXmlWriter} to write a new instance of a document. * * @param rootElement * The {@link TypedXmlWriter} interface that declares the content model of the root element. * This interface must have {@link XmlElement} annotation on it to designate the tag name * of the root element. * @param out * The target of the writing. */ public static T create( Class rootElement, XmlSerializer out ) { Document doc = new Document(out); QName n = getTagName(rootElement); return new ContainerElement(doc,null,n.getNamespaceURI(),n.getLocalPart())._cast(rootElement); } /** * Creates a new {@link TypedXmlWriter} to write a new instance of a document. * *

* Similar to the other method, but this version allows the caller to set the * tag name at the run-time. * * @param tagName * The tag name of the root document. * * @see #create(Class,XmlSerializer) */ public static T create( QName tagName, Class rootElement, XmlSerializer out ) { return new ContainerElement(new Document(out),null,tagName.getNamespaceURI(),tagName.getLocalPart())._cast(rootElement); } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/Text.java000066400000000000000000000023231157142111200223010ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2; /** * {@link Pcdata} or {@link Cdata}. * * @author Kohsuke Kawaguchi */ abstract class Text extends Content { /** * The text to be writtten. */ protected final StringBuilder buffer = new StringBuilder(); protected Text(Document document, NamespaceResolver nsResolver, Object obj) { document.writeValue(obj,nsResolver,buffer); } boolean concludesPendingStartTag() { return false; } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/TxwException.java000066400000000000000000000022531157142111200240200ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2; /** * Signals errors in the TXW processing. */ public class TxwException extends RuntimeException { public TxwException(String message) { super(message); } public TxwException(Throwable cause) { super(cause); } public TxwException(String message, Throwable cause) { super(message, cause); } private static final long serialVersionUID = 1L; } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/TypedXmlWriter.java000066400000000000000000000175321157142111200243300ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2; import com.sun.xml.txw2.annotation.XmlElement; import com.sun.xml.txw2.output.XmlSerializer; import javax.xml.namespace.QName; /** * Defines common operations for all typed XML writers. * Root of all typed XML writer interfaces. * *

* This interface defines a series of methods to allow client applications * to write arbitrary well-formed documents. * * @author Kohsuke Kawaguchi */ public interface TypedXmlWriter { /** * Commits this element (and all its descendants) to the output. * *

* Short for _commit(true). */ void commit(); /** * Commits this element (and all its descendants) to the output. * *

* Once a writer is committed, nothing can be added to it further. * Committing allows TXW to output a part of the document even * if the rest has not yet been written. * * @param includingAllPredecessors * if false, this operation will _commit this writer and all its * descendants writers. If true, in addition to those writers, * this operation will close all the writers before this writer * in the document order. */ void commit(boolean includingAllPredecessors); /** * Blocks the writing of the start tag so that * new attributes can be added even after child * elements are appended. * *

* This blocks the output at the token before the start tag until * the {@link #commit()} method is called to _commit this element. * *

* For more information, see the TXW documentation. */ void block(); /** * Gets the {@link Document} object that this writer is writing to. * * @return * always non-null. */ Document getDocument(); /** * Adds an attribute of the given name and the value. * *

* Short for

_attribute("",localName,value);
* * @see #_attribute(String, String, Object) */ void _attribute( String localName, Object value ); /** * Adds an attribute of the given name and the value. * *

* Short for

_attribute(new QName(nsUri,localName),value);
* * @see #_attribute(QName, Object) */ void _attribute( String nsUri, String localName, Object value ); /** * Adds an attribute of the given name and the value. * * @param attributeName * must not be null. * @param value * value of the attribute. * must not be null. * See the documentation for the conversion rules. */ void _attribute( QName attributeName, Object value ); /** * Declares a new namespace URI on this element. * *

* The runtime system will assign an unique prefix for the URI. * * @param uri * can be empty, but must not be null. */ void _namespace( String uri ); /** * Declares a new namespace URI on this element to * a specific prefix. * * @param uri * can be empty, but must not be null. * @param prefix * If non-empty, this prefix is bound to the URI * on this element. If empty, then the runtime will still try to * use the URI as the default namespace, but it may fail to do so * because of the constraints in the XML. * * @throws IllegalArgumentException * if the same prefix is already declared on this element. */ void _namespace( String uri, String prefix ); /** * Declares a new namespace URI on this element. * *

* The runtime system will assign an unique prefix for the URI. * * @param uri * can be empty, but must not be null. * @param requirePrefix * if false, this method behaves just like {@link #_namespace(String)}. * if true, this guarantees that the URI is bound to a non empty prefix. */ void _namespace( String uri, boolean requirePrefix ); /** * Appends text data. * * @param value * must not be null. * See the documentation for the conversion rules. */ void _pcdata( Object value ); /** * Appends CDATA section. * * @param value * must not be null. * See the documentation for the conversion rules. */ void _cdata( Object value ); /** * Appends a comment. * * @param value * must not be null. * See the documentation for the conversion rules. * * @throws UnsupportedOperationException * if the underlying {@link XmlSerializer} does not support * writing comments, this exception can be thrown. */ void _comment( Object value ) throws UnsupportedOperationException; /** * Appends a new child element. * *

* Short for

_element(URI of this element,localName,contentModel);
* *

* The namespace URI will be inherited from the parent element. * * @see #_element(String, String, Class) */ T _element( String localName, Class contentModel ); /** * Appends a new child element. * *

* The newly created child element is appended at the end of the children. * * @param nsUri * The namespace URI of the newly created element. * @param localName * The local name of the newly created element. * @param contentModel * The typed XML writer interface used to write the children of * the new child element. * * @return * always return non-null {@link TypedXmlWriter} that can be used * to write the contents of the newly created child element. */ T _element( String nsUri, String localName, Class contentModel ); /** * Appends a new child element. * *

* Short for

_element(tagName.getNamespaceURI(),tagName.getLocalPart(),contentModel);
* * @see #_element(String, String, Class) */ T _element( QName tagName, Class contentModel ); /** * Appends a new child element. * *

* This version of the _element method requires the T class to be * annotated with {@link XmlElement} annotation. The element name will be * taken from there. * * @see #_element(String, String, Class) */ T _element( Class contentModel ); /** * Returns a different interface for this typed XML Writer. * *

* Semantically, this operation is a 'cast' --- it returns the same underlying * writer in a different interface. The returned new writer and the current writer * will write to the same element. * *

* But this is different from Java's ordinary cast because the returned object * is not always the same as the current object. * * @return * always return non-null. */ T _cast( Class targetInterface ); } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/annotation/000077500000000000000000000000001157142111200226645ustar00rootroot00000000000000txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/annotation/XmlAttribute.java000066400000000000000000000040441157142111200261550ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2.annotation; import com.sun.xml.txw2.TypedXmlWriter; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Specifies that the invocation of the method will produce an attribute. * *

* The method signature has to match the form R foo(DT1,DT2,..) * *

* R is either void or the type to which the interface that declares * this method is assignable. In the case of the latter, the method will return * this object, allowing you to chain the multiple attribute method * invocations like {@link StringBuffer}. * *

* DTi must be datatype objects. * *

* When this method is called, a new attribute is added to the current element, * whose value is whitespace-separated text from each of the datatype objects. * * @author Kohsuke Kawaguchi */ @Retention(RUNTIME) @Target({METHOD}) public @interface XmlAttribute { /** * The local name of the attribute. * *

* If left unspecified, the method name is used as the attribute name. * */ String value() default ""; /** * The namespace URI of the attribute. */ String ns() default ""; } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/annotation/XmlCDATA.java000066400000000000000000000022651157142111200250310ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2.annotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.ElementType.METHOD; /** * Used along with {@link XmlElement} to write a CDATA section, * instead of the normal PCDATA. * * @author Kohsuke Kawaguchi */ @Retention(RUNTIME) @Target({METHOD}) public @interface XmlCDATA { } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/annotation/XmlElement.java000066400000000000000000000063411157142111200256050ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2.annotation; import com.sun.xml.txw2.TypedXmlWriter; import com.sun.xml.txw2.TXW; import com.sun.xml.txw2.output.XmlSerializer; import javax.xml.namespace.QName; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.ElementType.METHOD; /** * Specifies the name of the XML element. * *

Used on method

*

* When used on methods declared on interfaces that derive * from {@link TypedXmlWriter}, it specifies that the invocation * of the method will produce an element of the specified name. * *

* The method signature has to match one of the following patterns. * *

*
Child writer: TW foo()
*
TW must be an interface derived from {@link TypedXmlWriter}. * When this method is called, a new child element is started, * and its content can be written by using the returned TW * object. This child element will be ended when its _commit method * is called. *
Leaf element: void foo(DT1,DT2,...)
*
DTi must be datatype objects. * When this method is called, a new child element is started, * followed by the whitespace-separated text data from each of * the datatype objects, followed by the end tag. *
* *

Used on interface

*

* When used on interfaces that derive from {@link TypedXmlWriter}, * it associates an element name with that interface. This name is * used in a few places, such as in {@link TXW#create(Class,XmlSerializer)} * and {@link TypedXmlWriter#_element(Class)}. * * * @author Kohsuke Kawaguchi */ @Retention(RUNTIME) @Target({METHOD,TYPE}) public @interface XmlElement { /** * The local name of the element. */ String value() default ""; /** * The namespace URI of this element. * *

* If the annotation is on an interface and this paramter is left unspecified, * then the namespace URI is taken from {@link XmlNamespace} annotation on * the package that the interface is in. If {@link XmlNamespace} annotation * doesn't exist, the namespace URI will be "". * *

* If the annotation is on a method and this parameter is left unspecified, * then the namespace URI is the same as the namespace URI of the writer interface. */ String ns() default "##default"; } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/annotation/XmlNamespace.java000066400000000000000000000027111157142111200261050ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2.annotation; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.ElementType.PACKAGE; import com.sun.xml.txw2.TypedXmlWriter; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Declares the namespace URI of the {@link TypedXmlWriter}s * in a package. * *

* This annotation is placed on a package. When specified, * it sets the default value of the namespace URI for * all the elements ({@link XmlElement}s) in the given package. * * @author Kohsuke Kawaguchi */ @Retention(RUNTIME) @Target({PACKAGE}) public @interface XmlNamespace { /** * The namespace URI. */ String value(); } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/annotation/XmlValue.java000066400000000000000000000033131157142111200252640ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2.annotation; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.ElementType.METHOD; import com.sun.xml.txw2.DatatypeWriter; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Specifies that the invocation of the method will produce a text * *

* The method signature has to match the form R foo(DT1,DT2,..) * *

* R is either void or the type to which the interface that declares * this method is assignable. In the case of the latter, the method will return * this object, allowing you to chain the multiple method * invocations like {@link StringBuffer}. * *

* DTi must be datatype objects. * *

* When this method is called, whitespace-separated text data * is added from each of the datatype objects. * * @author Kohsuke Kawaguchi */ @Retention(RUNTIME) @Target({METHOD}) public @interface XmlValue { } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/annotation/package.html000066400000000000000000000014021157142111200251420ustar00rootroot00000000000000

Defines a set of annotations that can be used on TypedXmlWriter interfaces.

Package-level Annotation

{@link XmlNamespace} can be used on a package to designate the namespace URI for the whole package.

Interface Annotation

{@link XmlElement} can be used on TypedXmlWriter-derived interfaces to associate a tag name to that interface.

Method Annotations

{@link XmlElement}, {@link XmlAttribute}, or {@link XmlValue} can be used on a method declared on a TypedXmLWriter-derived interface. Those annotations are mutually-exclusive. See their javadoc for details. If none of the above three annotations are specified, {@link XmlElement} is assumed. txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/output/000077500000000000000000000000001157142111200220525ustar00rootroot00000000000000txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/output/CharacterEscapeHandler.java000066400000000000000000000041601157142111200272310ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ /* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2.output; import java.io.IOException; import java.io.Writer; /** * Performs character escaping and write the result * to the output. * * @since 1.0.1 * @author * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public interface CharacterEscapeHandler { /** * @param ch The array of characters. * @param start The starting position. * @param length The number of characters to use. * @param isAttVal true if this is an attribute value literal. */ void escape( char ch[], int start, int length, boolean isAttVal, Writer out ) throws IOException; } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/output/DataWriter.java000066400000000000000000000264521157142111200247740ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ //@@3RD PARTY CODE@@ // DataWriter.java - XML writer for data-oriented files. package com.sun.xml.txw2.output; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import java.io.Writer; import java.util.Stack; /** * Write data- or field-oriented XML. * *

This filter pretty-prints field-oriented XML without mixed content. * all added indentation and newlines will be passed on down * the filter chain (if any).

* *

In general, all whitespace in an XML document is potentially * significant, so a general-purpose XML writing tool like the * {@link XMLWriter} class cannot * add newlines or indentation.

* *

There is, however, a large class of XML documents where information * is strictly fielded: each element contains either character data * or other elements, but not both. For this special case, it is possible * for a writing tool to provide automatic indentation and newlines * without requiring extra work from the user. Note that this class * will likely not yield appropriate results for document-oriented * XML like XHTML pages, which mix character data and elements together.

* *

This writer will automatically place each start tag on a new line, * optionally indented if an indent step is provided (by default, there * is no indentation). If an element contains other elements, the end * tag will also appear on a new line with leading indentation. Consider, * for example, the following code:

* *
 * DataWriter w = new DataWriter();
 *
 * w.setIndentStep(2);
 * w.startDocument();
 * w.startElement("Person");
 * w.dataElement("name", "Jane Smith");
 * w.dataElement("date-of-birth", "1965-05-23");
 * w.dataElement("citizenship", "US");
 * w.endElement("Person");
 * w.endDocument();
 * 
* *

This code will produce the following document:

* *
 * <?xml version="1.0" standalone="yes"?>
 *
 * <Person>
 *   <name>Jane Smith</name>
 *   <date-of-birth>1965-05-23</date-of-birth>
 *   <citizenship>US</citizenship>
 * </Person>
 * 
* *

This class inherits from {@link XMLWriter}, * and provides all of the same support for Namespaces.

* * @since 1.0 * @author David Megginson, david@megginson.com * @version 0.2 * @see XMLWriter */ public class DataWriter extends XMLWriter { //////////////////////////////////////////////////////////////////// // Constructors. //////////////////////////////////////////////////////////////////// /** * Create a new data writer for the specified output. * * @param writer The character stream where the XML document * will be written. * @param encoding * If non-null string is specified, it is written as a part * of the XML declaration. */ public DataWriter ( Writer writer, String encoding, CharacterEscapeHandler _escapeHandler ) { super(writer,encoding,_escapeHandler); } public DataWriter (Writer writer, String encoding ) { this( writer, encoding, DumbEscapeHandler.theInstance ); } public DataWriter (Writer writer) { this( writer, null, DumbEscapeHandler.theInstance ); } //////////////////////////////////////////////////////////////////// // Accessors and setters. //////////////////////////////////////////////////////////////////// /** * Return the current indent step. * *

Return the current indent step: each start tag will be * indented by this number of spaces times the number of * ancestors that the element has.

* * @return The number of spaces in each indentation step, * or 0 or less for no indentation. * @see #setIndentStep(int) * * @deprecated * Only return the length of the indent string. */ public int getIndentStep () { return indentStep.length(); } /** * Set the current indent step. * * @param indentStep The new indent step (0 or less for no * indentation). * @see #getIndentStep() * * @deprecated * Should use the version that takes string. */ public void setIndentStep (int indentStep) { StringBuilder s = new StringBuilder(); for( ; indentStep>0; indentStep-- ) s.append(' '); setIndentStep(s.toString()); } public void setIndentStep(String s) { this.indentStep = s; } //////////////////////////////////////////////////////////////////// // Override methods from XMLWriter. //////////////////////////////////////////////////////////////////// /** * Reset the writer so that it can be reused. * *

This method is especially useful if the writer failed * with an exception the last time through.

* * @see XMLWriter#reset() */ public void reset () { depth = 0; state = SEEN_NOTHING; stateStack = new Stack(); super.reset(); } /** * Write a start tag. * *

Each tag will begin on a new line, and will be * indented by the current indent step times the number * of ancestors that the element has.

* *

The newline and indentation will be passed on down * the filter chain through regular characters events.

* * @param uri The element's Namespace URI. * @param localName The element's local name. * @param qName The element's qualified (prefixed) name. * @param atts The element's attribute list. * @exception org.xml.sax.SAXException If there is an error * writing the start tag, or if a filter further * down the chain raises an exception. * @see XMLWriter#startElement(String, String, String, Attributes) */ public void startElement (String uri, String localName, String qName, Attributes atts) throws SAXException { stateStack.push(SEEN_ELEMENT); state = SEEN_NOTHING; if (depth > 0) { super.characters("\n"); } doIndent(); super.startElement(uri, localName, qName, atts); depth++; } /** * Write an end tag. * *

If the element has contained other elements, the tag * will appear indented on a new line; otherwise, it will * appear immediately following whatever came before.

* *

The newline and indentation will be passed on down * the filter chain through regular characters events.

* * @param uri The element's Namespace URI. * @param localName The element's local name. * @param qName The element's qualified (prefixed) name. * @exception org.xml.sax.SAXException If there is an error * writing the end tag, or if a filter further * down the chain raises an exception. * @see XMLWriter#endElement(String, String, String) */ public void endElement (String uri, String localName, String qName) throws SAXException { depth--; if (state == SEEN_ELEMENT) { super.characters("\n"); doIndent(); } super.endElement(uri, localName, qName); state = stateStack.pop(); } // /** // * Write a empty element tag. // * // *

Each tag will appear on a new line, and will be // * indented by the current indent step times the number // * of ancestors that the element has.

// * // *

The newline and indentation will be passed on down // * the filter chain through regular characters events.

// * // * @param uri The element's Namespace URI. // * @param localName The element's local name. // * @param qName The element's qualified (prefixed) name. // * @param atts The element's attribute list. // * @exception org.xml.sax.SAXException If there is an error // * writing the empty tag, or if a filter further // * down the chain raises an exception. // * @see XMLWriter#emptyElement(String, String, String, Attributes) // */ // public void emptyElement (String uri, String localName, // String qName, Attributes atts) // throws SAXException // { // state = SEEN_ELEMENT; // if (depth > 0) { // super.characters("\n"); // } // doIndent(); // super.emptyElement(uri, localName, qName, atts); // } /** * Write a sequence of characters. * * @param ch The characters to write. * @param start The starting position in the array. * @param length The number of characters to use. * @exception org.xml.sax.SAXException If there is an error * writing the characters, or if a filter further * down the chain raises an exception. * @see XMLWriter#characters(char[], int, int) */ public void characters (char ch[], int start, int length) throws SAXException { state = SEEN_DATA; super.characters(ch, start, length); } public void comment(char ch[], int start, int length) throws SAXException { if (depth > 0) { super.characters("\n"); } doIndent(); super.comment(ch,start,length); } //////////////////////////////////////////////////////////////////// // Internal methods. //////////////////////////////////////////////////////////////////// /** * Print indentation for the current level. * * @exception org.xml.sax.SAXException If there is an error * writing the indentation characters, or if a filter * further down the chain raises an exception. */ private void doIndent () throws SAXException { if (depth > 0) { char[] ch = indentStep.toCharArray(); for( int i=0; i': out.write(">"); break; case '\"': if (isAttVal) { out.write("""); } else { out.write('\"'); } break; default: if (ch[i] > '\u007f') { out.write("&#"); out.write(Integer.toString(ch[i])); out.write(';'); } else { out.write(ch[i]); } } } } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/output/DumpSerializer.java000066400000000000000000000044231157142111200256570ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2.output; import java.io.PrintStream; /** * Shows the call sequence of {@link XmlSerializer} methods. * * Useful for debugging and learning how TXW works. * * @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public class DumpSerializer implements XmlSerializer { private final PrintStream out; public DumpSerializer(PrintStream out) { this.out = out; } public void beginStartTag(String uri, String localName, String prefix) { out.println('<'+prefix+':'+localName); } public void writeAttribute(String uri, String localName, String prefix, StringBuilder value) { out.println('@'+prefix+':'+localName+'='+value); } public void writeXmlns(String prefix, String uri) { out.println("xmlns:"+prefix+'='+uri); } public void endStartTag(String uri, String localName, String prefix) { out.println('>'); } public void endTag() { out.println(""); } public void text(StringBuilder text) { out.println(text); } public void cdata(StringBuilder text) { out.println(""); } public void comment(StringBuilder comment) { out.println(""); } public void startDocument() { out.println(""); } public void endDocument() { out.println("done"); } public void flush() { out.println("flush"); } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/output/IndentingXMLFilter.java000066400000000000000000000213011157142111200263600ustar00rootroot00000000000000package com.sun.xml.txw2.output; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.XMLFilterImpl; import java.util.Stack; /** * {@link XMLFilterImpl} that does indentation to SAX events. * * @author Kohsuke Kawaguchi */ public class IndentingXMLFilter extends XMLFilterImpl implements LexicalHandler { private LexicalHandler lexical; public IndentingXMLFilter() { } public IndentingXMLFilter(ContentHandler handler) { setContentHandler(handler); } public IndentingXMLFilter(ContentHandler handler, LexicalHandler lexical) { setContentHandler(handler); setLexicalHandler(lexical); } public LexicalHandler getLexicalHandler() { return lexical; } public void setLexicalHandler(LexicalHandler lexical) { this.lexical = lexical; } /** * Return the current indent step. * *

Return the current indent step: each start tag will be * indented by this number of spaces times the number of * ancestors that the element has.

* * @return The number of spaces in each indentation step, * or 0 or less for no indentation. * @see #setIndentStep(int) * * @deprecated * Only return the length of the indent string. */ public int getIndentStep () { return indentStep.length(); } /** * Set the current indent step. * * @param indentStep The new indent step (0 or less for no * indentation). * @see #getIndentStep() * * @deprecated * Should use the version that takes string. */ public void setIndentStep (int indentStep) { StringBuilder s = new StringBuilder(); for( ; indentStep>0; indentStep-- ) s.append(' '); setIndentStep(s.toString()); } public void setIndentStep(String s) { this.indentStep = s; } //////////////////////////////////////////////////////////////////// // Override methods from XMLWriter. //////////////////////////////////////////////////////////////////// /** * Write a start tag. * *

Each tag will begin on a new line, and will be * indented by the current indent step times the number * of ancestors that the element has.

* *

The newline and indentation will be passed on down * the filter chain through regular characters events.

* * @param uri The element's Namespace URI. * @param localName The element's local name. * @param qName The element's qualified (prefixed) name. * @param atts The element's attribute list. * @exception org.xml.sax.SAXException If there is an error * writing the start tag, or if a filter further * down the chain raises an exception. * @see XMLWriter#startElement(String, String, String,Attributes) */ public void startElement (String uri, String localName, String qName, Attributes atts) throws SAXException { stateStack.push(SEEN_ELEMENT); state = SEEN_NOTHING; if (depth > 0) { writeNewLine(); } doIndent(); super.startElement(uri, localName, qName, atts); depth++; } private void writeNewLine() throws SAXException { super.characters(NEWLINE,0,NEWLINE.length); } private static final char[] NEWLINE = {'\n'}; /** * Write an end tag. * *

If the element has contained other elements, the tag * will appear indented on a new line; otherwise, it will * appear immediately following whatever came before.

* *

The newline and indentation will be passed on down * the filter chain through regular characters events.

* * @param uri The element's Namespace URI. * @param localName The element's local name. * @param qName The element's qualified (prefixed) name. * @exception org.xml.sax.SAXException If there is an error * writing the end tag, or if a filter further * down the chain raises an exception. * @see XMLWriter#endElement(String, String, String) */ public void endElement (String uri, String localName, String qName) throws SAXException { depth--; if (state == SEEN_ELEMENT) { writeNewLine(); doIndent(); } super.endElement(uri, localName, qName); state = stateStack.pop(); } // /** // * Write a empty element tag. // * // *

Each tag will appear on a new line, and will be // * indented by the current indent step times the number // * of ancestors that the element has.

// * // *

The newline and indentation will be passed on down // * the filter chain through regular characters events.

// * // * @param uri The element's Namespace URI. // * @param localName The element's local name. // * @param qName The element's qualified (prefixed) name. // * @param atts The element's attribute list. // * @exception org.xml.sax.SAXException If there is an error // * writing the empty tag, or if a filter further // * down the chain raises an exception. // * @see XMLWriter#emptyElement(String, String, String, Attributes) // */ // public void emptyElement (String uri, String localName, // String qName, Attributes atts) // throws SAXException // { // state = SEEN_ELEMENT; // if (depth > 0) { // super.characters("\n"); // } // doIndent(); // super.emptyElement(uri, localName, qName, atts); // } /** * Write a sequence of characters. * * @param ch The characters to write. * @param start The starting position in the array. * @param length The number of characters to use. * @exception org.xml.sax.SAXException If there is an error * writing the characters, or if a filter further * down the chain raises an exception. * @see XMLWriter#characters(char[], int, int) */ public void characters (char ch[], int start, int length) throws SAXException { state = SEEN_DATA; super.characters(ch, start, length); } public void comment(char ch[], int start, int length) throws SAXException { if (depth > 0) { writeNewLine(); } doIndent(); if(lexical!=null) lexical.comment(ch,start,length); } public void startDTD(String name, String publicId, String systemId) throws SAXException { if(lexical!=null) lexical.startDTD(name, publicId, systemId); } public void endDTD() throws SAXException { if(lexical!=null) lexical.endDTD(); } public void startEntity(String name) throws SAXException { if(lexical!=null) lexical.startEntity(name); } public void endEntity(String name) throws SAXException { if(lexical!=null) lexical.endEntity(name); } public void startCDATA() throws SAXException { if(lexical!=null) lexical.startCDATA(); } public void endCDATA() throws SAXException { if(lexical!=null) lexical.endCDATA(); } //////////////////////////////////////////////////////////////////// // Internal methods. //////////////////////////////////////////////////////////////////// /** * Print indentation for the current level. * * @exception org.xml.sax.SAXException If there is an error * writing the indentation characters, or if a filter * further down the chain raises an exception. */ private void doIndent () throws SAXException { if (depth > 0) { char[] ch = indentStep.toCharArray(); for( int i=0; i stateStack = new Stack(); private String indentStep = ""; private int depth = 0; } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/output/IndentingXMLStreamWriter.java000066400000000000000000000120011157142111200275600ustar00rootroot00000000000000package com.sun.xml.txw2.output; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import java.util.Stack; /** * @author Kohsuke Kawaguchi */ public class IndentingXMLStreamWriter extends DelegatingXMLStreamWriter { private final static Object SEEN_NOTHING = new Object(); private final static Object SEEN_ELEMENT = new Object(); private final static Object SEEN_DATA = new Object(); private Object state = SEEN_NOTHING; private Stack stateStack = new Stack(); private String indentStep = " "; private int depth = 0; public IndentingXMLStreamWriter(XMLStreamWriter writer) { super(writer); } /** * Return the current indent step. * *

Return the current indent step: each start tag will be * indented by this number of spaces times the number of * ancestors that the element has.

* * @return The number of spaces in each indentation step, * or 0 or less for no indentation. * @see #setIndentStep(int) * * @deprecated * Only return the length of the indent string. */ public int getIndentStep() { return indentStep.length(); } /** * Set the current indent step. * * @param indentStep The new indent step (0 or less for no * indentation). * @see #getIndentStep() * * @deprecated * Should use the version that takes string. */ public void setIndentStep(int indentStep) { StringBuilder s = new StringBuilder(); for (; indentStep > 0; indentStep--) s.append(' '); setIndentStep(s.toString()); } public void setIndentStep(String s) { this.indentStep = s; } private void onStartElement() throws XMLStreamException { stateStack.push(SEEN_ELEMENT); state = SEEN_NOTHING; if (depth > 0) { super.writeCharacters("\n"); } doIndent(); depth++; } private void onEndElement() throws XMLStreamException { depth--; if (state == SEEN_ELEMENT) { super.writeCharacters("\n"); doIndent(); } state = stateStack.pop(); } private void onEmptyElement() throws XMLStreamException { state = SEEN_ELEMENT; if (depth > 0) { super.writeCharacters("\n"); } doIndent(); } /** * Print indentation for the current level. * * @exception org.xml.sax.SAXException If there is an error * writing the indentation characters, or if a filter * further down the chain raises an exception. */ private void doIndent() throws XMLStreamException { if (depth > 0) { for (int i = 0; i < depth; i++) super.writeCharacters(indentStep); } } public void writeStartDocument() throws XMLStreamException { super.writeStartDocument(); super.writeCharacters("\n"); } public void writeStartDocument(String version) throws XMLStreamException { super.writeStartDocument(version); super.writeCharacters("\n"); } public void writeStartDocument(String encoding, String version) throws XMLStreamException { super.writeStartDocument(encoding, version); super.writeCharacters("\n"); } public void writeStartElement(String localName) throws XMLStreamException { onStartElement(); super.writeStartElement(localName); } public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { onStartElement(); super.writeStartElement(namespaceURI, localName); } public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { onStartElement(); super.writeStartElement(prefix, localName, namespaceURI); } public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { onEmptyElement(); super.writeEmptyElement(namespaceURI, localName); } public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { onEmptyElement(); super.writeEmptyElement(prefix, localName, namespaceURI); } public void writeEmptyElement(String localName) throws XMLStreamException { onEmptyElement(); super.writeEmptyElement(localName); } public void writeEndElement() throws XMLStreamException { onEndElement(); super.writeEndElement(); } public void writeCharacters(String text) throws XMLStreamException { state = SEEN_DATA; super.writeCharacters(text); } public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { state = SEEN_DATA; super.writeCharacters(text, start, len); } public void writeCData(String data) throws XMLStreamException { state = SEEN_DATA; super.writeCData(data); } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/output/ResultFactory.java000066400000000000000000000041701157142111200255250ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2.output; import javax.xml.transform.Result; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.stream.StreamResult; /** * Factory for producing XmlSerializers for various Result types. * * @author Ryan.Shoemaker@Sun.COM */ public abstract class ResultFactory { /** * Do not instanciate. */ private ResultFactory() {} /** * Factory method for producing {@link XmlSerializer) from {@link javax.xml.transform.Result}. * * This method supports {@link javax.xml.transform.sax.SAXResult}, * {@link javax.xml.transform.stream.StreamResult}, and {@link javax.xml.transform.dom.DOMResult}. * * @param result the Result that will receive output from the XmlSerializer * @return an implementation of XmlSerializer that will produce output on the supplied Result */ public static XmlSerializer createSerializer(Result result) { if (result instanceof SAXResult) return new SaxSerializer((SAXResult) result); if (result instanceof DOMResult) return new DomSerializer((DOMResult) result); if (result instanceof StreamResult) return new StreamSerializer((StreamResult) result); throw new UnsupportedOperationException("Unsupported Result type: " + result.getClass().getName()); } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/output/SaxSerializer.java000066400000000000000000000137121157142111200255060ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2.output; import com.sun.xml.txw2.TxwException; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.AttributesImpl; import javax.xml.transform.sax.SAXResult; import java.util.Stack; /** * {@link XmlSerializer} for {@link SAXResult} and {@link ContentHandler}. * * @author Ryan.Shoemaker@Sun.COM */ public class SaxSerializer implements XmlSerializer { private final ContentHandler writer; private final LexicalHandler lexical; public SaxSerializer(ContentHandler handler) { this(handler,null,true); } /** * Creates an {@link XmlSerializer} that writes SAX events. * *

* Sepcifying a non-null {@link LexicalHandler} allows applications * to write comments and CDATA sections. */ public SaxSerializer(ContentHandler handler,LexicalHandler lex) { this(handler, lex, true); } public SaxSerializer(ContentHandler handler,LexicalHandler lex, boolean indenting) { if(!indenting) { writer = handler; lexical = lex; } else { IndentingXMLFilter indenter = new IndentingXMLFilter(handler, lex); writer = indenter; lexical = indenter; } } public SaxSerializer(SAXResult result) { this(result.getHandler(),result.getLexicalHandler()); } // XmlSerializer implementation public void startDocument() { try { writer.startDocument(); } catch (SAXException e) { throw new TxwException(e); } } // namespace prefix bindings // add in #writeXmlns and fired in #endStartTag private final Stack prefixBindings = new Stack(); public void writeXmlns(String prefix, String uri) { // defend against parsers that pass null in for "xmlns" prefix if (prefix == null) { prefix = ""; } if (prefix.equals("xml")) { return; } prefixBindings.add(uri); prefixBindings.add(prefix); } // element stack private final Stack elementBindings = new Stack(); public void beginStartTag(String uri, String localName, String prefix) { // save element bindings for #endTag elementBindings.add(getQName(prefix, localName)); elementBindings.add(localName); elementBindings.add(uri); } // attribute storage // attrs are buffered in #writeAttribute and sent to the content // handler in #endStartTag private final AttributesImpl attrs = new AttributesImpl(); public void writeAttribute(String uri, String localName, String prefix, StringBuilder value) { attrs.addAttribute(uri, localName, getQName(prefix, localName), "CDATA", value.toString()); } public void endStartTag(String uri, String localName, String prefix) { try { while (prefixBindings.size() != 0) { writer.startPrefixMapping(prefixBindings.pop(), // prefix prefixBindings.pop() // uri ); } writer.startElement(uri, localName, getQName(prefix, localName), attrs); attrs.clear(); } catch (SAXException e) { throw new TxwException(e); } } public void endTag() { try { writer.endElement(elementBindings.pop(), // uri elementBindings.pop(), // localName elementBindings.pop() // qname ); } catch (SAXException e) { throw new TxwException(e); } } public void text(StringBuilder text) { try { writer.characters(text.toString().toCharArray(), 0, text.length()); } catch (SAXException e) { throw new TxwException(e); } } public void cdata(StringBuilder text) { if(lexical==null) throw new UnsupportedOperationException("LexicalHandler is needed to write PCDATA"); try { lexical.startCDATA(); text(text); lexical.endCDATA(); } catch (SAXException e) { throw new TxwException(e); } } public void comment(StringBuilder comment) { try { if(lexical==null) throw new UnsupportedOperationException("LexicalHandler is needed to write comments"); else lexical.comment(comment.toString().toCharArray(), 0, comment.length() ); } catch (SAXException e) { throw new TxwException(e); } } public void endDocument() { try { writer.endDocument(); } catch (SAXException e) { throw new TxwException(e); } } public void flush() { // noop } // other methods private static String getQName(String prefix, String localName) { final String qName; if (prefix == null || prefix.length() == 0) qName = localName; else qName = prefix + ':' + localName; return qName; } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/output/StaxSerializer.java000066400000000000000000000074341157142111200256760ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2.output; import com.sun.xml.txw2.TxwException; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; /** * XML serializer for StAX XMLStreamWriter. * * TODO: add support for XMLEventWriter (if it makes sense) * * @author Ryan.Shoemaker@Sun.COM */ public class StaxSerializer implements XmlSerializer { private final XMLStreamWriter out; public StaxSerializer(XMLStreamWriter writer) { this(writer,true); } public StaxSerializer(XMLStreamWriter writer, boolean indenting) { if(indenting) writer = new IndentingXMLStreamWriter(writer); this.out = writer; } public void startDocument() { try { out.writeStartDocument(); } catch (XMLStreamException e) { throw new TxwException(e); } } public void beginStartTag(String uri, String localName, String prefix) { try { out.writeStartElement(prefix, localName, uri); } catch (XMLStreamException e) { throw new TxwException(e); } } public void writeAttribute(String uri, String localName, String prefix, StringBuilder value) { try { out.writeAttribute(prefix, uri, localName, value.toString()); } catch (XMLStreamException e) { throw new TxwException(e); } } public void writeXmlns(String prefix, String uri) { try { if (prefix.length() == 0) { out.setDefaultNamespace(uri); } else { out.setPrefix(prefix, uri); } // this method handles "", null, and "xmlns" prefixes properly out.writeNamespace(prefix, uri); } catch (XMLStreamException e) { throw new TxwException(e); } } public void endStartTag(String uri, String localName, String prefix) { // NO-OP } public void endTag() { try { out.writeEndElement(); } catch (XMLStreamException e) { throw new TxwException(e); } } public void text(StringBuilder text) { try { out.writeCharacters(text.toString()); } catch (XMLStreamException e) { throw new TxwException(e); } } public void cdata(StringBuilder text) { try { out.writeCData(text.toString()); } catch (XMLStreamException e) { throw new TxwException(e); } } public void comment(StringBuilder comment) { try { out.writeComment(comment.toString()); } catch (XMLStreamException e) { throw new TxwException(e); } } public void endDocument() { try { out.writeEndDocument(); out.flush(); } catch (XMLStreamException e) { throw new TxwException(e); } } public void flush() { try { out.flush(); } catch (XMLStreamException e) { throw new TxwException(e); } } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/output/StreamSerializer.java000066400000000000000000000132641157142111200262100ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2.output; import com.sun.xml.txw2.TxwException; import javax.xml.transform.stream.StreamResult; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.io.UnsupportedEncodingException; /** * {@link XmlSerializer} for {@link javax.xml.transform.stream.StreamResult}. * * @author Ryan.Shoemaker@Sun.COM */ public class StreamSerializer implements XmlSerializer { // delegate to SaxSerializer private final SaxSerializer serializer; private final XMLWriter writer; public StreamSerializer(OutputStream out) { this(createWriter(out)); } public StreamSerializer(OutputStream out,String encoding) throws UnsupportedEncodingException { this(createWriter(out,encoding)); } public StreamSerializer(Writer out) { this(new StreamResult(out)); } public StreamSerializer(StreamResult streamResult) { // if this method opened a stream, let it close it final OutputStream[] autoClose = new OutputStream[1]; if (streamResult.getWriter() != null) writer = createWriter(streamResult.getWriter()); else if (streamResult.getOutputStream() != null) writer = createWriter(streamResult.getOutputStream()); else if (streamResult.getSystemId() != null) { String fileURL = streamResult.getSystemId(); fileURL = convertURL(fileURL); try { FileOutputStream fos = new FileOutputStream(fileURL); autoClose[0] = fos; writer = createWriter(fos); } catch (IOException e) { throw new TxwException(e); } } else throw new IllegalArgumentException(); // now delegate to the SaxSerializer serializer = new SaxSerializer(writer,writer,false) { public void endDocument() { super.endDocument(); if(autoClose[0]!=null) { try { autoClose[0].close(); } catch (IOException e) { throw new TxwException(e); } autoClose[0] = null; } } }; } private StreamSerializer(XMLWriter writer) { this.writer = writer; // now delegate to the SaxSerializer serializer = new SaxSerializer(writer,writer,false); } private String convertURL(String url) { url = url.replace('\\', '/'); url = url.replaceAll("//","/"); url = url.replaceAll("//","/"); if (url.startsWith("file:/")) { if (url.substring(6).indexOf(":") > 0) url = url.substring(6); else url = url.substring(5); } // otherwise assume that it's a file name return url; } // XmlSerializer api's - delegate to SaxSerializer public void startDocument() { serializer.startDocument(); } public void beginStartTag(String uri, String localName, String prefix) { serializer.beginStartTag(uri, localName, prefix); } public void writeAttribute(String uri, String localName, String prefix, StringBuilder value) { serializer.writeAttribute(uri, localName, prefix, value); } public void writeXmlns(String prefix, String uri) { serializer.writeXmlns(prefix, uri); } public void endStartTag(String uri, String localName, String prefix) { serializer.endStartTag(uri, localName, prefix); } public void endTag() { serializer.endTag(); } public void text(StringBuilder text) { serializer.text(text); } public void cdata(StringBuilder text) { serializer.cdata(text); } public void comment(StringBuilder comment) { serializer.comment(comment); } public void endDocument() { serializer.endDocument(); } public void flush() { serializer.flush(); try { writer.flush(); } catch (IOException e) { throw new TxwException(e); } } // other supporting code private static XMLWriter createWriter(Writer w) { // buffering improves the performance DataWriter dw = new DataWriter(new BufferedWriter(w)); dw.setIndentStep(" "); return dw; } private static XMLWriter createWriter(OutputStream os, String encoding) throws UnsupportedEncodingException { XMLWriter writer = createWriter(new OutputStreamWriter(os,encoding)); writer.setEncoding(encoding); return writer; } private static XMLWriter createWriter(OutputStream os) { try { return createWriter(os,"UTF-8"); } catch (UnsupportedEncodingException e) { // UTF-8 is supported on all platforms. throw new Error(e); } } } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/output/XMLWriter.java000066400000000000000000001035451157142111200245620ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ // @@3RD PARTY CODE@@ // XMLWriter.java - serialize an XML document. // Written by David Megginson, david@megginson.com // NO WARRANTY! This class is in the public domain. // Id: XMLWriter.java,v 1.5 2000/09/17 01:08:16 david Exp package com.sun.xml.txw2.output; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.XMLFilterImpl; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Filter to write an XML document from a SAX event stream. * *

This class can be used by itself or as part of a SAX event * stream: it takes as input a series of SAX2 ContentHandler * events and uses the information in those events to write * an XML document. Since this class is a filter, it can also * pass the events on down a filter chain for further processing * (you can use the XMLWriter to take a snapshot of the current * state at any point in a filter chain), and it can be * used directly as a ContentHandler for a SAX2 XMLReader.

* *

The client creates a document by invoking the methods for * standard SAX2 events, always beginning with the * {@link #startDocument startDocument} method and ending with * the {@link #endDocument endDocument} method. There are convenience * methods provided so that clients to not have to create empty * attribute lists or provide empty strings as parameters; for * example, the method invocation

* *
 * w.startElement("foo");
 * 
* *

is equivalent to the regular SAX2 ContentHandler method

* *
 * w.startElement("", "foo", "", new AttributesImpl());
 * 
* *

Except that it is more efficient because it does not allocate * a new empty attribute list each time. The following code will send * a simple XML document to standard output:

* *
 * XMLWriter w = new XMLWriter();
 *
 * w.startDocument();
 * w.startElement("greeting");
 * w.characters("Hello, world!");
 * w.endElement("greeting");
 * w.endDocument();
 * 
* *

The resulting document will look like this:

* *
 * <?xml version="1.0" standalone="yes"?>
 *
 * <greeting>Hello, world!</greeting>
 * 
* *

In fact, there is an even simpler convenience method, * dataElement, designed for writing elements that * contain only character data, so the code to generate the * document could be shortened to

* *
 * XMLWriter w = new XMLWriter();
 *
 * w.startDocument();
 * w.dataElement("greeting", "Hello, world!");
 * w.endDocument();
 * 
* *

Whitespace

* *

According to the XML Recommendation, all whitespace * in an XML document is potentially significant to an application, * so this class never adds newlines or indentation. If you * insert three elements in a row, as in

* *
 * w.dataElement("item", "1");
 * w.dataElement("item", "2");
 * w.dataElement("item", "3");
 * 
* *

you will end up with

* *
 * <item>1</item><item>3</item><item>3</item>
 * 
* *

You need to invoke one of the characters methods * explicitly to add newlines or indentation. Alternatively, you * can use {@link DataWriter}, which * is derived from this class -- it is optimized for writing * purely data-oriented (or field-oriented) XML, and does automatic * linebreaks and indentation (but does not support mixed content * properly).

* * *

Namespace Support

* *

The writer contains extensive support for XML Namespaces, so that * a client application does not have to keep track of prefixes and * supply xmlns attributes. By default, the XML writer will * generate Namespace declarations in the form _NS1, _NS2, etc., wherever * they are needed, as in the following example:

* *
 * w.startDocument();
 * w.emptyElement("http://www.foo.com/ns/", "foo");
 * w.endDocument();
 * 
* *

The resulting document will look like this:

* *
 * <?xml version="1.0" standalone="yes"?>
 *
 * <_NS1:foo xmlns:_NS1="http://www.foo.com/ns/"/>
 * 
* *

In many cases, document authors will prefer to choose their * own prefixes rather than using the (ugly) default names. The * XML writer allows two methods for selecting prefixes:

* *
    *
  1. the qualified name
  2. *
  3. the {@link #setPrefix setPrefix} method.
  4. *
* *

Whenever the XML writer finds a new Namespace URI, it checks * to see if a qualified (prefixed) name is also available; if so * it attempts to use the name's prefix (as long as the prefix is * not already in use for another Namespace URI).

* *

Before writing a document, the client can also pre-map a prefix * to a Namespace URI with the setPrefix method:

* *
 * w.setPrefix("http://www.foo.com/ns/", "foo");
 * w.startDocument();
 * w.emptyElement("http://www.foo.com/ns/", "foo");
 * w.endDocument();
 * 
* *

The resulting document will look like this:

* *
 * <?xml version="1.0" standalone="yes"?>
 *
 * <foo:foo xmlns:foo="http://www.foo.com/ns/"/>
 * 
* *

The default Namespace simply uses an empty string as the prefix:

* *
 * w.setPrefix("http://www.foo.com/ns/", "");
 * w.startDocument();
 * w.emptyElement("http://www.foo.com/ns/", "foo");
 * w.endDocument();
 * 
* *

The resulting document will look like this:

* *
 * <?xml version="1.0" standalone="yes"?>
 *
 * <foo xmlns="http://www.foo.com/ns/"/>
 * 
* *

By default, the XML writer will not declare a Namespace until * it is actually used. Sometimes, this approach will create * a large number of Namespace declarations, as in the following * example:

* *
 * <xml version="1.0" standalone="yes"?>
 *
 * <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
 *  <rdf:Description about="http://www.foo.com/ids/books/12345">
 *   <dc:title xmlns:dc="http://www.purl.org/dc/">A Dark Night</dc:title>
 *   <dc:creator xmlns:dc="http://www.purl.org/dc/">Jane Smith</dc:title>
 *   <dc:date xmlns:dc="http://www.purl.org/dc/">2000-09-09</dc:title>
 *  </rdf:Description>
 * </rdf:RDF>
 * 
* *

The "rdf" prefix is declared only once, because the RDF Namespace * is used by the root element and can be inherited by all of its * descendants; the "dc" prefix, on the other hand, is declared three * times, because no higher element uses the Namespace. To solve this * problem, you can instruct the XML writer to predeclare Namespaces * on the root element even if they are not used there:

* *
 * w.forceNSDecl("http://www.purl.org/dc/");
 * 
* *

Now, the "dc" prefix will be declared on the root element even * though it's not needed there, and can be inherited by its * descendants:

* *
 * <xml version="1.0" standalone="yes"?>
 *
 * <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
 *             xmlns:dc="http://www.purl.org/dc/">
 *  <rdf:Description about="http://www.foo.com/ids/books/12345">
 *   <dc:title>A Dark Night</dc:title>
 *   <dc:creator>Jane Smith</dc:title>
 *   <dc:date>2000-09-09</dc:title>
 *  </rdf:Description>
 * </rdf:RDF>
 * 
* *

This approach is also useful for declaring Namespace prefixes * that be used by qualified names appearing in attribute values or * character data.

* * @author David Megginson, david@megginson.com * @version 0.2 * @since JAXB1.0 * @see org.xml.sax.XMLFilter * @see org.xml.sax.ContentHandler */ public class XMLWriter extends XMLFilterImpl implements LexicalHandler { //////////////////////////////////////////////////////////////////// // Constructors. //////////////////////////////////////////////////////////////////// /** * Create a new XML writer. * *

Write to the writer provided.

* * @param writer * The output destination, or null to use standard output. * @param encoding * If non-null string is specified, it is written as a part * of the XML declaration. */ public XMLWriter (Writer writer, String encoding, CharacterEscapeHandler _escapeHandler ) { init(writer,encoding); this.escapeHandler = _escapeHandler; } public XMLWriter (Writer writer, String encoding ) { this( writer, encoding, DumbEscapeHandler.theInstance ); } /** * Internal initialization method. * *

All of the public constructors invoke this method. * * @param writer The output destination, or null to use * standard output. */ private void init (Writer writer,String encoding) { setOutput(writer,encoding); } //////////////////////////////////////////////////////////////////// // Public methods. //////////////////////////////////////////////////////////////////// /** * Reset the writer. * *

This method is especially useful if the writer throws an * exception before it is finished, and you want to reuse the * writer for a new document. It is usually a good idea to * invoke {@link #flush flush} before resetting the writer, * to make sure that no output is lost.

* *

This method is invoked automatically by the * {@link #startDocument startDocument} method before writing * a new document.

* *

Note: this method will not * clear the prefix or URI information in the writer or * the selected output writer.

* * @see #flush() */ public void reset () { elementLevel = 0; startTagIsClosed = true; } /** * Flush the output. * *

This method flushes the output stream. It is especially useful * when you need to make certain that the entire document has * been written to output but do not want to _commit the output * stream.

* *

This method is invoked automatically by the * {@link #endDocument endDocument} method after writing a * document.

* * @see #reset() */ public void flush () throws IOException { output.flush(); } /** * Set a new output destination for the document. * * @param writer The output destination, or null to use * standard output. * @see #flush() */ public void setOutput (Writer writer,String _encoding) { if (writer == null) { output = new OutputStreamWriter(System.out); } else { output = writer; } encoding = _encoding; } public void setEncoding(String encoding) { this.encoding = encoding; } /** * Set whether the writer should print out the XML declaration * (<?xml version='1.0' ... ?>). *

* This option is set to true by default. */ public void setXmlDecl( boolean _writeXmlDecl ) { this.writeXmlDecl = _writeXmlDecl; } /** * Sets the header string. * * This string will be written right after the xml declaration * without any escaping. Useful for generating a boiler-plate * DOCTYPE decl, PIs, and comments. * * @param _header * passing null will work as if the empty string is passed. */ public void setHeader( String _header ) { this.header = _header; } private final HashMap locallyDeclaredPrefix = new HashMap(); public void startPrefixMapping( String prefix, String uri ) throws SAXException { locallyDeclaredPrefix.put(prefix,uri); } //////////////////////////////////////////////////////////////////// // Methods from org.xml.sax.ContentHandler. //////////////////////////////////////////////////////////////////// /** * Write the XML declaration at the beginning of the document. * * Pass the event on down the filter chain for further processing. * * @exception org.xml.sax.SAXException If there is an error * writing the XML declaration, or if a handler further down * the filter chain raises an exception. * @see org.xml.sax.ContentHandler#startDocument() */ public void startDocument () throws SAXException { try { reset(); if(writeXmlDecl) { String e=""; if(encoding!=null) e = " encoding=\""+encoding+"\""; write("\n"); } if(header!=null) write(header); super.startDocument(); } catch( IOException e ) { throw new SAXException(e); } } /** * Write a newline at the end of the document. * * Pass the event on down the filter chain for further processing. * * @exception org.xml.sax.SAXException If there is an error * writing the newline, or if a handler further down * the filter chain raises an exception. * @see org.xml.sax.ContentHandler#endDocument() */ public void endDocument () throws SAXException { try { if (!startTagIsClosed) { write("/>"); startTagIsClosed = true; } write('\n'); super.endDocument(); try { flush(); } catch (IOException e) { throw new SAXException(e); } } catch( IOException e ) { throw new SAXException(e); } } /** * Write a start tag. * * Pass the event on down the filter chain for further processing. * * @param uri The Namespace URI, or the empty string if none * is available. * @param localName The element's local (unprefixed) name (required). * @param qName The element's qualified (prefixed) name, or the * empty string is none is available. This method will * use the qName as a template for generating a prefix * if necessary, but it is not guaranteed to use the * same qName. * @param atts The element's attribute list (must not be null). * @exception org.xml.sax.SAXException If there is an error * writing the start tag, or if a handler further down * the filter chain raises an exception. * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ public void startElement (String uri, String localName, String qName, Attributes atts) throws SAXException { try { if (!startTagIsClosed) { write(">"); } elementLevel++; // nsSupport.pushContext(); write('<'); writeName(uri, localName, qName, true); writeAttributes(atts); // declare namespaces specified by the startPrefixMapping methods if(!locallyDeclaredPrefix.isEmpty()) { Iterator itr = locallyDeclaredPrefix.entrySet().iterator(); while(itr.hasNext()) { Map.Entry e = (Map.Entry)itr.next(); String p = (String)e.getKey(); String u = (String)e.getValue(); if (u == null) { u = ""; } write(' '); if ("".equals(p)) { write("xmlns=\""); } else { write("xmlns:"); write(p); write("=\""); } char ch[] = u.toCharArray(); writeEsc(ch, 0, ch.length, true); write('\"'); } locallyDeclaredPrefix.clear(); // clear the contents } // if (elementLevel == 1) { // forceNSDecls(); // } // writeNSDecls(); super.startElement(uri, localName, qName, atts); startTagIsClosed = false; } catch( IOException e ) { throw new SAXException(e); } } /** * Write an end tag. * * Pass the event on down the filter chain for further processing. * * @param uri The Namespace URI, or the empty string if none * is available. * @param localName The element's local (unprefixed) name (required). * @param qName The element's qualified (prefixed) name, or the * empty string is none is available. This method will * use the qName as a template for generating a prefix * if necessary, but it is not guaranteed to use the * same qName. * @exception org.xml.sax.SAXException If there is an error * writing the end tag, or if a handler further down * the filter chain raises an exception. * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ public void endElement (String uri, String localName, String qName) throws SAXException { try { if (startTagIsClosed) { write("'); } else { write("/>"); startTagIsClosed = true; } if (elementLevel == 1) { write('\n'); } super.endElement(uri, localName, qName); // nsSupport.popContext(); elementLevel--; } catch( IOException e ) { throw new SAXException(e); } } /** * Write character data. * * Pass the event on down the filter chain for further processing. * * @param ch The array of characters to write. * @param start The starting position in the array. * @param len The number of characters to write. * @exception org.xml.sax.SAXException If there is an error * writing the characters, or if a handler further down * the filter chain raises an exception. * @see org.xml.sax.ContentHandler#characters(char[], int, int) */ public void characters (char ch[], int start, int len) throws SAXException { try { if (!startTagIsClosed) { write('>'); startTagIsClosed = true; } if(inCDATA) output.write(ch,start,len); else writeEsc(ch, start, len, false); super.characters(ch, start, len); } catch( IOException e ) { throw new SAXException(e); } } /** * Write ignorable whitespace. * * Pass the event on down the filter chain for further processing. * * @param ch The array of characters to write. * @param start The starting position in the array. * @param length The number of characters to write. * @exception org.xml.sax.SAXException If there is an error * writing the whitespace, or if a handler further down * the filter chain raises an exception. * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int) */ public void ignorableWhitespace (char ch[], int start, int length) throws SAXException { try { writeEsc(ch, start, length, false); super.ignorableWhitespace(ch, start, length); } catch( IOException e ) { throw new SAXException(e); } } /** * Write a processing instruction. * * Pass the event on down the filter chain for further processing. * * @param target The PI target. * @param data The PI data. * @exception org.xml.sax.SAXException If there is an error * writing the PI, or if a handler further down * the filter chain raises an exception. * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String) */ public void processingInstruction (String target, String data) throws SAXException { try { if (!startTagIsClosed) { write('>'); startTagIsClosed = true; } write(""); if (elementLevel < 1) { write('\n'); } super.processingInstruction(target, data); } catch( IOException e ) { throw new SAXException(e); } } //////////////////////////////////////////////////////////////////// // Convenience methods. //////////////////////////////////////////////////////////////////// /** * Start a new element without a qname or attributes. * *

This method will provide a default empty attribute * list and an empty string for the qualified name. * It invokes {@link * #startElement(String, String, String, Attributes)} * directly.

* * @param uri The element's Namespace URI. * @param localName The element's local name. * @exception org.xml.sax.SAXException If there is an error * writing the start tag, or if a handler further down * the filter chain raises an exception. * @see #startElement(String, String, String, Attributes) */ public void startElement (String uri, String localName) throws SAXException { startElement(uri, localName, "", EMPTY_ATTS); } /** * Start a new element without a qname, attributes or a Namespace URI. * *

This method will provide an empty string for the * Namespace URI, and empty string for the qualified name, * and a default empty attribute list. It invokes * #startElement(String, String, String, Attributes)} * directly.

* * @param localName The element's local name. * @exception org.xml.sax.SAXException If there is an error * writing the start tag, or if a handler further down * the filter chain raises an exception. * @see #startElement(String, String, String, Attributes) */ public void startElement (String localName) throws SAXException { startElement("", localName, "", EMPTY_ATTS); } /** * End an element without a qname. * *

This method will supply an empty string for the qName. * It invokes {@link #endElement(String, String, String)} * directly.

* * @param uri The element's Namespace URI. * @param localName The element's local name. * @exception org.xml.sax.SAXException If there is an error * writing the end tag, or if a handler further down * the filter chain raises an exception. * @see #endElement(String, String, String) */ public void endElement (String uri, String localName) throws SAXException { endElement(uri, localName, ""); } /** * End an element without a Namespace URI or qname. * *

This method will supply an empty string for the qName * and an empty string for the Namespace URI. * It invokes {@link #endElement(String, String, String)} * directly.

* * @param localName The element's local name. * @exception org.xml.sax.SAXException If there is an error * writing the end tag, or if a handler further down * the filter chain raises an exception. * @see #endElement(String, String, String) */ public void endElement (String localName) throws SAXException { endElement("", localName, ""); } /** * Write an element with character data content. * *

This is a convenience method to write a complete element * with character data content, including the start tag * and end tag.

* *

This method invokes * {@link #startElement(String, String, String, Attributes)}, * followed by * {@link #characters(String)}, followed by * {@link #endElement(String, String, String)}.

* * @param uri The element's Namespace URI. * @param localName The element's local name. * @param qName The element's default qualified name. * @param atts The element's attributes. * @param content The character data content. * @exception org.xml.sax.SAXException If there is an error * writing the empty tag, or if a handler further down * the filter chain raises an exception. * @see #startElement(String, String, String, Attributes) * @see #characters(String) * @see #endElement(String, String, String) */ public void dataElement (String uri, String localName, String qName, Attributes atts, String content) throws SAXException { startElement(uri, localName, qName, atts); characters(content); endElement(uri, localName, qName); } /** * Write an element with character data content but no attributes. * *

This is a convenience method to write a complete element * with character data content, including the start tag * and end tag. This method provides an empty string * for the qname and an empty attribute list.

* *

This method invokes * {@link #startElement(String, String, String, Attributes)}, * followed by * {@link #characters(String)}, followed by * {@link #endElement(String, String, String)}.

* * @param uri The element's Namespace URI. * @param localName The element's local name. * @param content The character data content. * @exception org.xml.sax.SAXException If there is an error * writing the empty tag, or if a handler further down * the filter chain raises an exception. * @see #startElement(String, String, String, Attributes) * @see #characters(String) * @see #endElement(String, String, String) */ public void dataElement (String uri, String localName, String content) throws SAXException { dataElement(uri, localName, "", EMPTY_ATTS, content); } /** * Write an element with character data content but no attributes or Namespace URI. * *

This is a convenience method to write a complete element * with character data content, including the start tag * and end tag. The method provides an empty string for the * Namespace URI, and empty string for the qualified name, * and an empty attribute list.

* *

This method invokes * {@link #startElement(String, String, String, Attributes)}, * followed by * {@link #characters(String)}, followed by * {@link #endElement(String, String, String)}.

* * @param localName The element's local name. * @param content The character data content. * @exception org.xml.sax.SAXException If there is an error * writing the empty tag, or if a handler further down * the filter chain raises an exception. * @see #startElement(String, String, String, Attributes) * @see #characters(String) * @see #endElement(String, String, String) */ public void dataElement (String localName, String content) throws SAXException { dataElement("", localName, "", EMPTY_ATTS, content); } /** * Write a string of character data, with XML escaping. * *

This is a convenience method that takes an XML * String, converts it to a character array, then invokes * {@link #characters(char[], int, int)}.

* * @param data The character data. * @exception org.xml.sax.SAXException If there is an error * writing the string, or if a handler further down * the filter chain raises an exception. * @see #characters(char[], int, int) */ public void characters (String data) throws SAXException { try { if (!startTagIsClosed) { write('>'); startTagIsClosed = true; } char ch[] = data.toCharArray(); characters(ch, 0, ch.length); } catch( IOException e ) { throw new SAXException(e); } } public void startDTD(String name, String publicId, String systemId) throws SAXException { } public void endDTD() throws SAXException { } public void startEntity(String name) throws SAXException { } public void endEntity(String name) throws SAXException { } public void startCDATA() throws SAXException { try { if (!startTagIsClosed) { write('>'); startTagIsClosed = true; } write(""); } catch (IOException e) { throw new SAXException(e); } } public void comment(char ch[], int start, int length) throws SAXException { try { output.write(""); } catch (IOException e) { throw new SAXException(e); } } //////////////////////////////////////////////////////////////////// // Internal methods. //////////////////////////////////////////////////////////////////// /** * Write a raw character. * * @param c The character to write. */ private void write (char c) throws IOException { output.write(c); } /** * Write a raw string. */ private void write (String s) throws IOException { output.write(s); } /** * Write out an attribute list, escaping values. * * The names will have prefixes added to them. * * @param atts The attribute list to write. * @exception SAXException If there is an error writing * the attribute list, this method will throw an * IOException wrapped in a SAXException. */ private void writeAttributes (Attributes atts) throws IOException, SAXException { int len = atts.getLength(); for (int i = 0; i < len; i++) { char ch[] = atts.getValue(i).toCharArray(); write(' '); writeName(atts.getURI(i), atts.getLocalName(i), atts.getQName(i), false); write("=\""); writeEsc(ch, 0, ch.length, true); write('"'); } } /** * Write an array of data characters with escaping. * * @param ch The array of characters. * @param start The starting position. * @param length The number of characters to use. * @param isAttVal true if this is an attribute value literal. * @exception SAXException If there is an error writing * the characters, this method will throw an * IOException wrapped in a SAXException. */ private void writeEsc (char ch[], int start, int length, boolean isAttVal) throws SAXException, IOException { escapeHandler.escape(ch, start, length, isAttVal, output); } /** * Write an element or attribute name. * * @param uri The Namespace URI. * @param localName The local name. * @param qName The prefixed name, if available, or the empty string. * @param isElement true if this is an element name, false if it * is an attribute name. */ private void writeName (String uri, String localName, String qName, boolean isElement) throws IOException { write(qName); } //////////////////////////////////////////////////////////////////// // Constants. //////////////////////////////////////////////////////////////////// private final Attributes EMPTY_ATTS = new AttributesImpl(); //////////////////////////////////////////////////////////////////// // Internal state. //////////////////////////////////////////////////////////////////// private boolean inCDATA = false; private int elementLevel = 0; private Writer output; private String encoding; private boolean writeXmlDecl = true; /** * This string will be written right after the xml declaration * without any escaping. Useful for generating a boiler-plate DOCTYPE decl * , PIs, and comments. */ private String header=null; private final CharacterEscapeHandler escapeHandler; private boolean startTagIsClosed = true; } // end of XMLWriter.java txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/output/XmlSerializer.java000066400000000000000000000103721157142111200255120ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.txw2.output; import com.sun.xml.txw2.TypedXmlWriter; /** * Low-level typeless XML writer driven from {@link TypedXmlWriter}. * *

* Applications can use one of the predefined implementations to * send TXW output to the desired location/format, or they can * choose to implement this interface for custom output. * *

* One {@link XmlSerializer} instance is responsible for writing * one XML document. * *

Call Sequence

* TXW calls methods on this interface in the following order: * *
 * WHOLE_SEQUENCE := startDocument ELEMENT endDocument
 * ELEMENT := beginStartTag writeXmlns* writeAttribute* endStartTag CONTENT endTag
 * CONTENT := (text|ELEMENT)*
 * 
* *

* TXW maintains all the in-scope namespace bindings and prefix allocation. * The {@link XmlSerializer} implementation should just use the prefix * specified. *

* * @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public interface XmlSerializer { /** * The first method to be called. */ void startDocument(); /** * Begins writing a start tag. * * @param uri * the namespace URI of the element. Can be empty but never be null. * @param prefix * the prefix that should be used for this element. Can be empty, * but never null. */ void beginStartTag(String uri,String localName,String prefix); /** * Writes an attribute. * * @param value * The value of the attribute. It's the callee's responsibility to * escape special characters (such as <, >, and &) in this buffer. * * @param uri * the namespace URI of the attribute. Can be empty but never be null. * @param prefix * the prefix that should be used for this attribute. Can be empty, * but never null. */ void writeAttribute(String uri,String localName,String prefix,StringBuilder value); /** * Writes a namespace declaration. * * @param uri * the namespace URI to be declared. Can be empty but never be null. * @param prefix * the prefix that is allocated. Can be empty but never be null. */ void writeXmlns(String prefix,String uri); /** * Completes the start tag. * * @param uri * the namespace URI of the element. Can be empty but never be null. * @param prefix * the prefix that should be used for this element. Can be empty, * but never null. */ void endStartTag(String uri,String localName,String prefix); /** * Writes an end tag. */ void endTag(); /** * Writes PCDATA. * * @param text * The character data to be written. It's the callee's responsibility to * escape special characters (such as <, >, and &) in this buffer. */ void text(StringBuilder text); /** * Writes CDATA. */ void cdata(StringBuilder text); /** * Writes a comment. * * @throws UnsupportedOperationException * if the writer doesn't support writing a comment, it can throw this exception. */ void comment(StringBuilder comment); /** * The last method to be called. */ void endDocument(); /** * Flush the buffer. * * This method is called when applications invoke {@link TypedXmlWriter#commit(boolean)} * method. If the implementation performs any buffering, it should flush the buffer. */ void flush(); } txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/output/package.html000066400000000000000000000001401157142111200243260ustar00rootroot00000000000000

Defines XmlSerializer and its built-in implementations. txw2-0.1+20070624/src/runtime/com/sun/xml/txw2/package.html000066400000000000000000000000651157142111200227740ustar00rootroot00000000000000

TXW runtime. txw2-0.1+20070624/src/test/000077500000000000000000000000001157142111200147175ustar00rootroot00000000000000txw2-0.1+20070624/src/test/IndentingXMLStreamWriterTest.java000066400000000000000000000013371157142111200232770ustar00rootroot00000000000000import com.sun.xml.txw2.output.IndentingXMLStreamWriter; import javax.xml.stream.XMLStreamWriter; import javax.xml.stream.XMLOutputFactory; /** * @author Kohsuke Kawaguchi */ public class IndentingXMLStreamWriterTest { public static void main(String[] args) throws Exception { XMLOutputFactory xof = XMLOutputFactory.newInstance(); XMLStreamWriter w = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(System.out)); w.writeStartDocument(); w.writeStartElement("foo"); w.writeEmptyElement("bar"); w.writeStartElement("x"); w.writeCharacters("body"); w.writeEndElement(); w.writeEndElement(); w.writeEndDocument(); w.close(); } } txw2-0.1+20070624/src/test/Main.java000066400000000000000000000024311157142111200164460ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ import com.sun.xml.txw2.TXW; import com.sun.xml.txw2.output.DumpSerializer; import javax.xml.namespace.QName; /** * @author Kohsuke Kawaguchi */ public class Main { public static void main(String[] args) { NameCards root = TXW.create(NameCards.class,new DumpSerializer(System.out)); NameCard nc = root.nameCard(); nc.id(3); nc.test2(new QName("uri","local")); nc.name("Kohsuke"); nc.address("California"); nc.test(new QName("","local")); root.commit(); } } txw2-0.1+20070624/src/test/NameCard.java000066400000000000000000000023761157142111200172440ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ import com.sun.xml.txw2.annotation.XmlAttribute; import com.sun.xml.txw2.annotation.XmlElement; import com.sun.xml.txw2.TypedXmlWriter; import javax.xml.namespace.QName; /** * @author Kohsuke Kawaguchi */ @XmlElement(ns="beep",value="nameCard") public interface NameCard extends TypedXmlWriter { void name( String name ); void address( String address ); @XmlElement("aaa") void test(QName v); @XmlAttribute void test2(QName n); @XmlAttribute("iid") void id( int id ); } txw2-0.1+20070624/src/test/NameCards.java000066400000000000000000000017731157142111200174270ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ import com.sun.xml.txw2.TypedXmlWriter; import com.sun.xml.txw2.annotation.XmlElement; /** * @author Kohsuke Kawaguchi */ public interface NameCards extends TypedXmlWriter { @XmlElement(ns="beep",value="name-card") NameCard nameCard(); } txw2-0.1+20070624/src/test/test/000077500000000000000000000000001157142111200156765ustar00rootroot00000000000000txw2-0.1+20070624/src/test/test/t1/000077500000000000000000000000001157142111200162225ustar00rootroot00000000000000txw2-0.1+20070624/src/test/test/t1/Foo.java000066400000000000000000000021041157142111200176050ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package test.t1; import com.sun.xml.txw2.TypedXmlWriter; import com.sun.xml.txw2.annotation.XmlElement; import com.sun.xml.txw2.annotation.XmlAttribute; /** * @author Kohsuke Kawaguchi */ @XmlElement(value="foo") public interface Foo extends TypedXmlWriter { Foo foo(); @XmlAttribute void hello(int min); } txw2-0.1+20070624/src/test/test/t1/Main.java000066400000000000000000000022061157142111200177510ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package test.t1; import com.sun.xml.txw2.TXW; import com.sun.xml.txw2.output.DumpSerializer; import javax.xml.namespace.QName; /** * @author Kohsuke Kawaguchi */ public class Main { public static void main(String[] args) { Foo root = TXW.create(Foo.class,new DumpSerializer(System.out)); root.hello(5); root.foo(); root.commit(); } } txw2-0.1+20070624/src/test/test/t1/package-info.java000066400000000000000000000015411157142111200214120ustar00rootroot00000000000000/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ @XmlNamespace("http://ns/") package test.t1; import com.sun.xml.txw2.annotation.XmlNamespace; txw2-0.1+20070624/txw2.iml000066400000000000000000000066771157142111200146000ustar00rootroot00000000000000 txw2-0.1+20070624/txw2.ipr000066400000000000000000000466361157142111200146100ustar00rootroot00000000000000 false false false false false false false txw2-0.1+20070624/wsdl11/000077500000000000000000000000001157142111200142645ustar00rootroot00000000000000txw2-0.1+20070624/wsdl11/build.xml000066400000000000000000000021511157142111200161040ustar00rootroot00000000000000 txw2-0.1+20070624/wsdl11/httpBindings.rnc000066400000000000000000000013421157142111200174250ustar00rootroot00000000000000# RELAX NG Schema for WSDL 1.1 HTTP Binding # # Written by Kohsuke Kawaguchi # $Id: httpBindings.rnc,v 1.1 2005-05-10 19:46:23 kohsuke Exp $ # # This schema is in public domain. Feel free to use it in anyway you can. # If you find a bug, please let me know. namespace local = "" namespace txw = "http://java.sun.com/txw" default namespace http = "http://schemas.xmlsoap.org/wsdl/http/" address = element address { attribute location {xsd:anyURI} } binding = element binding { attribute verb {xsd:NMTOKEN} } operation = element operation { attribute location {xsd:anyURI} } urlEncoded = element urlEncoded { element urlReplacement {empty} } # dummy start = address|binding|operation|urlEncoded txw2-0.1+20070624/wsdl11/mimeBindings.rnc000066400000000000000000000016071157142111200174010ustar00rootroot00000000000000# RELAX NG Schema for WSDL 1.1 HTTP Binding # # Written by Kohsuke Kawaguchi # $Id: mimeBindings.rnc,v 1.1 2005-05-10 19:46:23 kohsuke Exp $ # # This schema is in public domain. Feel free to use it in anyway you can. # If you find a bug, please let me know. namespace local = "" namespace txw = "http://java.sun.com/txw" default namespace mime = "http://schemas.xmlsoap.org/wsdl/mime/" content = element content { attribute type {text}?, attribute part {xsd:NMTOKEN}? } multipartRelated = element multipartRelated { element part { attribute name {xsd:NMTOKEN}, otherElement* }* } mimeXml = element mimeXml { attribute part {xsd:NMTOKEN}? } otherElement = element * - mime:* { mixed { anyElement* }, attribute * {text}* } anyElement = element * { mixed { anyElement* }, attribute * {text}* } # dummy start = content|multipartRelated|mimeXml txw2-0.1+20070624/wsdl11/soapBindings.rnc000066400000000000000000000022311157142111200174060ustar00rootroot00000000000000# RELAX NG Schema for WSDL 1.1 SOAP Binding # # Written by Kohsuke Kawaguchi # $Id: soapBindings.rnc,v 1.1 2005-05-10 19:46:23 kohsuke Exp $ # # This schema is in public domain. Feel free to use it in anyway you can. # If you find a bug, please let me know. namespace local = "" namespace txw = "http://java.sun.com/txw" default namespace soap = "http://schemas.xmlsoap.org/wsdl/soap/" binding = element binding { attribute transport {xsd:anyURI}?, attribute style {styleChoice}? } styleChoice = "rpc"|"document" operation = element operation { attribute soapAction {xsd:anyURI}?, attribute style {styleChoice}? } body = element body { bodyType } bodyType = attribute encodingStyle {xsd:anyURI}?, attribute parts {xsd:NMTOKENS}?, attribute use {useChoice}?, attribute namespace {xsd:anyURI}? useChoice = "literal"|"encoded" fault = element fault { bodyType } header = element header { attribute message {xsd:QName}, bodyType, element headerFault { attribute message {xsd:QName}, bodyType } } address = element address { attribute location {xsd:anyURI} } # dummy start = address|header|fault|body|operation|binding txw2-0.1+20070624/wsdl11/src/000077500000000000000000000000001157142111200150535ustar00rootroot00000000000000txw2-0.1+20070624/wsdl11/src/WsdlTest.java000066400000000000000000000012341157142111200174670ustar00rootroot00000000000000 import com.sun.xml.txw2.TXW; import com.sun.xml.txw2.output.StreamSerializer; import wsdl.Definitions; import javax.xml.namespace.QName; /** * @author Kohsuke Kawaguchi */ public class WsdlTest { public static void main(String[] args) { Definitions root = TXW.create(Definitions.class,new StreamSerializer(System.out)); root._namespace("http://schemas.xmlsoap.org/wsdl/","wsdl"); root._namespace("foo","bar"); root._comment("GENERATED. DO NOT MODIFY"); root._pcdata("\n"); root.targetNamespace("abc"); root.message().name("msg1"); root.message().name("msg2"); root.commit(); } } txw2-0.1+20070624/wsdl11/wsdl.rnc000066400000000000000000000054401157142111200157440ustar00rootroot00000000000000# RELAX NG Schema for WSDL 1.1 # # Written by Kohsuke Kawaguchi # $Id: wsdl.rnc,v 1.1 2005-05-10 19:46:23 kohsuke Exp $ # # This schema is in public domain. Feel free to use it in anyway you can. # If you find a bug, please let me know. default namespace wsdl = "http://schemas.xmlsoap.org/wsdl/" namespace local = "" namespace txw = "http://java.sun.com/txw" start = definitions documentation = element documentation { mixed { otherElement* }, attribute * {text}* } [txw:mode="inherit"] documented = documentation? [txw:mode="inherit"] openAtts = documented, attribute * - local:* {text}* definitions = element definitions { documented, import*, types*, message*, portType*, binding*, service*, otherElement*, attribute targetNamespace {xsd:anyURI}?, attribute name {xsd:NMTOKEN}? } import = element import { documented, attribute namespace {xsd:anyURI}, attribute location {xsd:anyURI} } types = element types { documented, otherElement* } message = element message { documented, part*, attribute name {xsd:NMTOKEN} } part = element part { openAtts, attribute name {xsd:NMTOKEN}, ( attribute type {xsd:QName} | attribute element {xsd:QName} ) } portType = element portType { documented, operation*, attribute name {xsd:NCName} } operation = element operation { documented, attribute name {xsd:NCName}, ( element one-way-operation { input } | element request-response-operation { input, output, fault* } | element solicit-response-operation { output, input, fault* } | element notification-operation { output } ) } input = element input { paramType } output = element output { paramType } fault = element fault { faultType } [txw:mode="inherit"] paramType = documented, attribute name {xsd:NMTOKEN}?, attribute message {xsd:QName} [txw:mode="inherit"] faultType = documented, attribute name {xsd:NMTOKEN}, attribute message {xsd:QName} [txw:mode="inherit"] startWithExtensionsType = documented, otherElement* binding = element binding { startWithExtensionsType, element operation { binding_operationType }*, attribute name {xsd:NCName}, attribute type {xsd:QName} } binding_operationType = attribute name {xsd:NCName}, startWithExtensionsType, element input {startWithExtensionsType}?, element output {startWithExtensionsType}?, element fault { attribute name {xsd:NMTOKEN}, startWithExtensionsType }* service = element service { attribute name {xsd:NCName}, documented, port* } port = element port { attribute name {xsd:NCName}, attribute binding {xsd:QName}, attribute arrayType {text}?, documented, otherElement? } otherElement = element * - wsdl:* { mixed { anyElement* }, attribute * {text}* } anyElement = element * { mixed { anyElement* }, attribute * {text}* } txw2-0.1+20070624/wsdl11/wsdl11.iml000066400000000000000000000015461157142111200161100ustar00rootroot00000000000000 txw2-0.1+20070624/xmlschema/000077500000000000000000000000001157142111200151325ustar00rootroot00000000000000txw2-0.1+20070624/xmlschema/build.xml000066400000000000000000000015161157142111200167560ustar00rootroot00000000000000 txw2-0.1+20070624/xmlschema/src/000077500000000000000000000000001157142111200157215ustar00rootroot00000000000000txw2-0.1+20070624/xmlschema/src/XsdTest.java000066400000000000000000000016211157142111200201620ustar00rootroot00000000000000 import com.sun.tools.jxc.gen.xmlschema.Schema; import com.sun.tools.jxc.gen.xmlschema.TopLevelElement; import com.sun.xml.txw2.TXW; import com.sun.xml.txw2.output.StreamSerializer; import javax.xml.namespace.QName; /** * @author Kohsuke Kawaguchi */ public class XsdTest { private static final StringBuilder newline = new StringBuilder("\n"); public static void main(String[] args) { Schema root = TXW.create(Schema.class,new StreamSerializer(System.out)); root._namespace("http://www.w3.org/2001/XMLSchema","xs"); root.version("1.0").targetNamespace("http://foobar/"); root._pcdata(newline); root.complexType().name("ink").sequence(); root._pcdata(newline); TopLevelElement e = root.element(); e.name("foo").type(new QName("abc","def")); e.commit(); System.out.print("[committed]"); root.commit(); } } txw2-0.1+20070624/xmlschema/xmlschema-for-jaxb.rng000066400000000000000000001324521157142111200213400ustar00rootroot00000000000000 RELAX NG schema for XML Schema by Jeni Tennison. Based on XML Schema Part I: Structures Recommendation and XML Schema Part II: Datatypes. Amended to comply with 10 August 2001 Tutorial. Removed key attributes. Replaced not element with except elements. Replaced multiple consecutive optional attributes to use the zeroOrMore/choice pattern. Removed interleave elements inside list elements (which are no longer permitted). This allows any number of attributes that are not in the XML Schema namespace or are in no namespace. This is somewhat more complicated than the XML Schema anyAttribute equivalent. This allows any number of attributes that are not in the XML Schema namespace or are in no namespace, an optional id attribute of type ID, and an optional annotation element. This is used as the basis for many element content models. This gives the content model of the top level of the schema. This gives the components that can be redefined within the redefine element. They also occur at the top level of the schema. This gives the values for the various form attributes: elementFormDefault and attributeFormDefault on the schema element, and the form attributes on the element and attribute elements. qualified unqualified This gives the values that can be taken in the lists used to control derivation by extension or restriction (this is 'reduced' derivation because some derivation can involve substitution). This RELAX NG schema, like the XML Schema Recommendation here, allows the keywords 'extension' and 'restriction' to be repeated any number of times. extension restriction This specifies the possible values for attributes that control derivation. #all This is the beginning point for the schema, and defines the schema element. This gives the value type for the maxOccurs attribute, which may be a non-negative number or the keyword 'unbounded'. unbounded This specifies the occurs attributes, minOccurs and maxOccurs, as they are normally used. This gives the possible content of complex types. This gives the particles that can make up a model group. This specifies the relationship between fixed and default attributes on element and attribute elements - if one is present, then the other cannot be. This is a constraint that cannot be specified using XML Schema. This specifies the relationship between the type attribute and the simpleType element child of attribute elements - if one is present, then the other cannot be, although it is possible for neither to be allowed. This describes attribute elements when used in a local context. They have an optional use attribute, possibly a fixed or default attribute, and then can either have a ref attribute (referring to a top-level attribute) or a name attribute with an optional form attribute and specifying an attribute type. optional prohibited required This describes attribute elements when used at the top level of the schema. They must have a name, may have a fixed or default attribute, and specify their type through a type attribute or child simpleType element. The name attribute of each attribute element that appears at the top level of the schema is unique. This gives the model group for specifying the attributes in a complex type, an extension or restriction. This specifies the anyAttribute wildcard. This specifies the content of a complexType element. As children, it can have a simpleContent, a complexContent or a model group. Only if it has one of the latter two, may it have a mixed attribute. This latter constraint is something that cannot be specified in XML Schema. This specifies the basic content of a complexType element. This specifies the model for a complexType element at the top level of the schema. It must have a name, which provides a unique identifier within the type symbol space. It may have abstract, block and/or final attributes. Otherwise it is the same as other complexTypes. This specifies the model for a local complexType element. This describes a restriction element within a complexContent element (i.e. one that restricts a complex type). It has a base attribute, may contain a model group and may contain attribute declarations of various sorts. This specifies the basic model for an extension element: adding a required base attribute to the model used for most components. This describes an extension element within a complexContent element (i.e. one that restricts a complex type). It may contain a model group and may contain attribute declarations of various sorts. This describes a complexContent element. It may have a mixed attribute, and either a restriction or extension element as content. This describes a restriction element that appears within a simpleContent or simpleType element (i.e. one that restricts a simple type). Its content follows the simple restriction model that is detailed below, and may include attribute declarations. This describes an extension element that appears within a simpleContent element (i.e. one that extends a simple type). Like other extensions, it has a base type, but it can only be used to add attributes. This describes a simpleContent element, whose content can either hold a restriction or extension element. This gives the possible values for block attributes on element elements, which includes substitution amongst the list of possible values. This RELAX NG schema, like the XML Schema Recommendation, allows each of the keywords 'extension', 'restriction' and 'substitution' to occur more than once within the list. #all extension restriction substitution This describes the basic content model of an element element. It is annotated, may have a fixed or default attribute, and may have nillable and/or block attributes. Its type may be specified through a type attribute, a local simple type or a local complex type - the choice between these methods is something that cannot be indicated with XML Schema. This content is optionally followed by some identify constraints. This describes an element element that appears at the top level of the schema. On top of the basic content for an element element, it has to have a name, which is a unique identifier in the element symbol space. It may have substitutionGroup, abstract and/or final attributes. This describes an element element that appears locally, within a complexType or group element. It may have minOccurs and/or maxOccurs attributes. If it has a ref attribute, then that's all it can have. Otherwise, it must have a name and specifies its type in the same way as the basic element content model described above. It may in this case also have a form element. These constraints on local elements cannot be described within XML Schema. This describes an group element that appears at the top level of the schema. It must have a name attribute, and must have one of an all, choice or sequence element child. This describes group element that occurs locally, referring to a top-level named group. It may have occurrence attributes, and must have a ref attribute. This gives the content of a model group (not a group element) in the normal run of things. It has occurrence attributes and any number of particles within it. This gives the content of a model group (not a group element) within a named group - it differs from the above in that it doesn't have any occurrence attributes. This describes an all element that appears outside a named group (i.e. as the content of a complexType element). It has the standard model for an all element, but adds minOccurs and maxOccurs attributes which can only take certain values. This describes a choice element that appears outside a named group. This describes a sequence element that appears outside a named group. This describes a wildcard element (i.e. any or anyAttribute). The namespace attribute can take a list URIs interspersed with the keywords '##targetNamespace' and/or '##local'. This RELAX NG schema, like the XML Schema Recommendation, allows the keywords to be specified more than once each within the list, if they're given. This model also specifies the processContents attribute. ##any ##other ##targetNamespace ##local lax skip strict This describes an any element as a wildcard. This describes an attributeGroup element as it appears at the top level of the schema. It must have a name attribute, and then contains attribute declarations. This describes an attributeGroup element as it appears within a complex type. It must have a ref attribute. This describes an include element, which must have a schemaLocation attribute. This describes a redefine element, which must have a schemaLocation attribute and can then contain any mix of annotations and redefinable components. This describes an import element that's used when its parent schema element specifies a targetNamespace. In these cases, the namespace attribute on the import element is optional. This describes a selector element. The xpath attribute is a simplified XPath - the regular expression given here is the one from the XML Schema for XML Schema. (\.//)?(((child::)?((\i\c*:)?(\i\c*|\*)))|\.)(/(((child::)?((\i\c*:)?(\i\c*|\*)))|\.))*(\|(\.//)?(((child::)?((\i\c*:)?(\i\c*|\*)))|\.)(/(((child::)?((\i\c*:)?(\i\c*|\*)))|\.))*)* This describes a field element. The xpath attribute is a simplified XPath - the regular expression given here is the one from the XML Schema for XML Schema. (\.//)?((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)/)*((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)|((attribute::|@)((\i\c*:)?(\i\c*|\*))))(\|(\.//)?((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)/)*((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)|((attribute::|@)((\i\c*:)?(\i\c*|\*)))))* This gives the basic content for identity constraints - a name attribute that uniquely identifies the identity constraint, a selector element and one or more field elements. This gives a model group for the three identity constraint elements, used within the content of element elements. This describes a unique element. This describes a key element. This describes a keyref element. This describes a notation element. The names of notation elements are unique in the notation symbol space. The public attribute is required, and the system attribute is optional. This is designed to describe the content of the appinfo elements in the schema. At the moment this allows any mixed content without validation. Note that this is fairly complex compared to the XML Schema equivalent, which would be a single any element. This describes an appinfo element. It has an optional source attribute and can currently contain anything at all. This is designed to describe the content of the documentation elements in the schema. At the moment this allows any mixed content without validation. Note that this is fairly complex compared to the XML Schema equivalent, which would be a single any element. This describes a documentation element. It has optional source and xml:lang attributes and can currently contain anything at all. This describes an annotation element. It can have any attributes, may have an id attribute, and contains any number of documentation or appinfo elements. This gives the various types of derivation of simple types. This specifies the values of the final attribute for simple types. This RELAX NG schema for XML Schema, like the XML Schema Recommendation, allows the keywords 'list', 'union' and 'restriction' to appear more than once within the list. #all list union restriction This gives the basic content of a simple type. This describes a simpleType element as it appears at the top level of the schema. It has to have a name attribute and may have a final attribute. This describes a simpleType element as it appears within an attribute or element. This describes the relationship between the various range facets. Only one of minExclusive and minInclusive can be present, and only one of maxExclusive and maxInclusive can be present. This is a constraint that can't easily be expressed using XML Schema. This RELAX NG schema for XML Schema is a little more restrictive than the XML Schema Recommendation in that it also forces there to be a maximum of one of each of these types of facets. This specifies optional totalDigits and fractionDigits elements. This RELAX NG schema for XML Schema is a little more restrictive than the XML Schema Recommendation in that it also forces there to be a maximum of one of each of these types of facets. This specifies optional length, minLength and maxLength elements. This RELAX NG schema for XML Schema is a little more restrictive than the XML Schema Recommendation in that it also forces there to be a maximum of one of each of these types of facets, and says that if a length element is given, then neither minLength nor maxLength should be present. This specifies zero or more enumeration or pattern elements and an optional whiteSpace element. This RELAX NG schema for XML Schema is a little more restrictive than the XML Schema Recommendation in that it also forces there to be a maximum of one whiteSpace element within the facets. Note that the whiteSpace facet is constrained to have a value of 'collapse'. This specifies the types of facets that are valid in restrictions on the built-in data types. This can only perform rudimentary checking, but should be enough in most circumstances. Note that for xs:anySimpleType and xs:string, the whiteSpace facet can take any value, for xs:normalizedString it can be 'replace' or 'collapse', and for all other built-in types it has to be 'collapse'. This describes a list element. It can either specify a local simple type or have a itemType attribute. This constraint cannot be expressed in XML Schema. This describes a union element. If the memberTypes attribute is missing or empty, then it must contain one or more simpleType elements; if it's present, then it can contain simpleType elements or list simple types in the memberTypes attribute. This constraint cannot be expressed in XML Schema. This is the basic content of a facet. It has an optional fixed attribute. This is the content of a facet that cannot be fixed (enumeration or pattern). It has a value attribute that can take any kind of value. This is the content of a range facet. The value must be one of the data types shown (as these are the only types of data that accept ranges). I haven't gone so far as to indicate the data type of the value attribute of a range facet according to the base type as this would be very complicated (although it would be possible in RELAX NG). This describes a minExclusive element. This describes a minInclusive element. This describes a maxExclusive element. This describes a maxInclusive element. This is the content of a numerical facet. This describes a totalDigits element. The value attribute must take a positive integer. This describes a fractionDigits element. This describes a length element. This describes a minLength element. This describes a maxLength element. This describes an enumeration element. This describes a whiteSpace element that can take any of the permitted values. preserve replace collapse This describes a whiteSpace element that can only take the values 'replace' or 'collapse'. replace collapse This describes a whiteSpace element that can only take the value 'collapse'. collapse This describes a pattern element. txw2-0.1+20070624/xmlschema/xmlschema.iml000066400000000000000000000015461157142111200176240ustar00rootroot00000000000000 txw2-0.1+20070624/xmlschema/xmlschema.rng000066400000000000000000001355761157142111200176440ustar00rootroot00000000000000 RELAX NG schema for XML Schema by Jeni Tennison. Based on XML Schema Part I: Structures Recommendation and XML Schema Part II: Datatypes. Amended to comply with 10 August 2001 Tutorial. Removed key attributes. Replaced not element with except elements. Replaced multiple consecutive optional attributes to use the zeroOrMore/choice pattern. Removed interleave elements inside list elements (which are no longer permitted). This allows any number of attributes that are not in the XML Schema namespace or are in no namespace. This is somewhat more complicated than the XML Schema anyAttribute equivalent. This allows any number of attributes that are not in the XML Schema namespace or are in no namespace, an optional id attribute of type ID, and an optional annotation element. This is used as the basis for many element content models. This gives the content model of the top level of the schema. This gives the components that can be redefined within the redefine element. They also occur at the top level of the schema. This gives the values for the various form attributes: elementFormDefault and attributeFormDefault on the schema element, and the form attributes on the element and attribute elements. qualified unqualified This gives the values that can be taken in the lists used to control derivation by extension or restriction (this is 'reduced' derivation because some derivation can involve substitution). This RELAX NG schema, like the XML Schema Recommendation here, allows the keywords 'extension' and 'restriction' to be repeated any number of times. extension restriction This specifies the possible values for attributes that control derivation. #all This is the beginning point for the schema, and defines the schema element. This gives the value type for the maxOccurs attribute, which may be a non-negative number or the keyword 'unbounded'. unbounded This specifies the occurs attributes, minOccurs and maxOccurs, as they are normally used. This gives the possible content of complex types. This gives the particles that can make up a model group. This specifies the relationship between fixed and default attributes on element and attribute elements - if one is present, then the other cannot be. This is a constraint that cannot be specified using XML Schema. This specifies the relationship between the type attribute and the simpleType element child of attribute elements - if one is present, then the other cannot be, although it is possible for neither to be allowed. This describes attribute elements when used in a local context. They have an optional use attribute, possibly a fixed or default attribute, and then can either have a ref attribute (referring to a top-level attribute) or a name attribute with an optional form attribute and specifying an attribute type. optional prohibited required This describes attribute elements when used at the top level of the schema. They must have a name, may have a fixed or default attribute, and specify their type through a type attribute or child simpleType element. The name attribute of each attribute element that appears at the top level of the schema is unique. This gives the model group for specifying the attributes in a complex type, an extension or restriction. This specifies the anyAttribute wildcard. This specifies the content of a complexType element. As children, it can have a simpleContent, a complexContent or a model group. Only if it has one of the latter two, may it have a mixed attribute. This latter constraint is something that cannot be specified in XML Schema. This specifies the basic content of a complexType element. This specifies the model for a complexType element at the top level of the schema. It must have a name, which provides a unique identifier within the type symbol space. It may have abstract, block and/or final attributes. Otherwise it is the same as other complexTypes. This specifies the model for a local complexType element. This describes a restriction element within a complexContent element (i.e. one that restricts a complex type). It has a base attribute, may contain a model group and may contain attribute declarations of various sorts. This specifies the basic model for an extension element: adding a required base attribute to the model used for most components. This describes an extension element within a complexContent element (i.e. one that restricts a complex type). It may contain a model group and may contain attribute declarations of various sorts. This describes a complexContent element. It may have a mixed attribute, and either a restriction or extension element as content. This describes a restriction element that appears within a simpleContent or simpleType element (i.e. one that restricts a simple type). Its content follows the simple restriction model that is detailed below, and may include attribute declarations. This describes an extension element that appears within a simpleContent element (i.e. one that extends a simple type). Like other extensions, it has a base type, but it can only be used to add attributes. This describes a simpleContent element, whose content can either hold a restriction or extension element. This gives the possible values for block attributes on element elements, which includes substitution amongst the list of possible values. This RELAX NG schema, like the XML Schema Recommendation, allows each of the keywords 'extension', 'restriction' and 'substitution' to occur more than once within the list. #all extension restriction substitution This describes the basic content model of an element element. It is annotated, may have a fixed or default attribute, and may have nillable and/or block attributes. Its type may be specified through a type attribute, a local simple type or a local complex type - the choice between these methods is something that cannot be indicated with XML Schema. This content is optionally followed by some identify constraints. This describes an element element that appears at the top level of the schema. On top of the basic content for an element element, it has to have a name, which is a unique identifier in the element symbol space. It may have substitutionGroup, abstract and/or final attributes. This describes an element element that appears locally, within a complexType or group element. It may have minOccurs and/or maxOccurs attributes. If it has a ref attribute, then that's all it can have. Otherwise, it must have a name and specifies its type in the same way as the basic element content model described above. It may in this case also have a form element. These constraints on local elements cannot be described within XML Schema. This describes an group element that appears at the top level of the schema. It must have a name attribute, and must have one of an all, choice or sequence element child. This describes group element that occurs locally, referring to a top-level named group. It may have occurrence attributes, and must have a ref attribute. This gives the content of a model group (not a group element) in the normal run of things. It has occurrence attributes and any number of particles within it. This gives the content of a model group (not a group element) within a named group - it differs from the above in that it doesn't have any occurrence attributes. This gives the content of an all element. It contains element elements that are similar to local element elements, but the minOccurs and maxOccurs attributes can only take values of 0 or 1. 0 1 0 1 This describes an all element that appears outside a named group (i.e. as the content of a complexType element). It has the standard model for an all element, but adds minOccurs and maxOccurs attributes which can only take certain values. 0 1 1 This describes a choice element that appears outside a named group. This describes a sequence element that appears outside a named group. This describes a wildcard element (i.e. any or anyAttribute). The namespace attribute can take a list URIs interspersed with the keywords '##targetNamespace' and/or '##local'. This RELAX NG schema, like the XML Schema Recommendation, allows the keywords to be specified more than once each within the list, if they're given. This model also specifies the processContents attribute. ##any ##other ##targetNamespace ##local lax skip strict This describes an any element as a wildcard. This describes an attributeGroup element as it appears at the top level of the schema. It must have a name attribute, and then contains attribute declarations. This describes an attributeGroup element as it appears within a complex type. It must have a ref attribute. This describes an include element, which must have a schemaLocation attribute. This describes a redefine element, which must have a schemaLocation attribute and can then contain any mix of annotations and redefinable components. This describes an import element that's used when its parent schema element specifies a targetNamespace. In these cases, the namespace attribute on the import element is optional. This describes a selector element. The xpath attribute is a simplified XPath - the regular expression given here is the one from the XML Schema for XML Schema. (\.//)?(((child::)?((\i\c*:)?(\i\c*|\*)))|\.)(/(((child::)?((\i\c*:)?(\i\c*|\*)))|\.))*(\|(\.//)?(((child::)?((\i\c*:)?(\i\c*|\*)))|\.)(/(((child::)?((\i\c*:)?(\i\c*|\*)))|\.))*)* This describes a field element. The xpath attribute is a simplified XPath - the regular expression given here is the one from the XML Schema for XML Schema. (\.//)?((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)/)*((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)|((attribute::|@)((\i\c*:)?(\i\c*|\*))))(\|(\.//)?((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)/)*((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)|((attribute::|@)((\i\c*:)?(\i\c*|\*)))))* This gives the basic content for identity constraints - a name attribute that uniquely identifies the identity constraint, a selector element and one or more field elements. This gives a model group for the three identity constraint elements, used within the content of element elements. This describes a unique element. This describes a key element. This describes a keyref element. This describes a notation element. The names of notation elements are unique in the notation symbol space. The public attribute is required, and the system attribute is optional. This is designed to describe the content of the appinfo elements in the schema. At the moment this allows any mixed content without validation. Note that this is fairly complex compared to the XML Schema equivalent, which would be a single any element. This describes an appinfo element. It has an optional source attribute and can currently contain anything at all. This is designed to describe the content of the documentation elements in the schema. At the moment this allows any mixed content without validation. Note that this is fairly complex compared to the XML Schema equivalent, which would be a single any element. This describes a documentation element. It has optional source and xml:lang attributes and can currently contain anything at all. This describes an annotation element. It can have any attributes, may have an id attribute, and contains any number of documentation or appinfo elements. This gives the various types of derivation of simple types. This specifies the values of the final attribute for simple types. This RELAX NG schema for XML Schema, like the XML Schema Recommendation, allows the keywords 'list', 'union' and 'restriction' to appear more than once within the list. #all list union restriction This gives the basic content of a simple type. This describes a simpleType element as it appears at the top level of the schema. It has to have a name attribute and may have a final attribute. This describes a simpleType element as it appears within an attribute or element. This describes the relationship between the various range facets. Only one of minExclusive and minInclusive can be present, and only one of maxExclusive and maxInclusive can be present. This is a constraint that can't easily be expressed using XML Schema. This RELAX NG schema for XML Schema is a little more restrictive than the XML Schema Recommendation in that it also forces there to be a maximum of one of each of these types of facets. This specifies optional totalDigits and fractionDigits elements. This RELAX NG schema for XML Schema is a little more restrictive than the XML Schema Recommendation in that it also forces there to be a maximum of one of each of these types of facets. This specifies optional length, minLength and maxLength elements. This RELAX NG schema for XML Schema is a little more restrictive than the XML Schema Recommendation in that it also forces there to be a maximum of one of each of these types of facets, and says that if a length element is given, then neither minLength nor maxLength should be present. This specifies zero or more enumeration or pattern elements and an optional whiteSpace element. This RELAX NG schema for XML Schema is a little more restrictive than the XML Schema Recommendation in that it also forces there to be a maximum of one whiteSpace element within the facets. Note that the whiteSpace facet is constrained to have a value of 'collapse'. This specifies the types of facets that are valid in restrictions on the built-in data types. This can only perform rudimentary checking, but should be enough in most circumstances. Note that for xs:anySimpleType and xs:string, the whiteSpace facet can take any value, for xs:normalizedString it can be 'replace' or 'collapse', and for all other built-in types it has to be 'collapse'. This describes a list element. It can either specify a local simple type or have a itemType attribute. This constraint cannot be expressed in XML Schema. This describes a union element. If the memberTypes attribute is missing or empty, then it must contain one or more simpleType elements; if it's present, then it can contain simpleType elements or list simple types in the memberTypes attribute. This constraint cannot be expressed in XML Schema. This is the basic content of a facet. It has an optional fixed attribute. This is the content of a facet that cannot be fixed (enumeration or pattern). It has a value attribute that can take any kind of value. This is the content of a range facet. The value must be one of the data types shown (as these are the only types of data that accept ranges). I haven't gone so far as to indicate the data type of the value attribute of a range facet according to the base type as this would be very complicated (although it would be possible in RELAX NG). This describes a minExclusive element. This describes a minInclusive element. This describes a maxExclusive element. This describes a maxInclusive element. This is the content of a numerical facet. This describes a totalDigits element. The value attribute must take a positive integer. This describes a fractionDigits element. This describes a length element. This describes a minLength element. This describes a maxLength element. This describes an enumeration element. This describes a whiteSpace element that can take any of the permitted values. preserve replace collapse This describes a whiteSpace element that can only take the values 'replace' or 'collapse'. replace collapse This describes a whiteSpace element that can only take the value 'collapse'. collapse This describes a pattern element.